propagation: age-based dedup cache retention with persisted timestamps

This commit is contained in:
DeFiDude committed 2026-06-10 00:33:43 -06:00
1 parent 2fc60703ea
commit 9e44e8a407
3 files changed
+112 -50

No files matched your search

+8
View File
@@ -32,6 +32,14 @@
//!
//! [`DiscoveryStamper`]: rns_transport::discovery::DiscoveryStamper
/// Unix time as f64 seconds — Python `time.time()` equivalent.
pub(crate) fn now_f64() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
pub mod constants;
pub mod discovery_stamper;
pub mod handlers;
+51 -16
View File
@@ -98,8 +98,10 @@ impl PropagationEntry {
pub struct PropagationStore {
entries: HashMap<PropagationTransientId, PropagationEntry>,
total_size: usize,
locally_delivered_ids: HashSet<PropagationTransientId>,
locally_processed_ids: HashSet<PropagationTransientId>,
/// Dedup caches: transient ID → first-seen Unix time. Age-based retention
/// (`MESSAGE_EXPIRY * 6`), persisted with their real timestamps.
locally_delivered_ids: HashMap<PropagationTransientId, f64>,
locally_processed_ids: HashMap<PropagationTransientId, f64>,
ignored_destinations: HashSet<[u8; 16]>,
/// Prioritised destinations receive a 0.1x weight multiplier during culling.
prioritised_destinations: HashSet<[u8; 16]>,
@@ -256,45 +258,49 @@ impl PropagationStore {
}
pub fn mark_locally_delivered(&mut self, transient_id: PropagationTransientId) {
self.locally_delivered_ids.insert(transient_id);
self.locally_delivered_ids
.insert(transient_id, crate::now_f64());
}
pub fn is_locally_delivered(&self, transient_id: &PropagationTransientId) -> bool {
self.locally_delivered_ids.contains(transient_id)
self.locally_delivered_ids.contains_key(transient_id)
}
pub fn mark_locally_processed(&mut self, transient_id: PropagationTransientId) {
self.locally_processed_ids.insert(transient_id);
self.locally_processed_ids
.insert(transient_id, crate::now_f64());
}
pub fn is_locally_processed(&self, transient_id: &PropagationTransientId) -> bool {
self.locally_processed_ids.contains(transient_id)
self.locally_processed_ids.contains_key(transient_id)
}
pub fn locally_delivered_ids(&self) -> &HashSet<PropagationTransientId> {
pub fn locally_delivered_ids(&self) -> &HashMap<PropagationTransientId, f64> {
&self.locally_delivered_ids
}
pub fn locally_processed_ids(&self) -> &HashSet<PropagationTransientId> {
pub fn locally_processed_ids(&self) -> &HashMap<PropagationTransientId, f64> {
&self.locally_processed_ids
}
pub fn replace_locally_delivered(&mut self, ids: HashSet<PropagationTransientId>) {
pub fn replace_locally_delivered(&mut self, ids: HashMap<PropagationTransientId, f64>) {
self.locally_delivered_ids = ids;
}
pub fn replace_locally_processed(&mut self, ids: HashSet<PropagationTransientId>) {
pub fn replace_locally_processed(&mut self, ids: HashMap<PropagationTransientId, f64>) {
self.locally_processed_ids = ids;
}
/// Drop cache entries whose transient IDs no longer exist in `entries`
/// (i.e. were culled). Python removes them once older than
/// MESSAGE_EXPIRY * 6; the caller decides the cutoff here.
pub fn clean_transient_caches(&mut self) {
/// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python
/// `LXMRouter.clean_transient_id_caches`, LXMRouter.py:956). Retention is
/// purely age-based: entries must outlive their store membership so a
/// culled-and-reoffered message is still recognised as already handled.
pub fn clean_transient_caches(&mut self, now: f64) {
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
self.locally_delivered_ids
.retain(|id| self.entries.contains_key(id));
.retain(|_, timestamp| now <= *timestamp + expiry);
self.locally_processed_ids
.retain(|id| self.entries.contains_key(id));
.retain(|_, timestamp| now <= *timestamp + expiry);
}
/// `from_peer` is the peer we received this message from, or `None` if it
@@ -515,6 +521,35 @@ mod tests {
assert!(store.is_locally_processed(&transient_id));
}
/// T1-10: dedup caches are age-based (Python MESSAGE_EXPIRY*6), not keyed
/// to store membership — a culled-and-reoffered message must still be
/// recognised; entries expire only once their timestamp ages out.
#[test]
fn test_transient_caches_age_based_retention() {
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
let mut store = PropagationStore::new();
let transient_id = tid(0xAA);
store.mark_locally_delivered(transient_id);
store.mark_locally_processed(transient_id);
let stamped_at = *store.locally_delivered_ids().get(&transient_id).unwrap();
// The entry was never inserted into the store at all — cleaning must
// still retain it while it is young (store-cull independence).
store.clean_transient_caches(stamped_at + 60.0);
assert!(store.is_locally_delivered(&transient_id));
assert!(store.is_locally_processed(&transient_id));
// Still retained just inside the expiry horizon...
store.clean_transient_caches(stamped_at + expiry - 1.0);
assert!(store.is_locally_delivered(&transient_id));
// ...and dropped once aged out.
store.clean_transient_caches(stamped_at + expiry + 1.0);
assert!(!store.is_locally_delivered(&transient_id));
assert!(!store.is_locally_processed(&transient_id));
}
#[test]
fn test_cull_by_weight() {
let mut store = PropagationStore::new();
+53 -34
View File
@@ -3,6 +3,7 @@
//! Python reference: LXMF/LXMRouter.py. Actor pattern — a single tokio task owns
//! all mutable state.
use crate::now_f64;
use std::collections::HashMap;
use std::fmt;
@@ -15,7 +16,6 @@ use crate::peer::LxmPeer;
use crate::propagation::PropagationStore;
use crate::stamper;
use crate::ticket::{Ticket, TicketStore};
use crate::types::PropagationTransientId;
/// Router configuration.
///
@@ -856,18 +856,18 @@ impl LxmRouter {
}
/// Load persisted runtime state (stamp costs, tickets, dedup sets) from
/// `state_dir`. Missing files are treated as empty state.
/// `state_dir`. Missing files are treated as empty state. Dedup-cache
/// timestamps are restored as persisted so age-based expiry survives
/// restarts.
pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?;
self.ticket_store
.replace_all(persist::load_tickets(state_dir)?);
let delivered = persist::load_local_deliveries(state_dir)?;
let processed = persist::load_locally_processed(state_dir)?;
self.propagation_store
.replace_locally_delivered(delivered.keys().copied().collect());
.replace_locally_delivered(persist::load_local_deliveries(state_dir)?);
self.propagation_store
.replace_locally_processed(processed.keys().copied().collect());
.replace_locally_processed(persist::load_locally_processed(state_dir)?);
Ok(())
}
@@ -875,29 +875,11 @@ impl LxmRouter {
/// periodically; each file is written atomically via rename.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
use std::time::{SystemTime, UNIX_EPOCH};
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, self.ticket_store.all())?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let delivered: std::collections::HashMap<PropagationTransientId, f64> = self
.propagation_store
.locally_delivered_ids()
.iter()
.map(|id| (*id, now))
.collect();
let processed: std::collections::HashMap<PropagationTransientId, f64> = self
.propagation_store
.locally_processed_ids()
.iter()
.map(|id| (*id, now))
.collect();
persist::save_local_deliveries(state_dir, &delivered)?;
persist::save_locally_processed(state_dir, &processed)?;
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
Ok(())
}
@@ -1730,7 +1712,7 @@ impl LxmRouter {
fn run_periodic_jobs(&mut self) {
// Job cadences match the Python LXMRouter jobloop.
if self.processing_count.is_multiple_of(JOB_TRANSIENT_INTERVAL) {
self.propagation_store.clean_transient_caches();
self.propagation_store.clean_transient_caches(now_f64());
}
if self.processing_count.is_multiple_of(JOB_STORE_INTERVAL)
&& self.config.propagation_enabled
@@ -1834,13 +1816,6 @@ pub struct NodeStats {
pub peer_stats: HashMap<[u8; 16], PeerStats>,
}
fn now_f64() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2408,6 +2383,50 @@ mod tests {
assert!(r2.propagation_store.is_locally_processed(&transient_a));
}
/// T1-10: persisted dedup timestamps are the REAL first-seen times —
/// restored on load (not reset to save-time), so age-based expiry is
/// stable across arbitrarily many save/load cycles.
#[test]
fn test_dedup_cache_timestamps_survive_save_load_cycles() {
let tmp = tempfile::TempDir::new().unwrap();
let transient = [0x42; 32];
let mut router = LxmRouter::new(RouterConfig::default());
router.propagation_store.mark_locally_delivered(transient);
let original_ts = *router
.propagation_store
.locally_delivered_ids()
.get(&transient)
.unwrap();
// Multiple save/load cycles must not refresh the timestamp.
for _ in 0..3 {
router.save_state(tmp.path()).unwrap();
let mut reloaded = LxmRouter::new(RouterConfig::default());
reloaded.load_state(tmp.path()).unwrap();
let loaded_ts = *reloaded
.propagation_store
.locally_delivered_ids()
.get(&transient)
.unwrap();
assert_eq!(loaded_ts, original_ts, "timestamp must survive reload");
router = reloaded;
}
assert_eq!(router.propagation_store.locally_delivered_ids().len(), 1);
// An aged-out entry is gone after the periodic clean, and stays gone
// through persistence (growth bounded).
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
router
.propagation_store
.clean_transient_caches(original_ts + expiry + 1.0);
assert!(!router.propagation_store.is_locally_delivered(&transient));
router.save_state(tmp.path()).unwrap();
let mut fresh = LxmRouter::new(RouterConfig::default());
fresh.load_state(tmp.path()).unwrap();
assert!(fresh.propagation_store.locally_delivered_ids().is_empty());
}
#[test]
fn test_load_state_missing_dir_is_ok() {
let tmp = tempfile::TempDir::new().unwrap();