From 5939c7b124e304b48d891f9641bf5af9267576fb Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:22:09 -0700 Subject: [PATCH] propagation: follow upstream store limits, unpeering, and identify retry --- crates/lxmf-core/src/propagation.rs | 16 ++ crates/lxmf-core/src/propagation_admission.rs | 4 +- crates/lxmf-core/src/propagation_node.rs | 147 ++++++++---------- crates/lxmf-core/src/propagation_sync.rs | 103 +++++++++--- crates/lxmf-core/src/router.rs | 60 +++---- crates/lxmf-core/tests/relay_store_v2.rs | 18 +-- crates/lxmf-tools/src/commands/lxmd.rs | 57 +++++-- crates/lxmf-tools/src/daemon.rs | 35 ++--- crates/lxmf-tools/src/lxmd_control.rs | 13 +- 9 files changed, 269 insertions(+), 184 deletions(-) diff --git a/crates/lxmf-core/src/propagation.rs b/crates/lxmf-core/src/propagation.rs index 0b548bb..2aa6105 100644 --- a/crates/lxmf-core/src/propagation.rs +++ b/crates/lxmf-core/src/propagation.rs @@ -296,6 +296,22 @@ impl PropagationStore { .insert(transient_id, crate::now_f64()); } + /// Record `transient_id` as processed unless it already is; the first-seen time is kept. + /// Returns false when it was already processed. + pub fn claim_processed(&mut self, transient_id: PropagationTransientId, now: f64) -> bool { + match self.locally_processed_ids.entry(transient_id) { + std::collections::hash_map::Entry::Occupied(_) => false, + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(now); + true + } + } + } + + pub(crate) fn unclaim_processed(&mut self, transient_id: &PropagationTransientId) { + self.locally_processed_ids.remove(transient_id); + } + pub fn is_locally_processed(&self, transient_id: &PropagationTransientId) -> bool { self.locally_processed_ids.contains_key(transient_id) } diff --git a/crates/lxmf-core/src/propagation_admission.rs b/crates/lxmf-core/src/propagation_admission.rs index 583e0d6..dccf5ec 100644 --- a/crates/lxmf-core/src/propagation_admission.rs +++ b/crates/lxmf-core/src/propagation_admission.rs @@ -27,7 +27,7 @@ const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation"; pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3; /// Lower bound applied to the configured inbound-sync threshold. pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1; -/// Duration applied after a known peer submits an invalid-stamp batch. +/// Default duration applied after a known peer submits an invalid-stamp batch. pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE); /// Policy applied to inbound propagation-node offers. @@ -521,7 +521,7 @@ impl PnInboundAdmission { Ok(PnCleanupResult::Removed(PnInboundState::Validating)) } - /// Install the standard throttle after invalid stamp validation for a + /// Install the configured throttle after invalid stamp validation for a /// known peer, including an unsolicited Resource with no offer record. /// /// `peer_destination_hash` must be the peer's already-derived diff --git a/crates/lxmf-core/src/propagation_node.rs b/crates/lxmf-core/src/propagation_node.rs index 9d43a82..859e579 100644 --- a/crates/lxmf-core/src/propagation_node.rs +++ b/crates/lxmf-core/src/propagation_node.rs @@ -480,6 +480,8 @@ pub enum PropagationAdmission { Reserved(Box), CommittedDuplicate(PropagationDuplicateCheck), Pending(PropagationAdmissionWaiter), + /// The transient ID was processed before and is no longer stored; nothing is written. + AlreadyProcessed, Rejected, } @@ -672,9 +674,6 @@ pub struct PropagationNode { storage_path: Option, object_paths: HashMap, _store_lock: Option, - /// Transitional pre-1.1 behavior; removed when the daemon-lifetime - /// `PnInboundAdmission` becomes the live throttle owner. - last_offer_times: HashMap<[u8; 16], f64>, /// Monotonic in-process revision of the propagation store. Outbound peer /// scheduling and offer-preparation revalidation use this to avoid both /// stale offers and repeated scans of an unchanged fully-handled store. @@ -700,7 +699,6 @@ impl PropagationNode { storage_path: None, object_paths: HashMap::new(), _store_lock: None, - last_offer_times: HashMap::new(), offer_generation: 0, pending_write_ids: HashSet::new(), pending_admissions: HashMap::new(), @@ -776,7 +774,6 @@ impl PropagationNode { storage_path: Some(storage_path), object_paths: HashMap::new(), _store_lock: Some(lock), - last_offer_times: HashMap::new(), offer_generation: 0, pending_write_ids: HashSet::new(), pending_admissions: HashMap::new(), @@ -800,18 +797,7 @@ impl PropagationNode { { return None; } - // Python checks the current store size before inserting and permits - // the message that crosses the cap; the next admission is rejected - // until culling makes room. Include reservations in that current-size - // view so concurrent writers cannot all pass the same preflight. - let occupied = self - .store - .total_size() - .saturating_add(self.pending_write_bytes); - if occupied > self.config.max_storage { - return None; - } - + // The storage limit is enforced only by maintenance culling, as in Python. let (result, _) = tokio::sync::watch::channel(PropagationAdmissionOutcome::Pending); let reservation = std::sync::Arc::new(AdmissionReservation { content_hash: rns_crypto::sha::full_hash(&data), @@ -850,6 +836,8 @@ impl PropagationNode { self.pending_admissions.remove(transient_id); if self.pending_write_ids.remove(transient_id) { self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size); + // A failed write leaves the message retryable. + self.store.unclaim_processed(transient_id); } } @@ -956,6 +944,9 @@ impl PropagationNode { for id in stale { self.pending_admissions.remove(&id); self.pending_write_ids.remove(&id); + if !self.store.contains(&id) { + self.store.unclaim_processed(&id); + } } self.pending_write_bytes = self .pending_admissions @@ -992,6 +983,16 @@ impl PropagationNode { } let mut destination = [0; 16]; destination.copy_from_slice(&blob.bytes[..16]); + if self.store.is_destination_ignored(&destination) { + return PropagationAdmission::Rejected; + } + // LXMRouter.lxmf_propagation claims the transient ID before storing it. + if !self + .store + .claim_processed(blob.transient_id, crate::now_f64()) + { + return PropagationAdmission::AlreadyProcessed; + } let entry = PropagationEntry::new_stamped( blob.transient_id, blob.transient_id, @@ -1084,6 +1085,7 @@ impl PropagationNode { pub fn plan_maintenance(&mut self) -> PropagationRetirementPlan { self.reap_retired(); let now = crate::now_f64(); + self.store.clean_transient_caches(now); let cutoff = now - self.config.max_message_age as f64; let mut ids = Vec::new(); let mut remaining = self.store.total_size(); @@ -1188,6 +1190,21 @@ impl PropagationNode { self.eligible(transient_id) && self.store.contains(transient_id) } + /// Transient IDs claimed at intake, with their first-seen times. + pub fn processed_ids(&self) -> &HashMap { + self.store.locally_processed_ids() + } + + /// Add processed IDs recorded elsewhere, keeping existing first-seen times. + pub fn merge_processed_ids<'a>( + &mut self, + ids: impl IntoIterator, + ) { + for (id, seen) in ids { + self.store.claim_processed(*id, *seen); + } + } + pub fn get_session(&self, peer_hash: &[u8; 16]) -> Option<&SyncSession> { self.sync_sessions.get(peer_hash) } @@ -1283,18 +1300,6 @@ impl PropagationNode { request_data: &[u8], ctx: OfferRequestContext<'_>, ) -> Vec { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|duration| duration.as_secs_f64()) - .unwrap_or(0.0); - if self - .last_offer_times - .get(&ctx.peer_hash) - .is_some_and(|last_time| now - last_time < PN_STAMP_THROTTLE as f64) - { - return Self::encode_offer_response(&OfferResponse::ErrorThrottled); - } - let offer = match crate::propagation_offer::decode(request_data, self.config.max_offer_size) { Ok(offer) => offer, @@ -1324,7 +1329,6 @@ impl PropagationNode { OfferResponse::ErrorInvalidKey }; - self.last_offer_times.insert(ctx.peer_hash, now); Self::encode_offer_response(&response) } @@ -2124,7 +2128,7 @@ pub(crate) mod tests { } #[test] - fn test_reject_store_full() { + fn test_store_over_limit_still_admits() { let config = PropagationNodeConfig { max_storage: 1, ..Default::default() @@ -2135,7 +2139,8 @@ pub(crate) mod tests { assert!(node.accept_fixture(&msg1)); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); - assert!(!node.accept_fixture(&msg2)); + assert!(node.accept_fixture(&msg2)); + assert_eq!(node.message_count(), 2); } #[test] @@ -2492,13 +2497,9 @@ pub(crate) mod tests { assert_eq!(node.message_count(), 0); } - /// After a message is culled (expired), the same message resurfacing - /// must be accepted again — the node's "seen" memory is the store - /// itself, not a separate dedup log. Otherwise a node that culled a - /// message and then received it again from another peer would - /// silently drop it, breaking store-and-forward semantics. + /// A culled message is still in the processed set, so it is not stored again. #[test] - fn test_reaccept_after_cull() { + fn test_culled_message_is_not_readmitted() { let config = PropagationNodeConfig { max_message_age: 1, ..Default::default() @@ -2508,54 +2509,28 @@ pub(crate) mod tests { let mut msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "cull then redeliver"); msg.timestamp = 1000.0; assert!(node.accept_fixture(&msg), "first accept"); - assert_eq!(node.message_count(), 1); - + std::thread::sleep(std::time::Duration::from_millis(1100)); node.tick(); assert_eq!(node.message_count(), 0, "culled by tick"); - // Fresh timestamp so the re-delivery isn't itself expired. - msg.timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs_f64(); - assert!( - node.accept_fixture(&msg), - "same message re-accepted after cull" - ); - assert_eq!(node.message_count(), 1); + assert!(!node.accept_fixture(&msg), "culled message filtered"); + assert_eq!(node.message_count(), 0); } - /// A store that was full and rejecting new messages must recover - /// capacity after culling — the reject-store-full path is transient, - /// not terminal. Exercises: fill → reject → cull expired → accept. + /// The storage limit is enforced by culling the heaviest entries, not at admission. #[test] - fn test_accept_after_store_full_and_cull() { - let config = PropagationNodeConfig { - max_storage: 1, - max_message_age: 1, - ..Default::default() - }; - let mut node = durable_test_node(config, [0xAA; 16]); - - let mut msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "first"); - msg1.timestamp = 1000.0; // ancient so tick will cull it - assert!(node.accept_fixture(&msg1)); - - let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "rejected-while-full"); - assert!( - !node.accept_fixture(&msg2), - "store full, second message must reject" - ); - + fn test_cull_trims_store_to_limit() { + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); + for body in ["first", "second", "third"] { + let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", body); + assert!(node.accept_fixture(&msg)); + } + let largest = node.store.entries().map(|e| e.size).max().unwrap(); + node.config.max_storage = node.total_size() - 1; node.tick(); - assert_eq!(node.message_count(), 0, "expired msg culled"); - - let msg3 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "accepted-after-cull"); - assert!( - node.accept_fixture(&msg3), - "store has space after cull, next message accepted" - ); - assert_eq!(node.message_count(), 1); + assert_eq!(node.message_count(), 2); + assert!(node.total_size() <= node.config.max_storage); + assert!(node.total_size() + largest > node.config.max_storage); } #[test] @@ -3122,6 +3097,20 @@ pub(crate) mod tests { ); let response = OfferResponse::from_msgpack(&response_bytes); assert_eq!(response, OfferResponse::WantAll); + + // LXMRouter.offer_request has no per-peer offer rate gate. + let again = node.handle_offer_request( + &valid_request, + offer_ctx( + [0xBB; 16], + true, + false, + true, + Some(&local_identity), + Some(&remote_identity), + ), + ); + assert_eq!(OfferResponse::from_msgpack(&again), OfferResponse::WantAll); } #[test] diff --git a/crates/lxmf-core/src/propagation_sync.rs b/crates/lxmf-core/src/propagation_sync.rs index 077d3be..8b4a069 100644 --- a/crates/lxmf-core/src/propagation_sync.rs +++ b/crates/lxmf-core/src/propagation_sync.rs @@ -57,6 +57,8 @@ pub enum SyncTaskState { NoPath, /// The peer answered the offer with `ERROR_THROTTLED`. Throttled, + /// The peer answered the offer with `ERROR_NO_ACCESS`. + NoAccess, Failed, } @@ -65,8 +67,10 @@ pub enum PeerSyncTerminalState { Complete, /// The path request was not answered; no link was attempted. NoPath, - /// The peer answered the offer with `ERROR_THROTTLED`. + /// The node answered the offer with `ERROR_THROTTLED`. Throttled, + /// The node answered the offer with `ERROR_NO_ACCESS`. + NoAccess, Failed, } @@ -185,6 +189,7 @@ pub struct PropagationSyncTask { active_offer_generation: Option, generation_exhausted: bool, terminal_result: Option, + identify_retried: bool, pending_transport: VecDeque, preserve_pending_on_cleanup: bool, offered_count: u64, @@ -243,6 +248,7 @@ impl PropagationSyncTask { active_offer_generation: None, generation_exhausted: false, terminal_result: None, + identify_retried: false, pending_transport: VecDeque::new(), preserve_pending_on_cleanup: false, offered_count: 0, @@ -309,6 +315,7 @@ impl PropagationSyncTask { active_offer_generation: None, generation_exhausted: false, terminal_result: None, + identify_retried: false, pending_transport: VecDeque::new(), preserve_pending_on_cleanup: false, offered_count: 0, @@ -369,6 +376,7 @@ impl PropagationSyncTask { active_offer_generation: None, generation_exhausted: false, terminal_result: None, + identify_retried: false, pending_transport: VecDeque::new(), preserve_pending_on_cleanup: false, offered_count: 0, @@ -704,6 +712,7 @@ impl PropagationSyncTask { self.transfer_wire_size = 0; self.transfer_started = None; self.link_establishment_rate = None; + self.identify_retried = false; } /// Drain inbound events from transport. @@ -1110,7 +1119,17 @@ impl PropagationSyncTask { self.record_handled_updates(&already_handled); self.prepare_transfer_for_ids(&wanted_ids); } + // Python identifies again and resends the offer without a bound; retry once per attempt. + OfferResponse::ErrorNoIdentity if !self.identify_retried && self.link.is_some() => { + self.identify_retried = true; + self.state = if self.send_identify() { + SyncTaskState::Offering + } else { + SyncTaskState::Failed + }; + } OfferResponse::ErrorThrottled => self.state = SyncTaskState::Throttled, + OfferResponse::ErrorNoAccess => self.state = SyncTaskState::NoAccess, _ => { self.state = SyncTaskState::Failed; } @@ -1197,6 +1216,7 @@ impl PropagationSyncTask { SyncTaskState::Complete | SyncTaskState::NoPath | SyncTaskState::Throttled + | SyncTaskState::NoAccess | SyncTaskState::Failed ) { @@ -1210,6 +1230,7 @@ impl PropagationSyncTask { | SyncTaskState::Complete | SyncTaskState::NoPath | SyncTaskState::Throttled + | SyncTaskState::NoAccess | SyncTaskState::Failed ) { self.drive_link_watchdog(); @@ -1240,6 +1261,7 @@ impl PropagationSyncTask { SyncTaskState::Complete | SyncTaskState::NoPath | SyncTaskState::Throttled + | SyncTaskState::NoAccess | SyncTaskState::Failed => { if self.terminal_result.is_none() && let Some(peer_hash) = self.node_dest_hash @@ -1251,6 +1273,7 @@ impl PropagationSyncTask { SyncTaskState::Complete => PeerSyncTerminalState::Complete, SyncTaskState::NoPath => PeerSyncTerminalState::NoPath, SyncTaskState::Throttled => PeerSyncTerminalState::Throttled, + SyncTaskState::NoAccess => PeerSyncTerminalState::NoAccess, _ => PeerSyncTerminalState::Failed, }, offer_generation: complete @@ -3305,29 +3328,38 @@ mod tests { } #[test] - fn test_handle_offer_response_error() { - let (tx, _rx) = mpsc::channel(16); - let mut task = test_task(tx, [0xAA; 16]); - task.set_node([0xBB; 16]); - task.state = SyncTaskState::AwaitingResponse; - - task.handle_offer_response(OfferResponse::ErrorNoAccess); - assert_eq!(task.state, SyncTaskState::Failed); - } - - #[test] - fn throttled_offer_response_ends_sync_as_throttled() { - let (tx, _rx) = mpsc::channel(16); - let mut task = test_task(tx, [0xAA; 16]); - task.set_node([0xBB; 16]); - task.state = SyncTaskState::AwaitingResponse; - - task.handle_offer_response(OfferResponse::ErrorThrottled); - task.tick(); - assert_eq!( - task.take_terminal_peer_result().unwrap().state, - PeerSyncTerminalState::Throttled - ); + fn offer_error_responses_reach_the_peer_as_distinct_outcomes() { + for (response, expected) in [ + ( + OfferResponse::ErrorThrottled, + PeerSyncTerminalState::Throttled, + ), + ( + OfferResponse::ErrorNoAccess, + PeerSyncTerminalState::NoAccess, + ), + ( + OfferResponse::ErrorInvalidKey, + PeerSyncTerminalState::Failed, + ), + // Without a live link there is nothing to identify on. + ( + OfferResponse::ErrorNoIdentity, + PeerSyncTerminalState::Failed, + ), + ] { + let (tx, _rx) = mpsc::channel(16); + let mut task = test_task(tx, [0xAA; 16]); + task.set_node([0xBB; 16]); + task.state = SyncTaskState::AwaitingResponse; + task.handle_offer_response(response.clone()); + task.tick(); + assert_eq!( + task.take_terminal_peer_result().map(|r| r.state), + Some(expected), + "{response:?}" + ); + } } #[test] @@ -3727,6 +3759,29 @@ mod tests { rns_wire::context::PacketContext::Request, ] ); + + // ERROR_NO_IDENTITY: identify again and resend the offer, once per attempt. + task.state = SyncTaskState::AwaitingResponse; + task.handle_offer_response(OfferResponse::ErrorNoIdentity); + assert_eq!(task.state, SyncTaskState::Offering); + task.send_offer_request(); + let mut contexts = Vec::new(); + while let Ok(message) = rx.try_recv() { + if let TransportMessage::SendLinkEndpoint { request, .. } = message { + let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + contexts.push(header.context); + } + } + assert_eq!( + contexts, + vec![ + rns_wire::context::PacketContext::LinkIdentify, + rns_wire::context::PacketContext::Request, + ] + ); + task.state = SyncTaskState::AwaitingResponse; + task.handle_offer_response(OfferResponse::ErrorNoIdentity); + assert_eq!(task.state, SyncTaskState::Failed); } #[test] diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index 3bb17e7..cf2c416 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -77,9 +77,9 @@ pub struct RouterConfig { pub propagation_enabled: bool, pub autopeer: bool, pub max_peers: usize, - pub propagation_limit_kb: usize, + pub propagation_limit_kb: f64, pub delivery_limit_kb: f64, - pub sync_limit_kb: usize, + pub sync_limit_kb: f64, pub propagation_stamp_cost: f64, pub propagation_stamp_flex: f64, pub stamp_cost: Option, @@ -138,9 +138,9 @@ impl Default for RouterConfig { propagation_enabled: false, autopeer: AUTOPEER, max_peers: MAX_PEERS, - propagation_limit_kb: PROPAGATION_LIMIT, + propagation_limit_kb: PROPAGATION_LIMIT as f64, delivery_limit_kb: DELIVERY_LIMIT as f64, - sync_limit_kb: SYNC_LIMIT, + sync_limit_kb: SYNC_LIMIT as f64, propagation_stamp_cost: PROPAGATION_COST, propagation_stamp_flex: PROPAGATION_COST_FLEX, stamp_cost: None, @@ -1613,16 +1613,18 @@ impl LxmRouter { return refreshed; } - if !configured_static && !self.config.autopeer { + // A static peer is created only at startup; once unpeered, its announces are ignored. + if configured_static { return false; } - if !configured_static - && hops.is_some_and(|h| h as usize > self.config.ext.autopeer_maxdepth) - { + if !self.config.autopeer { + return false; + } + if hops.is_some_and(|h| h as usize > self.config.ext.autopeer_maxdepth) { return false; } - let mut peer = LxmPeer::from_announce_with_metadata( + let peer = LxmPeer::from_announce_with_metadata( destination_hash, timebase, transfer_limit, @@ -1632,10 +1634,6 @@ impl LxmRouter { peering_cost, metadata, ); - if configured_static { - peer.is_static = true; - peer.autopeered = false; - } self.add_peer(peer) } @@ -1745,7 +1743,7 @@ impl LxmRouter { /// Set the advertised per-transfer propagation limit in decimal kB. /// This does not set total storage capacity or update a separate node owner. - pub fn set_propagation_limit(&mut self, limit_kb: usize) { + pub fn set_propagation_limit(&mut self, limit_kb: f64) { self.config.propagation_limit_kb = limit_kb; } @@ -2785,8 +2783,8 @@ pub struct PeerStats { pub struct NodeStats { pub uptime: f64, pub delivery_limit: f64, - pub propagation_limit: usize, - pub sync_limit: usize, + pub propagation_limit: f64, + pub sync_limit: f64, pub stamp_cost: f64, pub stamp_flex: f64, pub peering_cost: f64, @@ -4259,20 +4257,13 @@ mod tests { } #[test] - fn configured_static_announce_recreates_missing_peer_with_autopeer_disabled() { + fn unpeered_static_peer_is_not_recreated_by_its_announce() { let peer_hash = [0xA5; 16]; - let mut router = LxmRouter::new(RouterConfig { - autopeer: false, - ext: RouterConfigExt { - autopeer_maxdepth: 1, - ..Default::default() - }, - ..Default::default() - }); + let mut router = LxmRouter::new(RouterConfig::default()); router.static_peers.push(peer_hash); router.remove_peer(&peer_hash); - assert!(router.autopeer(AutopeerCandidate { + assert!(!router.autopeer(AutopeerCandidate { destination_hash: peer_hash, timebase: 101.0, transfer_limit: Some(2.0), @@ -4280,21 +4271,10 @@ mod tests { stamp_cost: Some(16.0), stamp_flexibility: Some(3.0), peering_cost: Some(18.0), - metadata: Some(std::collections::HashMap::from([( - crate::constants::PN_META_NAME, - b"static".to_vec(), - )])), - hops: Some(99), + metadata: None, + hops: Some(1), })); - let peer = router.peers.get(&peer_hash).unwrap(); - assert!(peer.is_static); - assert!(!peer.autopeered); - assert_eq!( - peer.metadata - .as_ref() - .and_then(|metadata| metadata.get(&crate::constants::PN_META_NAME)), - Some(&b"static".to_vec()) - ); + assert!(!router.peers.contains_key(&peer_hash)); } #[test] diff --git a/crates/lxmf-core/tests/relay_store_v2.rs b/crates/lxmf-core/tests/relay_store_v2.rs index 5fb6e26..dc34505 100644 --- a/crates/lxmf-core/tests/relay_store_v2.rs +++ b/crates/lxmf-core/tests/relay_store_v2.rs @@ -182,7 +182,7 @@ fn purge_cannot_report_success_when_its_durable_intent_cannot_be_published() { assert!(!reopened.contains(&tid)); } #[test] -fn purge_is_durable_before_success_and_old_plan_cannot_delete_readmission() { +fn purge_is_durable_and_purged_message_is_not_readmitted() { let dir = tempfile::tempdir().unwrap(); let old = dir.path().join("store"); let destination = [2; 16]; @@ -199,19 +199,17 @@ fn purge_is_durable_before_success_and_old_plan_cannot_delete_readmission() { assert_eq!(purge.into_response(), encode(&Value::Array(vec![]))); assert!(!node.contains(&tid)); assert!(!old_path.exists()); - let replacement = reserve(&mut node, bytes.clone()); - assert!(node.commit_store_write(replacement.persist().unwrap())); - let new_path = node.plan_message_reads(&[tid]).pop().unwrap().path; - assert_ne!(old_path, new_path); - // The old plan fails or sees an already completed retirement; it cannot - // gain authority over the distinct new admission path. + // A purged message stays processed and is filtered on re-upload. + assert!(matches!( + node.plan_opaque_admission(validated(bytes.clone())), + PropagationAdmission::AlreadyProcessed + )); let _ = stale.into_response(); - assert!(node.contains(&tid)); - assert_eq!(std::fs::read(&new_path).unwrap(), bytes); + assert!(!node.contains(&tid)); drop(node); let reopened = PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).unwrap(); - assert!(reopened.contains(&tid)); + assert!(!reopened.contains(&tid)); } #[test] fn foreign_purge_has_no_effect_and_maintenance_publishes_retirement_off_lock() { diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index 2c1d1ef..8962dcc 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -443,8 +443,8 @@ fn accepts_delivery_resource(data_size: usize, limit_kb: f64) -> bool { data_size as f64 <= limit_kb * lxmf_core::constants::BYTES_PER_KILOBYTE as f64 } -fn configured_kilobytes_to_bytes(kilobytes: usize) -> usize { - kilobytes.saturating_mul(lxmf_core::constants::BYTES_PER_KILOBYTE) +fn configured_kilobytes_to_bytes(kilobytes: f64) -> usize { + (kilobytes.max(0.0) * lxmf_core::constants::BYTES_PER_KILOBYTE as f64) as usize } fn delivery_resource_event_from_runtime(event: LinkResourceEvent) -> Option { @@ -770,6 +770,8 @@ fn execute_pn_packet_job(job: PnPacketValidationJob) -> PnPacketExecution { } } Ok(PropagationAdmission::Pending(waiter)) => pending.push(waiter), + // Python still proves a packet whose messages were filtered as duplicates. + Ok(PropagationAdmission::AlreadyProcessed) => {} _ => { result.stored = false; break; @@ -1758,6 +1760,20 @@ struct LxmdRunner { } impl LxmdRunner { + /// LXMF keeps one processed-ID store for local delivery and propagation intake. + fn merge_processed_ids(&mut self) { + let Some(node) = self.propagation_node.as_ref() else { + return; + }; + let Ok(mut node) = node.lock() else { + return; + }; + node.merge_processed_ids(self.router.propagation_store.locally_processed_ids()); + for (id, seen) in node.processed_ids() { + self.router.propagation_store.claim_processed(*id, *seen); + } + } + async fn install_announce_subscriptions( &mut self, rns_handle: &ReticulumHandle, @@ -3837,6 +3853,7 @@ impl LxmdRunner { let mut peers_to_persist = HashSet::new(); let mut finished = Vec::new(); let mut resync = Vec::new(); + let mut unpeered = Vec::new(); for (peer_hash, sync) in &mut self.peer_syncs { sync.drain_events(&self.known_identities); sync.tick(); @@ -3900,6 +3917,9 @@ impl LxmdRunner { peer.currently_transferring_messages = None; peer.next_sync_attempt = now + lxmf_core::constants::PN_STAMP_THROTTLE as f64; } + lxmf_core::propagation_sync::PeerSyncTerminalState::NoAccess => { + unpeered.push(result.peer_hash); + } lxmf_core::propagation_sync::PeerSyncTerminalState::Failed => { peer.sync_failed(); } @@ -3909,6 +3929,21 @@ impl LxmdRunner { for peer_hash in finished { self.peer_syncs.remove(&peer_hash); } + for peer_hash in unpeered { + // LXMRouter.unpeer drops the live peering only. + tracing::info!(peer = %hex::encode(peer_hash), "remote denied access, broke peering"); + self.router.remove_peer(&peer_hash); + peers_to_persist.remove(&peer_hash); + if let Some(ref node) = self.propagation_node + && let Ok(mut node) = node.lock() + && let Err(error) = node.delete_peer(&peer_hash) + { + tracing::warn!( + peer = %hex::encode(peer_hash), + "failed to remove persisted propagation peer: {error}" + ); + } + } // Python resource_concluded(): a persistent peer with messages left syncs again. for peer_hash in resync { self.attempt_peer_sync(peer_hash, now); @@ -4274,16 +4309,17 @@ impl LxmdRunner { Ok(Err(error)) => { tracing::warn!(%error, "relay maintenance remains pending"); self.prop_maintenance_task = None; - self.last_cull = now - 240.0; + self.last_cull = now - 420.0; } Err(oneshot::error::TryRecvError::Closed) => { self.prop_maintenance_task = None; - self.last_cull = now - 240.0; + self.last_cull = now - 420.0; } Err(oneshot::error::TryRecvError::Empty) => {} } } - if self.prop_maintenance_task.is_none() && now - self.last_cull > 300.0 { + // JOB_STORE_INTERVAL * PROCESSING_INTERVAL, the cadence of LXMRouter.clean_message_store. + if self.prop_maintenance_task.is_none() && now - self.last_cull > 480.0 { // Reserve only metadata under the lock. Native durable deletion // barriers run on one joined worker, away from receipt dispatch. if let Some(ref pn) = self.propagation_node @@ -4318,6 +4354,7 @@ impl LxmdRunner { } } if self.checkpoint_task.is_none() && now - self.last_crypto_save > 300.0 { + self.merge_processed_ids(); let checkpoint = DaemonCheckpoint { ratchets: self.ratchets_dir.clone(), received: self.received_ratchets.clone(), @@ -6485,6 +6522,7 @@ pub(crate) async fn main() { if let Err(e) = runner.router.load_state(&runner.data_dir) { tracing::warn!("Failed to load persisted router state: {e}"); } else { + runner.merge_processed_ids(); tracing::info!( "Loaded persisted router state from {}", runner.data_dir.display() @@ -6946,6 +6984,7 @@ pub(crate) async fn main() { // Python exit_handler() saves every peer's synchronisation state. runner.flush_peer_distribution_queue(); runner.save_all_peers(); + runner.merge_processed_ids(); if let Err(e) = runner.router.save_state(&runner.data_dir) { tracing::warn!("Failed to save router state on shutdown: {e}"); if one_shot_status.is_some() { @@ -7963,10 +8002,10 @@ mod tests { assert!(accepts_delivery_resource(380, 0.38)); assert!(!accepts_delivery_resource(381, 0.38)); - assert_eq!(configured_kilobytes_to_bytes(1), 1_000); - assert_eq!(configured_kilobytes_to_bytes(256), 256_000); - assert_eq!(configured_kilobytes_to_bytes(10_240), 10_240_000); - assert_eq!(configured_kilobytes_to_bytes(usize::MAX), usize::MAX); + assert_eq!(configured_kilobytes_to_bytes(1.0), 1_000); + assert_eq!(configured_kilobytes_to_bytes(0.5), 500); + assert_eq!(configured_kilobytes_to_bytes(10_240.0), 10_240_000); + assert_eq!(configured_kilobytes_to_bytes(f64::MAX), usize::MAX); } #[tokio::test(flavor = "current_thread")] diff --git a/crates/lxmf-tools/src/daemon.rs b/crates/lxmf-tools/src/daemon.rs index a63f624..b408181 100644 --- a/crates/lxmf-tools/src/daemon.rs +++ b/crates/lxmf-tools/src/daemon.rs @@ -421,8 +421,8 @@ pub struct DaemonConfig { pub sequential_pn_stamp_validation: bool, pub static_peers_bypass_sequential: bool, pub max_inbound_syncs: usize, - pub propagation_limit_kb: usize, - pub sync_limit_kb: usize, + pub propagation_limit_kb: f64, + pub sync_limit_kb: f64, pub on_inbound_command: Option, pub node_announce_at_start: bool, pub node_announce_interval: Option, @@ -460,8 +460,8 @@ impl Default for DaemonConfig { sequential_pn_stamp_validation: true, static_peers_bypass_sequential: true, max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS, - propagation_limit_kb: PROPAGATION_LIMIT, - sync_limit_kb: SYNC_LIMIT, + propagation_limit_kb: PROPAGATION_LIMIT as f64, + sync_limit_kb: SYNC_LIMIT as f64, on_inbound_command: None, node_announce_at_start: false, node_announce_interval: None, @@ -551,8 +551,8 @@ impl DaemonConfig { sequential_pn_stamp_validation: py.sequential_pn_stamp_validation, static_peers_bypass_sequential: py.static_peers_bypass_sequential, max_inbound_syncs: usize::try_from(py.max_inbound_syncs).unwrap_or(usize::MAX), - propagation_limit_kb: kb_to_usize_ceil(py.propagation_transfer_max_accepted_size), - sync_limit_kb: kb_to_usize_ceil(py.propagation_sync_max_accepted_size), + propagation_limit_kb: py.propagation_transfer_max_accepted_size, + sync_limit_kb: py.propagation_sync_max_accepted_size, on_inbound_command: py.on_inbound, node_announce_at_start: py.node_announce_at_start, node_announce_interval: seconds_to_u64(py.node_announce_interval), @@ -587,11 +587,14 @@ impl DaemonConfig { && get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none() && let Some(limit) = sec.get_uint("propagation_limit") { - dc.propagation_limit_kb = limit as usize; + dc.propagation_limit_kb = limit as f64; } dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false); } + // LXMRouter raises the per-sync limit to the per-transfer limit. + dc.sync_limit_kb = dc.sync_limit_kb.max(dc.propagation_limit_kb); + if let Some(sec) = config.section("control") { if !dc.auth_required { dc.auth_required = sec.get_bool_or("auth_required", false); @@ -619,10 +622,6 @@ fn seconds_to_u64(value: Option) -> Option { value.map(|seconds| seconds.max(0) as u64) } -fn kb_to_usize_ceil(value: f64) -> usize { - value.max(0.0).ceil().max(1.0) as usize -} - fn megabytes_to_bytes(value: f64) -> Option { let bytes = (value.max(0.0) * 1_000_000.0) as usize; (bytes > 0).then_some(bytes) @@ -853,8 +852,8 @@ mod tests { dc.to_inbound_admission_config(), PnInboundAdmissionConfig::default() ); - assert_eq!(dc.propagation_limit_kb, 256); - assert_eq!(dc.sync_limit_kb, 10_240); + assert_eq!(dc.propagation_limit_kb, 256.0); + assert_eq!(dc.sync_limit_kb, 10_240.0); assert!(!dc.node_announce_at_start); assert_eq!(dc.node_announce_interval, None); assert_eq!(dc.message_storage_limit, Some(500_000_000)); @@ -983,7 +982,7 @@ propagation_transfer_max_accepted_size = 12 let dc = DaemonConfig::from_config(&config).unwrap(); assert_eq!( - dc.propagation_limit_kb, 256, + dc.propagation_limit_kb, 256.0, "DaemonConfig should match Python 0.9.6 handling of legacy propagation_transfer_max_accepted_size" ); } @@ -996,8 +995,8 @@ propagation_transfer_max_accepted_size = 12 assert_eq!(rc.max_peers, 20); assert_eq!(rc.delivery_limit_kb, 1.0); assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0); - assert_eq!(rc.propagation_limit_kb, 256); - assert_eq!(rc.sync_limit_kb, 10_240); + assert_eq!(rc.propagation_limit_kb, 256.0); + assert_eq!(rc.sync_limit_kb, 10_240.0); assert_eq!(rc.propagation_stamp_cost, 16.0); assert_eq!(rc.propagation_stamp_flex, 3.0); assert_eq!(rc.ext.autopeer_maxdepth, AUTOPEER_MAXDEPTH); @@ -1075,8 +1074,8 @@ from_static_only = yes assert!(dc.node_announce_at_start); assert_eq!(dc.node_announce_interval, Some(120)); assert_eq!(dc.message_storage_limit, Some(5_000)); - assert_eq!(dc.propagation_limit_kb, 1); - assert_eq!(dc.sync_limit_kb, 1); + assert_eq!(dc.propagation_limit_kb, 0.38); + assert_eq!(dc.sync_limit_kb, 0.38); assert_eq!(dc.propagation_stamp_cost, 13.0); assert_eq!(dc.propagation_stamp_flex, 0.0); assert_eq!(dc.peering_cost, 0.0); diff --git a/crates/lxmf-tools/src/lxmd_control.rs b/crates/lxmf-tools/src/lxmd_control.rs index 3b7c22c..81d4aee 100644 --- a/crates/lxmf-tools/src/lxmd_control.rs +++ b/crates/lxmf-tools/src/lxmd_control.rs @@ -69,6 +69,15 @@ pub async fn query_control( .await } +/// lxmd limits are integers by default and `as_float` values when configured. +fn kilobytes_value(kilobytes: f64) -> Value { + if kilobytes.fract() == 0.0 && kilobytes.abs() < i64::MAX as f64 { + Value::from(kilobytes as i64) + } else { + Value::F64(kilobytes) + } +} + /// Python adds the timeout to `time.time()`: a negative one has already /// expired, and an infinite or NaN one never does. fn control_deadline(timeout_secs: f64) -> Duration { @@ -313,11 +322,11 @@ pub fn encode_router_control_stats( ), ( Value::String("propagation_limit".into()), - Value::from(router.config.propagation_limit_kb as u64), + kilobytes_value(router.config.propagation_limit_kb), ), ( Value::String("sync_limit".into()), - Value::from(router.config.sync_limit_kb as u64), + kilobytes_value(router.config.sync_limit_kb), ), ( Value::String("target_stamp_cost".into()),