Skip to content

Commit a98f878

Browse files
committed
Fix cleanup and enable user-configurable health scoring weights
1 parent 37ac290 commit a98f878

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

libp2p/network/health/data_structures.py

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,11 @@ class ConnectionHealth:
8383
# Count consecutive unhealthy evaluations to apply grace period
8484
consecutive_unhealthy: int = 0
8585

86+
# Health scoring weights (configurable)
87+
latency_weight: float = 0.4
88+
success_rate_weight: float = 0.4
89+
stability_weight: float = 0.2
90+
8691
def __post_init__(self) -> None:
8792
"""Initialize default values and validate data."""
8893
current_time = time.time()
@@ -103,14 +108,16 @@ def __post_init__(self) -> None:
103108
self.connection_stability = max(0.0, min(1.0, float(self.connection_stability)))
104109

105110
def update_health_score(self) -> None:
106-
"""Calculate overall health score based on metrics."""
111+
"""Calculate overall health score based on metrics with configurable weights."""
107112
# Weighted scoring algorithm
108113
latency_score = max(0.0, 1.0 - (self.ping_latency / 1000.0)) # Normalize to 1s
109114
success_score = self.ping_success_rate
110115
stability_score = self.connection_stability
111116

112117
self.health_score = (
113-
latency_score * 0.4 + success_score * 0.4 + stability_score * 0.2
118+
latency_score * self.latency_weight
119+
+ success_score * self.success_rate_weight
120+
+ stability_score * self.stability_weight
114121
)
115122

116123
def update_ping_metrics(self, latency: float, success: bool) -> None:
@@ -257,8 +264,30 @@ def get_health_summary(self) -> dict[str, Any]:
257264

258265
def create_default_connection_health(
259266
established_at: float | None = None,
267+
latency_weight: float = 0.4,
268+
success_rate_weight: float = 0.4,
269+
stability_weight: float = 0.2,
260270
) -> ConnectionHealth:
261-
"""Create a new ConnectionHealth instance with default values."""
271+
"""
272+
Create a new ConnectionHealth instance with default values.
273+
274+
Parameters
275+
----------
276+
established_at : float | None
277+
Timestamp when the connection was established. Defaults to current time.
278+
latency_weight : float
279+
Weight for latency in health scoring. Defaults to 0.4.
280+
success_rate_weight : float
281+
Weight for success rate in health scoring. Defaults to 0.4.
282+
stability_weight : float
283+
Weight for stability in health scoring. Defaults to 0.2.
284+
285+
Returns
286+
-------
287+
ConnectionHealth
288+
New ConnectionHealth instance with provided or default values.
289+
290+
"""
262291
current_time = time.time()
263292
established_at = established_at or current_time
264293

@@ -283,4 +312,7 @@ def create_default_connection_health(
283312
last_bandwidth_check=current_time,
284313
peak_bandwidth=0.0,
285314
average_bandwidth=0.0,
315+
latency_weight=latency_weight,
316+
success_rate_weight=success_rate_weight,
317+
stability_weight=stability_weight,
286318
)

libp2p/network/swarm.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,6 +782,9 @@ def remove_conn(self, swarm_conn: SwarmConn) -> None:
782782
"""
783783
peer_id = swarm_conn.muxed_conn.peer_id
784784

785+
# Clean up health tracking before removing the connection
786+
self.cleanup_connection_health(peer_id, swarm_conn)
787+
785788
if peer_id in self.connections:
786789
self.connections[peer_id] = [
787790
conn for conn in self.connections[peer_id] if conn != swarm_conn
@@ -856,7 +859,14 @@ def initialize_connection_health(self, peer_id: ID, connection: INetConn) -> Non
856859
if peer_id not in self.health_data:
857860
self.health_data[peer_id] = {}
858861

859-
self.health_data[peer_id][connection] = create_default_connection_health()
862+
# Pass user-defined weights from connection config
863+
# Type narrowed to ConnectionConfig by _is_health_monitoring_enabled()
864+
assert isinstance(self.connection_config, ConnectionConfig)
865+
self.health_data[peer_id][connection] = create_default_connection_health(
866+
latency_weight=self.connection_config.latency_weight,
867+
success_rate_weight=self.connection_config.success_rate_weight,
868+
stability_weight=self.connection_config.stability_weight,
869+
)
860870
logger.debug(f"Initialized health tracking for connection to peer {peer_id}")
861871

862872
def cleanup_connection_health(self, peer_id: ID, connection: INetConn) -> None:

0 commit comments

Comments
 (0)