Repository navigation
refactor: move address resolution and ownership to AddressManager - #3590
vladopajic wants to merge 10 commits into
Conversation
|
/review |
|
OpenCodeReview · Complete review: 31 of 31 selected files covered 11 findings.
📄
|
| File | Result |
|---|---|
libp2p/protocols/connectivity/dcutr/server.nim |
Reviewed |
libp2p/protocols/connectivity/autonatv2/server.nim |
Reviewed |
tests/integration/autotls_docker/test_autotls_docker.nim |
Reviewed |
tests/libp2p/test_peer_info.nim |
Reviewed |
tests/libp2p/services/test_autorelay.nim |
Reviewed |
tests/libp2p/protocols/test_autonat_v2_service.nim |
Reviewed |
libp2p/autotls/service.nim |
Reviewed |
tests/libp2p/services/test_hp.nim |
Reviewed |
tests/libp2p/services/test_private_addr_filter.nim |
Reviewed |
libp2p/services/natservice.nim |
Reviewed |
libp2p/switch.nim |
Reviewed |
tests/libp2p/test_switch_accept.nim |
Reviewed |
libp2p/services/autorelayservice.nim |
Reviewed |
tests/libp2p/test_switch.nim |
Reviewed |
libp2p/protocols/connectivity/autonatv2/service.nim |
Reviewed |
tests/libp2p/test_address_resolution.nim |
Reviewed |
libp2p/address_manager.nim |
Reviewed |
tests/libp2p/discovery/test_mdns.nim |
Reviewed |
libp2p/services/hpservice.nim |
Reviewed |
tests/libp2p/autotls/test_service.nim |
Reviewed |
tests/libp2p/test_peer_store_component.nim |
Reviewed |
libp2p/services/wildcardresolverservice.nim |
Reviewed |
tests/libp2p/test_address_manager.nim |
Reviewed |
libp2p/protocols/connectivity/autonat/service.nim |
Reviewed |
libp2p/services/mdns.nim |
Reviewed |
libp2p/peerinfo.nim |
Reviewed |
tests/libp2p/kademlia/test_automode_autonat_v2.nim |
Reviewed |
libp2p/builders.nim |
Reviewed |
tests/libp2p/protocols/test_identify.nim |
Reviewed |
tests/tools/lifecycle.nim |
Reviewed |
tests/libp2p/services/test_natservice.nim |
Reviewed |
Model: qwen4-max
Review generated in: 13m 47s
| if not service.owner.isNil() and service.owner.peerInfo == peer: | ||
| service.owner.addressManager.boundAddrs | ||
| else: | ||
| peer.addrs |
There was a problem hiding this comment.
The new branch dereferences service.owner.addressManager without a nil check. owner is set in the public tryStart(service, switch), which accepts any Switch — including hand-constructed ones without an addressManager (a construction that worked before this change, as the previous test fixtures show). Switch.start only enforces the manager via doAssert, which is compiled out in release builds, so a nil manager here becomes a nil-access Defect inside the async advertise/query path rather than a clean error. Since the guard already anticipates partially wired state (owner.isNil()), extend it to the manager and fall back to peer.addrs.
Suggestion:
| if not service.owner.isNil() and service.owner.peerInfo == peer: | |
| service.owner.addressManager.boundAddrs | |
| else: | |
| peer.addrs | |
| if not service.owner.isNil() and not service.owner.addressManager.isNil() and | |
| service.owner.peerInfo == peer: | |
| service.owner.addressManager.boundAddrs | |
| else: | |
| peer.addrs |
There was a problem hiding this comment.
addressManager needs to be set it is core component of Switch, if addressManager is not set we should better catch that as Defect.
| var initial = await s.addressManager.endBatchAndRefresh() | ||
| while initial.stale or initial.revision != s.addressManager.revision: | ||
| if s.stopping or s.addressManager.shuttingDown: | ||
| raise newException(LPError, "switch stopped during startup") | ||
| initial = await s.addressManager.resolve() |
There was a problem hiding this comment.
Unbounded stale-retry loop can starve startup (and address publication) under connection churn. The accept loops are already running at this point, and every inbound identify observation calls addObservation → invalidate() → revision++. resolve() reports stale whenever the revision moved during the mapper chain, and mappers such as NAT port mapping await network I/O for seconds (mappingTimeout defaults to 10s). On a node with steady inbound traffic, each resolve can come back stale, so this while loop (and the identical continue loop in refreshAddresses) can spin indefinitely while holding addressRefreshLock — start() never completes, explicit refreshAddresses() callers block, and every retry re-executes side-effectful mappers (repeated map/unmap requests against the router). Consider bounding the retries (e.g. publish the last consistent resolution after N attempts, or snapshot/suppress observation-driven invalidations during the initial resolution) instead of requiring a fully quiet revision window.
|
/review |
|
OpenCodeReview · Complete review: 31 of 31 selected files covered 6 findings.
Review infoReviewed commits:
Model: |
| self.shuttingDown = false | ||
| self.started = true | ||
| self.hasBoundAddrs = false | ||
| self.actualAddrs.setLen(0) |
There was a problem hiding this comment.
beginShutdown() sets shuttingDown = true but deliberately leaves started = true (only stop() clears it). That makes the unchanged if self.started: return guard at the top of start() return early, so this new self.shuttingDown = false reset is unreachable on the beginShutdown() → start() path. Since beginShutdown is exported, a caller that aborts teardown and restarts without a full stop() gets a silent no-op: isRunning stays false, every resolve() returns stale, and no verification heartbeat runs — permanently, until stop() is called. Guard with if self.started and not self.shuttingDown: return (and consider resetting batchDepth here too, since an interrupted batch otherwise keeps notifications suppressed after restart).
There was a problem hiding this comment.
this happens on start() → beginShutdown() → start() sequence which is not really normal nor expected to happen.
normal sequence is start() → beginShutdown() → stop() → start()
|
/review |
|
OpenCodeReview · Complete review: 32 of 32 selected files covered 9 findings.
Review infoReviewed commits:
Model: |
| self.hasBoundAddrs = false | ||
| self.actualAddrs.setLen(0) | ||
| self.invalidate() |
There was a problem hiding this comment.
start() resets the bound-address lifecycle state but not batchDepth; only stop() zeroes it, and beginShutdown() (the documented pre-teardown entry point) deliberately leaves it untouched. A consumer that opens a batch and then aborts through beginShutdown() — or whose Switch.stop() propagates CancelledError before reaching addressManager.stop() — keeps batchDepth > 0 across a restart. From then on invalidate() never emits onAddressChange, notifyReachability() returns early, and endBatchAndRefresh() never reaches the outermost close, so addresses are never refreshed or republished again. Reset the batch depth as part of the start transition (or close open batches in beginShutdown).
Suggestion:
| self.hasBoundAddrs = false | |
| self.actualAddrs.setLen(0) | |
| self.invalidate() | |
| self.hasBoundAddrs = false | |
| self.actualAddrs.setLen(0) | |
| self.batchDepth = 0 | |
| self.invalidate() |
There was a problem hiding this comment.
suggested reset in start() would break the current switch startup sequence:
Switch.start() calls beginBatch() before addressManager.start(). resetting batchDepth there would discard that active batch, so the later endBatchAndRefresh() would hit its assertion.
| s.addressManager.beginShutdown() | ||
| s.addressRefreshRequested = false |
There was a problem hiding this comment.
stop() now dereferences s.addressManager here, before the doAssert not s.addressManager.isNil(), MissingAddressManager guard near the end of the proc. For switches built field-by-field without a manager (the case the MissingAddressManager assert was added for, per the comment on the constant: TorSwitch/SwitchStub), stop now crashes with a raw nil-access defect instead of the intended diagnostic. Move the assert to the top of stop() (as start() does) so the guard precedes the first use.
Suggestion:
| s.addressManager.beginShutdown() | |
| s.addressRefreshRequested = false | |
| doAssert not s.addressManager.isNil(), MissingAddressManager | |
| s.addressManager.beginShutdown() | |
| s.addressRefreshRequested = false |
There was a problem hiding this comment.
same as in other comments, addressManager must be set as it is core component of Switch. if there is Defect caused bu nil pointer de reference then let it be. it is systemic issue that must be fixed.
8fbfa5e to
6f1051d
Compare
|
/review |
|
@greptileai review this PR |
|
[High impact] The PR appears safe to merge; no new blocking issue remains.
|
|
OpenCodeReview · Complete review: 32 of 32 selected files covered 5 findings.
Review infoReviewed commits:
Model: |
| let boundAddrs = switch.boundAddrs() | ||
| if boundAddrs.len > 0: | ||
| let addrs = await self.peerInfo.expandAddrs(boundAddrs) | ||
| switch.addressManager.setBoundAddrs(boundAddrs) |
There was a problem hiding this comment.
The AutoTLS service now writes the authoritative bound-address state that Switch owns (Switch.start commits the full set under addressRefreshLock after all transports start). The guard above only requires one TCP transport to be running, while switch.boundAddrs() collects only currently-running transports — so during startup this commits a partial set (hasBoundAddrs = true) that every other consumer (identifyGuesses, mDNS, AutoNAT) reads until Switch's final commit. With a WSS transport waiting on the certificate, that window spans the entire issuance. Each commit also bumps the manager revision, invalidating Switch's in-flight initial resolution and forcing extra re-resolution passes. Today the values happen to converge because Switch later commits the identical full set, but correctness depends on that ordering and on both writers deriving the set the same way. Consider gating the commit on all transports having started, or exposing a resolve path that takes the input set without mutating the shared boundAddrs state.
There was a problem hiding this comment.
Today the values happen to converge because Switch later commits the identical full set, but correctness depends on that ordering and on both writers deriving the set the same way.
test will make sure it converges
3161668 to
627a24f
Compare
|
/review |
|
@greptileai review this PR |
|
OpenCodeReview · Complete review: 32 of 32 selected files covered 5 findings.
Review infoReviewed commits:
Model: |
| proc beginBatch*(self: AddressManager) = | ||
| ## Explicit resolve calls remain available, but no change notifications escape. | ||
| inc self.batchDepth |
There was a problem hiding this comment.
The exported beginBatch/endBatchAndRefresh pair is not exception- or cancellation-safe: batchDepth is only decremented by an explicit endBatchAndRefresh call (or a full stop()). If a caller raises or is cancelled between the two calls, the depth leaks and permanently suppresses onAddressChange and notifyReachability, so the node silently stops republishing address/reachability changes until the next stop. Switch.start happens to be protected because all its failure paths run stop(), but this API is exported for services, which have no such guarantee. Additionally, the doAssert batchDepth > 0 guard in endBatchAndRefresh is compiled out under --assertions:off/-d:danger, letting an unpaired close drive the depth negative and break batching() semantics for subsequent batches. Consider providing a withBatch template that decrements in a finally (and refreshes after release), or at least documenting that callers must pair the calls via defer/try finally.
There was a problem hiding this comment.
or at least documenting that callers must pair the calls via defer/try finally
| # Callbacks may request another resolution, so never invoke them under the lock. | ||
| self.notifyReachabilitySoon() |
There was a problem hiding this comment.
Moving notifyReachabilitySoon() outside the resolution lock removes the serialization the old PeerInfo mapper lock provided, and exposes a re-entrancy hole in queueReachabilityNotification: notify() is invoked before self.reachabilityNotifyTail = current is assigned. If a reachability handler synchronously mutates state (flipping the summary) and calls resolve() before its first await, the nested notifyReachabilitySoon() sees the old (finished/nil) tail and runs the handler again while the outer handler invocation is still on the stack — violating the documented "keeps handlers from overlapping" invariant. Worse, when the outer notify() finally returns, reachabilityNotifyTail = current overwrites the newer tail registered during re-entrancy, so subsequent notifications chain past a still-running handler. Consider registering the notification in reachabilityNotifyTail before its body can execute (e.g., a placeholder future completed by notify()), or adding a re-entrancy guard so a synchronous re-request is coalesced into the running notification instead of overtaking it.
| addressManager.setListenAddrs(b.addresses) | ||
| addressManager.setAnnouncedAddrs(b.announcedAddrs) | ||
| addressManager.setAddressPolicy(b.addressPolicy) | ||
| let identify = Identify.new(peerInfo, b.sendSignedPeerRecord, addressManager) |
There was a problem hiding this comment.
the implication of key change: address ownership is sole in AddressManager.
setting addressPolicy, announcedAddrs, listenAddrs was moved from PeerInfo to AddressManager
| AddressMapper* = proc(listenAddrs: seq[MultiAddress]): Future[seq[MultiAddress]] {. | ||
| gcsafe, async: (raises: [CancelledError]) | ||
| .} ## A proc that resolves listen addresses into dialable addresses. | ||
|
|
There was a problem hiding this comment.
all code related to AddressMapper has been removed.
this sets PeerInfo for flowing refactoring #3254
| ## When non-empty, these replace the output of the mapper chain, e.g. to | ||
| ## advertise a public NAT-mapped address while binding locally. The mappers | ||
| ## still run, and addressPolicy still filters. | ||
| addrs*: seq[MultiAddress] |
There was a problem hiding this comment.
note PeerInfo type still has peerId and addrs, those information will always remain here as that peer identity information (also from other remote peers).
moves address resolution and mapper ownership into
AddressManager, withSwitchcoordinating refreshes and publishing resolved addresses throughPeerInfo.the change separates address calculation from publication, tracks revisions to discard stale resolutions, and coalesces refresh requests.
startup batches address changes until transports and services are ready. closing the outermost batch also requests publication, so changes deferred by batching do not leave
PeerInfostale.Updates services and tests to use the new address management flow, and adds coverage for resolution, lifecycle behavior, and refreshes interrupted by batching.
closes: #3253