Skip to content

Commit b0edc68

Browse files
authored
refactor(gossipsub): in-place negative-score peer removal
This change improves peer removal during `heartbeat` by switching from a two-pass remove logic to an in-place `retain` with very small size intermediate variable `removed_peers_count`. Pull-Request: #6209.
1 parent a0bf993 commit b0edc68

File tree

2 files changed

+21
-12
lines changed

2 files changed

+21
-12
lines changed

protocols/gossipsub/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@
2929
- gossipsub: do early return in for an empty input
3030
See [PR 6208](https://github.com/libp2p/rust-libp2p/pull/6208).
3131

32+
- Refactor gossipsub with in-place negative-score peer removal.
33+
See [PR 6209](https://github.com/libp2p/rust-libp2p/pull/6209).
34+
3235
## 0.49.2
3336

3437
- Relax `Behaviour::with_metrics` requirements, do not require DataTransform and TopicSubscriptionFilter to also impl Default

protocols/gossipsub/src/behaviour.rs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2135,11 +2135,14 @@ where
21352135
let mesh_n_high = self.config.mesh_n_high_for_topic(topic_hash);
21362136
let mesh_outbound_min = self.config.mesh_outbound_min_for_topic(topic_hash);
21372137

2138-
// drop all peers with negative score, without PX
2139-
// if there is at some point a stable retain method for BTreeSet the following can be
2140-
// written more efficiently with retain.
2141-
let mut to_remove_peers = Vec::new();
2142-
for peer_id in peers.iter() {
2138+
#[cfg(feature = "metrics")]
2139+
let mut removed_peers_count = 0;
2140+
2141+
// Drop all peers with negative score, without PX
2142+
//
2143+
// TODO: Use `extract_if` once MSRV is raised to a version that includes its
2144+
// stabilization.
2145+
peers.retain(|peer_id| {
21432146
let peer_score = scores.get(peer_id).map(|r| r.score).unwrap_or_default();
21442147

21452148
// Record the score per mesh
@@ -2159,17 +2162,20 @@ where
21592162
let current_topic = to_prune.entry(*peer_id).or_insert_with(Vec::new);
21602163
current_topic.push(topic_hash.clone());
21612164
no_px.insert(*peer_id);
2162-
to_remove_peers.push(*peer_id);
2165+
2166+
#[cfg(feature = "metrics")]
2167+
{
2168+
removed_peers_count += 1;
2169+
}
2170+
2171+
return false;
21632172
}
2164-
}
2173+
true
2174+
});
21652175

21662176
#[cfg(feature = "metrics")]
21672177
if let Some(m) = self.metrics.as_mut() {
2168-
m.peers_removed(topic_hash, Churn::BadScore, to_remove_peers.len())
2169-
}
2170-
2171-
for peer_id in to_remove_peers {
2172-
peers.remove(&peer_id);
2178+
m.peers_removed(topic_hash, Churn::BadScore, removed_peers_count)
21732179
}
21742180

21752181
// too little peers - add some

0 commit comments

Comments
 (0)