link: preserve asymmetric keepalive liveness

This commit is contained in:
DeFiDude committed 2026-07-24 20:15:50 -06:00
1 parent bb7395b284
commit 2ec94069a4
3 files changed
+194 -25

No files matched your search

+95 -11
View File
@@ -89,6 +89,10 @@ impl KeepaliveState {
/// Whether the initiator should emit a keepalive now (jitter applied).
pub fn should_send_keepalive(&self) -> bool {
self.should_send_keepalive_at(Instant::now())
}
pub(crate) fn should_send_keepalive_at(&self, now: Instant) -> bool {
let jittered = if self.jitter_negative {
self.keepalive_interval
.saturating_sub(self.jitter_offset)
@@ -97,37 +101,53 @@ impl KeepaliveState {
self.keepalive_interval + self.jitter_offset
};
let inbound_elapsed = self.last_inbound.elapsed();
let inbound_elapsed = now.saturating_duration_since(self.last_inbound);
let outbound_elapsed = self
.last_outbound
.or(self.activated_at)
.map(|baseline| now.saturating_duration_since(baseline))
.unwrap_or(inbound_elapsed);
let keepalive_elapsed = self
.last_keepalive_sent
.map(|t| t.elapsed())
.map(|last_keepalive| now.saturating_duration_since(last_keepalive))
.unwrap_or(Duration::MAX);
self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered
self.is_initiator
&& (inbound_elapsed >= jittered || outbound_elapsed >= jittered)
&& keepalive_elapsed >= jittered
}
pub(crate) fn should_respond_to_keepalive_at(&self, now: Instant) -> bool {
!self.is_initiator
&& self
.last_outbound
.map(|last_outbound| {
now.saturating_duration_since(last_outbound) >= self.keepalive_interval
})
.unwrap_or(true)
}
/// Whether the link should transition to STALE.
///
/// Uses the most recent of inbound, proof, or activation as the baseline so a
/// link that just came up isn't immediately flagged stale on a quiet channel.
/// Uses only peer evidence — inbound traffic, proof, or activation — as the
/// baseline. Local outbound traffic cannot prove that the peer remains alive.
pub fn is_stale(&self) -> bool {
self.is_stale_at(Instant::now())
}
pub(crate) fn is_stale_at(&self, now: Instant) -> bool {
let mut latest = self.last_inbound;
if let Some(proof) = self.last_proof {
if proof > latest {
latest = proof;
}
}
if let Some(outbound) = self.last_outbound {
if outbound > latest {
latest = outbound;
}
}
if let Some(activated) = self.activated_at {
if activated > latest {
latest = activated;
}
}
latest.elapsed() >= self.stale_time
now.saturating_duration_since(latest) >= self.stale_time
}
/// How long to wait in STALE before tearing the link down.
@@ -139,6 +159,16 @@ impl KeepaliveState {
self.last_keepalive_sent = Some(Instant::now());
}
pub(crate) fn mark_keepalive_sent_at(&mut self, now: Instant) {
self.last_keepalive_sent = Some(now);
}
pub(crate) fn record_keepalive_outbound(&mut self) {
let now = Instant::now();
self.last_outbound = Some(now);
self.last_keepalive_sent = Some(now);
}
pub fn since_inbound(&self) -> Duration {
self.last_inbound.elapsed()
}
@@ -220,6 +250,60 @@ mod tests {
assert!(!ks2.should_send_keepalive());
}
#[test]
fn continuous_inbound_still_schedules_keepalive_when_outbound_is_quiet() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.keepalive_interval = Duration::from_secs(5);
state.jitter_offset = Duration::ZERO;
state.jitter_negative = false;
state.last_inbound = now;
state.last_outbound = None;
state.activated_at = Some(now - Duration::from_secs(6));
state.last_keepalive_sent = Some(now - Duration::from_secs(6));
assert!(state.should_send_keepalive_at(now));
}
#[test]
fn recent_keepalive_suppresses_duplicate_at_exact_tick_time() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.keepalive_interval = Duration::from_secs(5);
state.jitter_offset = Duration::ZERO;
state.jitter_negative = false;
state.last_inbound = now - Duration::from_secs(6);
state.last_outbound = Some(now - Duration::from_secs(6));
state.last_keepalive_sent = Some(now - Duration::from_secs(4));
assert!(!state.should_send_keepalive_at(now));
assert!(state.should_send_keepalive_at(now + Duration::from_secs(1)));
}
#[test]
fn local_outbound_traffic_does_not_mask_a_stale_peer() {
let now = Instant::now();
let mut state = KeepaliveState::new(true);
state.stale_time = Duration::from_secs(5);
state.last_inbound = now - Duration::from_secs(6);
state.last_outbound = Some(now);
state.last_proof = None;
state.activated_at = None;
assert!(state.is_stale_at(now));
}
#[test]
fn responder_suppresses_keepalive_reply_after_recent_outbound() {
let now = Instant::now();
let mut state = KeepaliveState::new(false);
state.keepalive_interval = Duration::from_secs(5);
state.last_outbound = Some(now);
assert!(!state.should_respond_to_keepalive_at(now));
assert!(state.should_respond_to_keepalive_at(now + Duration::from_secs(5)));
}
#[test]
fn test_stale_detection() {
let mut ks = KeepaliveState::new(true);
+26 -13
View File
@@ -1171,11 +1171,23 @@ impl Link {
self.keepalive.record_outbound();
}
/// Count an outbound keepalive beat (Python counts them too, Packet.py:291)
/// without touching `last_outbound` — that would defer `is_stale` forever.
/// Count an outbound keepalive beat and retain its send time.
///
/// Stale detection deliberately ignores local outbound activity, while the
/// retained timestamp prevents redundant keepalive traffic.
pub fn record_tx_keepalive(&mut self, bytes: usize) {
self.tx_bytes += bytes as u64;
self.tx_count += 1;
self.keepalive.record_keepalive_outbound();
}
/// Whether this responder should answer a keepalive request.
///
/// Recent outbound traffic already proves the responder can transmit, so
/// an immediate extra reply would only duplicate that traffic.
pub fn should_respond_to_keepalive(&self) -> bool {
self.keepalive
.should_respond_to_keepalive_at(Instant::now())
}
/// `bytes` is the link payload after the context byte (Link.py:929).
@@ -1272,6 +1284,7 @@ impl Link {
),
)]
pub fn tick(&mut self) -> LinkAction {
let now = Instant::now();
for receipt in &mut self.pending_requests {
receipt.check_timeout();
}
@@ -1279,7 +1292,7 @@ impl Link {
match self.state {
LinkState::Pending | LinkState::Handshake => {
if self.request_time.elapsed() > self.establishment_timeout {
if now.saturating_duration_since(self.request_time) > self.establishment_timeout {
self.close(CloseReason::Timeout);
return LinkAction::Closed(CloseReason::Timeout);
}
@@ -1288,13 +1301,13 @@ impl Link {
LinkState::Active => {
// Emit any pending keepalive before checking staleness so a final
// beat goes out on the same tick the link transitions to STALE.
if self.keepalive.should_send_keepalive() {
self.keepalive.mark_keepalive_sent();
if self.keepalive.should_send_keepalive_at(now) {
self.keepalive.mark_keepalive_sent_at(now);
return LinkAction::SendKeepalive;
}
if self.keepalive.is_stale() {
if self.keepalive.is_stale_at(now) {
self.state = LinkState::Stale;
self.stale_since = Some(Instant::now());
self.stale_since = Some(now);
tracing::debug!(link_id = ?self.link_id, "link state -> Stale");
return LinkAction::TransitionedToStale;
}
@@ -1306,7 +1319,7 @@ impl Link {
let rtt = self.rtt.unwrap_or(Duration::from_secs(1));
let grace = self.keepalive.stale_grace_timeout(rtt);
if let Some(stale_since) = self.stale_since {
if stale_since.elapsed() >= grace {
if now.saturating_duration_since(stale_since) >= grace {
let teardown_data = self.encrypt(&self.link_id).unwrap_or_default();
self.close(CloseReason::Timeout);
return LinkAction::SendTeardownAndClose(teardown_data);
@@ -2492,11 +2505,10 @@ mod tests {
assert_eq!(rx_c, 1);
}
/// Keepalive beats count into traffic stats (Packet.py:291) but must not
/// refresh `last_outbound`, or an initiator pinging a dead peer would
/// never go stale.
/// Keepalive beats count into traffic stats and refresh the outbound
/// keepalive clock. Peer-liveness detection remains inbound-only.
#[test]
fn test_record_tx_keepalive_counts_without_outbound_refresh() {
fn test_record_tx_keepalive_counts_and_refreshes_outbound() {
let (mut link, _, _) = make_active_link();
assert!(link.keepalive.last_outbound.is_none());
@@ -2505,7 +2517,8 @@ mod tests {
let (tx_b, _, tx_c, _) = link.traffic_stats();
assert_eq!(tx_b, 1);
assert_eq!(tx_c, 1);
assert!(link.keepalive.last_outbound.is_none());
assert!(link.keepalive.last_outbound.is_some());
assert!(link.keepalive.last_keepalive_sent.is_some());
}
/// Initiator knows expected_hops at creation (Link.py:282); the responder
+73 -1
View File
@@ -1221,7 +1221,7 @@ impl LinkManager {
link_id = hex::encode(link_id),
"ignoring keepalive request on initiator side"
);
} else {
} else if active.link.should_respond_to_keepalive() {
let resp_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
@@ -1244,6 +1244,11 @@ impl LinkManager {
destination_hash: link_id,
},
));
} else {
tracing::trace!(
link_id = hex::encode(link_id),
"recent outbound traffic suppresses redundant keepalive response"
);
}
}
}
@@ -4031,6 +4036,73 @@ mod tests {
assert_eq!(lm.resource_strategy, ResourceStrategy::AcceptAll);
}
#[test]
fn responder_suppresses_redundant_keepalive_after_recent_outbound() {
let destination_hash = [0xA1; 16];
let identity_key = Ed25519PrivateKey::generate();
let identity_pub = identity_key.public_key();
let (mut initiator, request_data) = Link::new_initiator(destination_hash, 1);
let (mut responder, proof_data) =
Link::new_responder(&request_data, &identity_key, destination_hash, 1).unwrap();
let rtt_data = initiator
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
.unwrap();
responder.receive_rtt_packet(&rtt_data).unwrap();
responder.record_tx(1);
let link_id = responder.link_id;
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut manager =
LinkManager::new(transport_tx, event_rx, destination_hash, Some(identity_key));
manager.active_links.insert(
link_id,
ActiveLink {
link: responder,
_interface_id: 7,
channel: None,
inbound_resources: HashMap::new(),
outbound_resources: HashMap::new(),
outbound_split_queues: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
},
);
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Keepalive,
};
let mut request = header.pack();
request.push(rns_link::constants::KEEPALIVE_REQUEST);
manager.handle_inbound_packet(&request, 7);
assert!(
transport_rx.try_recv().is_err(),
"recent responder traffic must suppress a duplicate keepalive response"
);
let active = manager.active_links.get_mut(&link_id).unwrap();
active.link.keepalive.last_outbound =
std::time::Instant::now().checked_sub(active.link.keepalive.keepalive_interval);
manager.handle_inbound_packet(&request, 7);
assert!(matches!(
transport_rx.try_recv().unwrap(),
TransportMessage::Outbound(OutboundRequest { raw, destination_hash })
if destination_hash == link_id
&& raw.last() == Some(&rns_link::constants::KEEPALIVE_RESPONSE)
));
}
#[tokio::test]
async fn test_register_destination_channel() {
let (actor, tx) = rns_transport::actor::TransportActor::new();