transport: count received bytes as accepted or filtered, and rx_packets after preprocessing

This commit is contained in:
DeFiDude committed 2026-11-18 12:58:38 -07:00
1 parent 0f411d35fb
commit 7005c32200
7 files changed
+292 -71

No files matched your search

+57 -6
View File
@@ -13,6 +13,19 @@ enum InboundOrigin {
CachedPacket,
}
/// Python 1.6.1's verdict on one inbound frame (`Transport.inbound`): filtered
/// unless preprocessing admits it.
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub(super) enum InboundVerdict {
#[default]
Filtered,
/// Admitted, and counted in `rx_packets`.
Accepted,
/// Admitted without reaching `rx_packets`: a path request batched into one
/// already in flight (Transport.py:2256).
Batched,
}
/// A transit link proof's verdict; only a bad signature is a protocol
/// violation (Transport.py).
#[derive(PartialEq, Eq)]
@@ -43,13 +56,13 @@ impl TransportActor {
fields(interface_id = packet.interface_id, raw_len = packet.raw.len()),
)]
pub(super) fn on_inbound(&mut self, packet: crate::messages::InboundPacket) {
self.on_inbound_inner(packet, InboundOrigin::Wire);
self.on_inbound_counted(packet, InboundOrigin::Wire);
}
/// An announce the ingress controller held, released for processing; it
/// can be held again (Interface.py).
/// can be held again, and counts again (Interface.py).
pub(super) fn on_released_announce(&mut self, announce: crate::ingress::HeldAnnounce) {
self.on_inbound_inner(
self.on_inbound_counted(
crate::messages::InboundPacket {
raw: announce.raw,
interface_id: announce.receiving_interface_id,
@@ -130,7 +143,7 @@ impl TransportActor {
if raw.len() > 500 {
return;
}
self.on_inbound_inner(
self.on_inbound_counted(
crate::messages::InboundPacket {
raw,
interface_id: 0,
@@ -142,6 +155,39 @@ impl TransportActor {
);
}
/// Python `Transport.inbound`: each frame counts once, on its interface and
/// parent, as accepted or filtered bytes; cache replays are not counted.
fn on_inbound_counted(
&mut self,
packet: crate::messages::InboundPacket,
origin: InboundOrigin,
) {
let (interface_id, len) = (packet.interface_id, packet.raw.len() as u64);
let outer = std::mem::take(&mut self.inbound_verdict);
self.on_inbound_inner(packet, origin);
let verdict = std::mem::replace(&mut self.inbound_verdict, outer);
if origin == InboundOrigin::CachedPacket {
return;
}
if verdict == InboundVerdict::Accepted {
self.count_rx_packet();
}
let accepted = verdict != InboundVerdict::Filtered;
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
return;
};
let parent = entry.parent_id;
entry.received.count(len, accepted);
if let Some(parent) = parent.and_then(|id| self.interfaces.get_mut(&id)) {
parent.received.count(len, accepted);
}
}
/// Python's end of `preprocess_inbound` for the frame being processed.
pub(super) fn accept_inbound(&mut self, verdict: InboundVerdict) {
self.inbound_verdict = verdict;
}
fn on_inbound_inner(&mut self, packet: crate::messages::InboundPacket, origin: InboundOrigin) {
// Transport.py: frames of two bytes or less are protocol
// violations before any IFAC handling.
@@ -380,8 +426,12 @@ impl TransportActor {
}
}
if origin != InboundOrigin::CachedPacket {
self.count_rx_packet();
// Python 1.6.1 admits announces and path requests at the end of their
// own gates, everything else here (Transport.py:2266).
let path_request = parsed.flags.packet_type != rns_wire::flags::PacketType::Announce
&& parsed.destination_hash == Self::path_request_dest_hash();
if parsed.flags.packet_type != rns_wire::flags::PacketType::Announce && !path_request {
self.accept_inbound(InboundVerdict::Accepted);
}
// Announce gates run after the packet filter and before the hash is
@@ -738,6 +788,7 @@ impl TransportActor {
}
self.record_interface_event(interface_id, InterfaceEvent::ReceivedAnnounce, raw.len());
self.count_transport_event(InterfaceEvent::ReceivedAnnounce);
self.accept_inbound(InboundVerdict::Accepted);
if let Some(validated_identity) = validated_identity.as_ref() {
let known_public_key = self
+10 -41
View File
@@ -124,6 +124,8 @@ pub struct TransportActor {
pub(crate) blackhole_table: BlackholeTable,
/// Python's interface traffic count and top-level stats counters.
traffic_count: rpc::TrafficCount,
/// Python `preprocess_inbound`'s verdict on the frame being processed.
inbound_verdict: inbound::InboundVerdict,
/// Python's `local_client_rssi_cache`, `_snr_cache` and `_q_cache`: one
/// 512-entry list per metric, first match wins (Transport.py).
pub(crate) packet_rssi_cache: VecDeque<([u8; 32], f32)>,
@@ -525,6 +527,7 @@ impl TransportActor {
rate_table_retain: RATE_TABLE_RETAIN,
blackhole_table: BlackholeTable::new(),
traffic_count: rpc::TrafficCount::default(),
inbound_verdict: inbound::InboundVerdict::default(),
packet_rssi_cache: VecDeque::new(),
packet_snr_cache: VecDeque::new(),
packet_q_cache: VecDeque::new(),
@@ -2900,48 +2903,14 @@ mod tests {
fn make_test_interface(name: &str) -> (InterfaceEntry, mpsc::Receiver<Bytes>) {
let (tx, rx) = mpsc::channel(64);
let entry = InterfaceEntry {
owner: crate::InterfaceOwner::new(),
packet_capacity: crate::InterfacePacketCapacity::base(500),
name: name.to_string(),
mode: InterfaceMode::Gateway,
role: InterfaceRole::Normal,
parent_id: None,
accepted: false,
direction: InterfaceDirection::bidirectional(),
bitrate: 115200,
mtu: 500,
let entry = InterfaceEntry::new(
name.to_string(),
InterfaceMode::Gateway,
InterfaceDirection::bidirectional(),
115_200,
500,
tx,
ifac_key: None,
ifac_size: 0,
ifac_netname: None,
ifac_signed: None,
autoconnect_source: None,
announce_cap: ANNOUNCE_CAP,
announce_allowed_at: 0.0,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
online: None,
rxb: None,
txb: None,
inspection: None,
tx_drops: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
tx_dropped_bytes: 0,
protocol_violations: 0,
ifac_violations: 0,
packet_filter_hits: 0,
multipoint: false,
recursive_prs: false,
announces_from_internal: true,
announces_to_internal: None,
gravity: 0,
shared_medium: false,
destination_cost: None,
pr_cost: None,
ingress: crate::ingress::IngressController::new(),
announce_queue: Vec::new(),
};
);
(entry, rx)
}
@@ -715,6 +715,7 @@ impl TransportActor {
}
// Python counts a path request once its tag and stamp pass these gates,
// then classifies it against the updated burst state (Transport.py).
self.accept_inbound(super::inbound::InboundVerdict::Batched);
self.record_interface_event(interface_id, InterfaceEvent::ReceivedPathRequest, raw_len);
self.count_transport_event(InterfaceEvent::ReceivedPathRequest);
let ingress_limited = self
@@ -737,6 +738,7 @@ impl TransportActor {
}
return;
}
self.accept_inbound(super::inbound::InboundVerdict::Accepted);
self.inflight_path_requests.insert(requested_dest, now);
let mut tag_bytes = [0u8; 16];
+33 -20
View File
@@ -59,11 +59,7 @@ impl TransportActor {
.as_ref()
.map(|o| o.load(std::sync::atomic::Ordering::Relaxed))
.unwrap_or(true);
let rx_bytes = entry
.rxb
.as_ref()
.map(|c| c.load(std::sync::atomic::Ordering::Relaxed))
.unwrap_or(0);
let rx_bytes = entry.received.accepted;
let tx_bytes = entry
.txb
.as_ref()
@@ -93,6 +89,7 @@ impl TransportActor {
.get(&iface_id)
.copied()
.unwrap_or_default();
let speeds = self.traffic_count.speeds.get(&iface_id).copied();
// Python publishes IFAC only for an interface that has it.
let ifac_signature = entry.ifac_signature();
let has_ifac = entry.ifac_key.is_some();
@@ -101,6 +98,8 @@ impl TransportActor {
name: entry.name.clone(),
rx_bytes,
tx_bytes,
filtered_rx_bytes: entry.received.filtered,
filtered_tx_bytes: 0,
rx_rate: 0,
tx_rate: 0,
online,
@@ -158,7 +157,8 @@ impl TransportActor {
.inspection
.as_ref()
.and_then(|source| source.identity().cloned()),
speeds: self.traffic_count.speeds.get(&iface_id).copied(),
speeds: speeds.map(|s| [s[0], s[1], s[2], s[3], s[4], s[5]]),
filtered_speeds: speeds.map(|s| [s[6], s[7]]),
announce_rx_bytes: arxb,
announce_tx_bytes: atxb,
path_request_rx_bytes: prxb,
@@ -513,11 +513,7 @@ impl TransportActor {
.as_ref()
.map(|o| o.load(std::sync::atomic::Ordering::Relaxed))
.unwrap_or(true);
let rx = entry
.rxb
.as_ref()
.map(|c| c.load(std::sync::atomic::Ordering::Relaxed))
.unwrap_or(0);
let rx = entry.received.accepted;
let tx = entry
.txb
.as_ref()
@@ -811,10 +807,14 @@ pub(super) enum InterfaceEvent {
SentPathRequest,
}
/// Byte counters the traffic count samples: Python's `rxb`, `txb`, `arxb`,
/// `atxb`, `prxb`, `ptxb`, `frxb` and `ftxb`.
const SAMPLED: usize = 8;
#[derive(Debug, Clone, Copy)]
struct TrafficSample {
at: std::time::Instant,
bytes: [u64; 6],
bytes: [u64; SAMPLED],
}
/// Python `Transport.count_traffic_loop` state and the packet counters it
@@ -824,7 +824,7 @@ pub(super) struct TrafficCount {
started: std::time::Instant,
totals: TrafficTotalsRpcEntry,
samples: HashMap<InterfaceId, TrafficSample>,
speeds: HashMap<InterfaceId, [f64; 6]>,
speeds: HashMap<InterfaceId, [f64; SAMPLED]>,
/// Python `r_stat_rssi`, `r_stat_snr` and `r_stat_q` per interface.
signal: HashMap<InterfaceId, PacketMetrics>,
last_pps: Option<(std::time::Instant, u64, u64)>,
@@ -896,8 +896,8 @@ impl TransportActor {
}
}
/// Python `Transport.rx_packets += 1` once a packet passes the packet
/// filter (Transport.py).
/// Python 1.6.1 `Transport.rx_packets += 1` once a packet passes
/// preprocessing (Transport.py:2266).
pub(super) fn count_rx_packet(&mut self) {
self.traffic_count.totals.rx_packets += 1;
}
@@ -950,8 +950,8 @@ impl TransportActor {
count
.signal
.retain(|id, _| self.interfaces.contains_key(id));
let mut deltas = [0u64; 6];
let mut speeds = [0f64; 6];
let mut deltas = [0u64; SAMPLED];
let mut speeds = [0f64; SAMPLED];
let mut freqs = [0f64; 4];
let mut measured = false;
for (&id, entry) in &mut self.interfaces {
@@ -959,7 +959,16 @@ impl TransportActor {
continue;
}
let (arxb, atxb, prxb, ptxb) = entry.ingress.announce_and_path_request_bytes();
let bytes = [load(&entry.rxb), load(&entry.txb), arxb, atxb, prxb, ptxb];
let bytes = [
entry.received.accepted,
load(&entry.txb),
arxb,
atxb,
prxb,
ptxb,
entry.received.filtered,
0,
];
let Some(previous) = count.samples.insert(id, TrafficSample { at, bytes }) else {
continue;
};
@@ -967,8 +976,8 @@ impl TransportActor {
if elapsed <= 0.0 {
continue;
}
let mut interface_speeds = [0f64; 6];
for i in 0..6 {
let mut interface_speeds = [0f64; SAMPLED];
for i in 0..SAMPLED {
let delta = bytes[i].saturating_sub(previous.bytes[i]);
deltas[i] += delta;
interface_speeds[i] = (delta as f64 * 8.0) / elapsed;
@@ -998,6 +1007,8 @@ impl TransportActor {
totals.atxb += deltas[3];
totals.prxb += deltas[4];
totals.ptxb += deltas[5];
totals.frxb += deltas[6];
totals.ftxb += deltas[7];
[
totals.rxs,
totals.txs,
@@ -1005,6 +1016,8 @@ impl TransportActor {
totals.atxs,
totals.prxs,
totals.ptxs,
totals.frxs,
totals.ftxs,
] = speeds;
[totals.arxf, totals.atxf, totals.prxf, totals.ptxf] = freqs;
}
@@ -1,6 +1,5 @@
//! Held and cached announces re-enter inbound processing as Python
//! re-injects them: past IFAC, without counting their bytes again
//! (Interface.py, Transport.py).
//! re-injects them: past IFAC (Interface.py, Transport.py).
use super::*;
use crate::ingress::HeldAnnounce;
@@ -494,14 +494,20 @@ fn traffic_totals_are_cumulative_over_top_level_interfaces() {
actor.interfaces.insert(id, entry);
}
actor.count_traffic(1_000.0);
for id in 1..=3 {
actor.interfaces.get_mut(&id).unwrap().received.accepted += 100;
}
for counter in &counters {
counter.fetch_add(100, std::sync::atomic::Ordering::Relaxed);
counter.fetch_add(1_000, std::sync::atomic::Ordering::Relaxed);
}
std::thread::sleep(Duration::from_millis(5));
actor.count_traffic(1_001.0);
let measured = totals(&mut actor);
assert!(measured.measured);
assert_eq!(measured.rxb, 100, "only the top-level non-shared interface");
assert_eq!(
measured.rxb, 100,
"accepted bytes of the top-level non-shared interface, not the driver's wire count"
);
assert!(measured.rxs > 0.0);
actor.deregister_interface(1);
@@ -524,3 +530,145 @@ fn traffic_totals_count_never_used_paths() {
assert_eq!(measured.path_count, 3);
assert_eq!(measured.unused_path_count, 2);
}
fn received(actor: &mut TransportActor, id: InterfaceId) -> (u64, u64) {
let entry = stats(actor, id);
(entry.rx_bytes, entry.filtered_rx_bytes)
}
/// Python 1.6.1 counts each frame once in `Transport.inbound`: accepted bytes
/// in `rxb` and `rx_packets`, filtered ones in `frxb` (Transport.py:1973-1996).
#[test]
fn received_bytes_split_into_accepted_and_filtered() {
let mut actor = hub();
let _rx = attach(&mut actor, 1);
let data = make_data_packet([0x71; 16], 0);
let len = data.len() as u64;
inbound(&mut actor, data.clone(), 1);
assert_eq!(received(&mut actor, 1), (len, 0));
assert_eq!(totals(&mut actor).rx_packets, 1);
inbound(&mut actor, data, 1);
assert_eq!(
received(&mut actor, 1),
(len, len),
"a duplicate is filtered"
);
assert_eq!(
totals(&mut actor).rx_packets,
1,
"rx_packets counts accepted packets only"
);
let short_request = path_request([0x72; 16], &[0xA2; 15]);
inbound(&mut actor, short_request.clone(), 1);
assert_eq!(
received(&mut actor, 1),
(len, len + short_request.len() as u64),
"a path request of an invalid size is filtered"
);
let request = path_request([0x73; 16], &[0xA3; 16]);
inbound(&mut actor, request.clone(), 1);
let accepted = len + request.len() as u64;
assert_eq!(received(&mut actor, 1).0, accepted);
assert_eq!(totals(&mut actor).rx_packets, 2);
let (announce, _) = make_valid_announce("stats.accepted.announce", 1);
inbound(&mut actor, announce.clone(), 1);
assert_eq!(received(&mut actor, 1).0, accepted + announce.len() as u64);
assert_eq!(totals(&mut actor).rx_packets, 3);
}
/// A path request joining one in flight is accepted but never reaches
/// `rx_packets` (Transport.py:2256).
#[test]
fn a_batched_path_request_is_accepted_without_counting_a_packet() {
let mut actor = hub();
let _rx = attach(&mut actor, 1);
let destination = [0x74; 16];
actor.inflight_path_requests.insert(destination, now_f64());
let request = path_request(destination, &[0xA4; 16]);
inbound(&mut actor, request.clone(), 1);
assert_eq!(received(&mut actor, 1), (request.len() as u64, 0));
assert_eq!(totals(&mut actor).rx_packets, 0);
}
/// IFAC failures are filtered with the IFAC bytes counted.
#[test]
fn an_ifac_failure_is_filtered() {
let mut actor = hub();
attach_ifac(&mut actor, 1, [0x5A; 64]);
let raw = make_data_packet([0x75; 16], 0);
let mut flagged = raw.to_vec();
flagged[0] |= 0x80;
flagged.splice(2..2, [0u8; 8]);
let len = flagged.len() as u64;
inbound(&mut actor, flagged, 1);
assert_eq!(stats(&mut actor, 1).ifac_violations, 1);
assert_eq!(received(&mut actor, 1), (0, len));
assert_eq!(totals(&mut actor).rx_packets, 0);
}
/// A held announce is filtered and its release counts again, now accepted
/// (Transport.py:2165, Interface.py:339-341).
#[test]
fn a_held_announce_is_filtered_then_accepted_on_release() {
let mut actor = hub();
let _rx = attach(&mut actor, 1);
let ingress = &mut actor.interfaces.get_mut(&1).unwrap().ingress;
for _ in 0..50 {
ingress.received_announce();
}
assert!(ingress.should_ingress_limit(), "precondition: a burst");
let (announce, destination) = make_valid_announce("stats.held", 1);
let len = announce.len() as u64;
inbound(&mut actor, announce.clone(), 1);
assert_eq!(actor.interfaces[&1].ingress.held_count(), 1);
assert_eq!(received(&mut actor, 1), (0, len));
assert_eq!(totals(&mut actor).rx_packets, 0);
// The burst is over by the time Python releases it.
actor.interfaces.get_mut(&1).unwrap().ingress = crate::ingress::IngressController::new();
actor.on_released_announce(crate::ingress::HeldAnnounce {
raw: announce,
destination_hash: destination,
hops: 1,
receiving_interface_id: 1,
});
assert!(actor.path_table.has_path(&destination));
assert_eq!(received(&mut actor, 1), (len, len));
assert_eq!(totals(&mut actor).rx_packets, 1);
}
/// A spawned child adds both counters to its listener, and the traffic count
/// samples filtered bytes into the totals.
#[test]
fn a_child_adds_accepted_and_filtered_bytes_to_its_parent() {
let mut actor = hub();
let _parent = attach(&mut actor, 1);
let (mut child, _rx) = make_test_interface("stats_1/client_2");
child.parent_id = Some(1);
actor.interfaces.insert(2, child);
actor.count_traffic(1_000.0);
let data = make_data_packet([0x76; 16], 0);
let len = data.len() as u64;
inbound(&mut actor, data.clone(), 2);
inbound(&mut actor, data, 2);
assert_eq!(received(&mut actor, 2), (len, len));
assert_eq!(received(&mut actor, 1), (len, len));
std::thread::sleep(Duration::from_millis(5));
actor.count_traffic(1_001.0);
let measured = totals(&mut actor);
assert_eq!((measured.rxb, measured.frxb, measured.ftxb), (len, len, 0));
assert!(measured.frxs > 0.0);
let parent = stats(&mut actor, 1);
assert!(
parent
.filtered_speeds
.is_some_and(|[frxs, ftxs]| frxs > 0.0 && ftxs == 0.0)
);
assert_eq!(parent.filtered_tx_bytes, 0);
}
+39
View File
@@ -387,6 +387,8 @@ pub struct InterfaceEntry {
/// polling. `None` when the driver doesn't expose one (e.g. in-memory test
/// interfaces).
pub online: Option<Arc<AtomicBool>>,
/// The driver's count of every deframed frame. Stats report the bytes
/// transport accepted and filtered instead, as Python 1.6.1 does.
pub rxb: Option<Arc<std::sync::atomic::AtomicU64>>,
pub txb: Option<Arc<std::sync::atomic::AtomicU64>>,
/// Optional driver-owned aggregate inspection source.
@@ -432,6 +434,28 @@ pub struct InterfaceEntry {
/// Configured path request stamp requirement; `None` follows
/// `StampPolicy::pr_cost`. Resolve with `StampPolicy::interface_pr_cost`.
pub pr_cost: Option<f64>,
/// Python 1.6.1 `rxb` and `frxb`: inbound frame bytes transport accepted
/// or filtered, a spawned child's included in its parent's.
pub(crate) received: ReceivedBytes,
}
/// Inbound frame bytes, counted once each as Python's `Transport.inbound`
/// does: IFAC included, accepted or filtered by preprocessing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct ReceivedBytes {
pub(crate) accepted: u64,
pub(crate) filtered: u64,
}
impl ReceivedBytes {
pub(crate) fn count(&mut self, len: u64, accepted: bool) {
let counter = if accepted {
&mut self.accepted
} else {
&mut self.filtered
};
*counter = counter.saturating_add(len);
}
}
impl InterfaceEntry {
@@ -497,6 +521,7 @@ impl InterfaceEntry {
shared_medium: false,
destination_cost: None,
pr_cost: None,
received: ReceivedBytes::default(),
}
}
@@ -1303,8 +1328,13 @@ pub struct PathTableRpcEntry {
pub struct InterfaceStatRpcEntry {
pub id: InterfaceId,
pub name: String,
/// Python 1.6.1 `rxb`: received bytes transport accepted.
pub rx_bytes: u64,
pub tx_bytes: u64,
/// Python `frxb`: received bytes transport filtered, duplicates included.
pub filtered_rx_bytes: u64,
/// Python `ftxb`, which upstream never increments.
pub filtered_tx_bytes: u64,
pub rx_rate: u64,
pub tx_rate: u64,
pub online: bool,
@@ -1363,6 +1393,8 @@ pub struct InterfaceStatRpcEntry {
/// Python `current_rx/tx/arx/atx/prx/ptx_speed` in bits per second, set by
/// the traffic count on top-level interfaces after their first second.
pub speeds: Option<[f64; 6]>,
/// Python `current_frx_speed` and `current_ftx_speed`, sampled with `speeds`.
pub filtered_speeds: Option<[f64; 2]>,
/// Python `arxb`, `atxb`, `prxb` and `ptxb`.
pub announce_rx_bytes: u64,
pub announce_tx_bytes: u64,
@@ -1418,8 +1450,15 @@ pub struct TrafficTotalsRpcEntry {
pub ptxs: f64,
pub prxf: f64,
pub ptxf: f64,
/// Python `filtered_rxb` and `filtered_txb`, summed like `rxb`, and
/// `filtered_speed_rx` and `filtered_speed_tx`.
pub frxb: u64,
pub ftxb: u64,
pub frxs: f64,
pub ftxs: f64,
pub rxpps: u64,
pub txpps: u64,
/// Python 1.6.1 `rx_packets`: packets that passed preprocessing.
pub rx_packets: u64,
pub tx_packets: u64,
pub announce_rx_packets: u64,