persistence: save and clean known destinations and caches as upstream

This commit is contained in:
DeFiDude committed 2026-11-10 05:08:57 -07:00
1 parent fd005be9bd
commit 1897c8b666
10 files changed
+438 -120

No files matched your search

+11 -46
View File
@@ -1,7 +1,7 @@
//! Poll-driven scheduling of cache cleaning after 15 minutes and persistence
//! after 12 hours. Explicit persistence requests can emit a job once five
//! minutes have elapsed since the last gracious persist. Callers must poll
//! `tick` and execute the returned jobs; this module starts no timer or I/O.
//! Poll-driven scheduling of cache cleaning at start and every 15 minutes, and
//! persistence after 12 hours. The transport actor owns the gracious persist on
//! local client disconnect. Callers must poll `tick` and execute the returned
//! jobs; this module starts no timer or I/O.
use std::time::{Duration, Instant};
@@ -10,18 +10,17 @@ use crate::constants::*;
pub struct JobScheduler {
last_clean: Instant,
last_persist: Instant,
persist_requested: bool,
last_gracious_persist: Instant,
}
impl JobScheduler {
pub fn new() -> Self {
let now = Instant::now();
Self {
last_clean: now,
// Python starts with `last_cache_clean = 0`, so the first tick cleans.
last_clean: now
.checked_sub(Duration::from_secs(CLEAN_INTERVAL))
.unwrap_or(now),
last_persist: now,
persist_requested: false,
last_gracious_persist: now,
}
}
@@ -40,24 +39,10 @@ impl JobScheduler {
if now.duration_since(self.last_persist) >= Duration::from_secs(PERSIST_INTERVAL) {
jobs.push(Job::PersistData);
self.last_persist = now;
self.persist_requested = false;
}
if self.persist_requested
&& now.duration_since(self.last_gracious_persist)
>= Duration::from_secs(GRACIOUS_PERSIST_INTERVAL)
{
jobs.push(Job::PersistData);
self.last_gracious_persist = now;
self.persist_requested = false;
}
jobs
}
pub fn request_persist(&mut self) {
self.persist_requested = true;
}
}
impl Default for JobScheduler {
@@ -77,30 +62,10 @@ mod tests {
use super::*;
#[test]
fn test_scheduler_initial_tick() {
fn test_scheduler_initial_tick_cleans_caches() {
let mut scheduler = JobScheduler::new();
let jobs = scheduler.tick();
assert!(jobs.is_empty());
}
#[test]
fn test_scheduler_persist_request() {
let mut scheduler = JobScheduler::new();
assert!(!scheduler.persist_requested);
scheduler.request_persist();
assert!(scheduler.persist_requested);
}
#[test]
fn test_scheduler_forced_persist() {
let mut scheduler = JobScheduler::new();
let now = Instant::now();
scheduler.last_gracious_persist = now;
scheduler.request_persist();
let jobs = scheduler.tick_at(now + Duration::from_secs(GRACIOUS_PERSIST_INTERVAL + 1));
assert!(jobs.contains(&Job::PersistData));
assert!(!scheduler.persist_requested);
assert_eq!(scheduler.tick(), vec![Job::CleanCache]);
assert!(scheduler.tick().is_empty());
}
#[test]
+43 -4
View File
@@ -1777,8 +1777,10 @@ impl ReticulumHandle {
}
/// Read identity and announce metadata from this process's transport cache
/// without extending its lifetime. This remains a local lookup in Client
/// mode, even when the shared owner knows more.
/// and mark the destination used, like Python's `Identity.recall`. The
/// lookup stays local in Client mode; the use mark goes to the shared owner
/// over RPC, as Python's `_used_destination_data` does. A failed use mark
/// does not fail the recall.
///
/// The helper does not verify a fresh signature or check current presence.
/// Stored cache metadata can be restored with structural checks alone; keep
@@ -1787,6 +1789,23 @@ impl ReticulumHandle {
pub async fn recall(
&self,
destination_hash: [u8; 16],
) -> Result<Option<RecalledDestination>, ControlError> {
let recalled = self.recall_without_use(destination_hash).await?;
if recalled.is_some() {
let _ = self
.query_control_result(TransportQuery::UseDestination {
dest: destination_hash,
})
.await;
}
Ok(recalled)
}
/// `recall` without marking the destination used (Python `_no_use=True`),
/// for displays and internal lookups that must not extend retention.
pub async fn recall_without_use(
&self,
destination_hash: [u8; 16],
) -> Result<Option<RecalledDestination>, ControlError> {
let mut recalled = self.recall_identity(destination_hash).await?;
if let Some(recalled) = recalled.as_mut() {
@@ -9544,7 +9563,8 @@ fn clean_cache_dir_at(cache_dir: &Path, ttl: std::time::Duration, now: std::time
if let Ok(entries) = std::fs::read_dir(cache_dir) {
for entry in entries.flatten() {
let file_name = entry.file_name();
if file_name.as_encoded_bytes().len() != 32 {
// Python matches names of full-hash hex length, (HASHLENGTH//8)*2.
if file_name.as_encoded_bytes().len() != 64 {
continue;
}
if let Ok(metadata) = entry.metadata()
@@ -11951,6 +11971,18 @@ loglevel = 7
.send(TransportQueryResponse::FloatResult(value))
.expect("stamp response receiver");
}
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("use query")
else {
panic!("expected transport RPC");
};
assert!(matches!(
query,
TransportQuery::UseDestination { dest } if dest == destination_hash
));
response_tx
.send(TransportQueryResponse::BoolResult(true))
.expect("use response receiver");
});
let mut handle = dummy_handle();
@@ -16989,7 +17021,10 @@ port = 37428
fs::create_dir_all(&cache_dir).unwrap();
fs::create_dir_all(&resource_dir).unwrap();
let hash_name = "0123456789abcdef0123456789abcdef";
let hash_name = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let short_name = "0123456789abcdef0123456789abcdef";
let short_path = resource_dir.join(short_name);
fs::write(&short_path, b"keep").unwrap();
let packet_path = cache_dir.join(hash_name);
let resource_path = resource_dir.join(hash_name);
let unrelated_path = resource_dir.join("unrelated");
@@ -17018,6 +17053,10 @@ port = 37428
unrelated_path.exists(),
"non-hash files are not cache entries"
);
assert!(
short_path.exists(),
"names shorter than a full hash are not cache entries"
);
let packet_modified = fs::metadata(&packet_path).unwrap().modified().unwrap();
clean_cache_dir_at(
@@ -890,6 +890,9 @@ impl TransportActor {
tunnel.expires = now_f64() + TUNNEL_TIMEOUT as f64;
}
self.state_dirty = true;
if self.path_requests.contains_key(&header.destination_hash) {
self.use_destination(&header.destination_hash);
}
// Wake any callers waiting on a path for this destination.
self.fire_path_waiters(&header.destination_hash);
+58 -12
View File
@@ -27,7 +27,7 @@ impl TransportActor {
// addition to `on_shutdown` because mobile force-quit kills the
// process without delivering Shutdown. Hashlist is saved separately.
if self.storage_dir.is_some()
&& self.state_dirty
&& (self.state_dirty || self.routing_save_pending)
&& now - self.last_state_save >= STATE_SAVE_INTERVAL_SECS
{
// Async: the fsync chain (F_FULLFSYNC per file on macOS) stalls
@@ -36,6 +36,13 @@ impl TransportActor {
self.save_routing_state_async();
}
if self.storage_dir.is_some()
&& self.state_dirty
&& now - self.last_known_destinations_flush >= KD_FLUSH_INTERVAL
{
self.flush_known_destinations_async();
}
if now - self.last_tables_cull >= TABLES_CULL_INTERVAL {
// Batched culls bound per-tick work; on large tables a single
// sweep would stall the actor and back up the inbound channel.
@@ -207,17 +214,21 @@ impl TransportActor {
if self.startup_complete && now - self.last_cache_clean >= CACHE_CLEAN_INTERVAL {
self.packet_hashlist.force_rotate();
self.cleanup_known_destinations(now);
self.last_cache_clean = now;
}
if now - self.last_known_destinations_clean >= KNOWN_DESTINATIONS_INTERVAL {
self.cleanup_known_destinations(now);
self.last_known_destinations_clean = now;
}
// On-disk announce-cache prune. Deliberately outside the
// startup_complete gate: that gate is stamped on first interface
// registration, and a node with no interfaces must still collect
// backlog (Python's jobs thread cleans unconditionally). Safe before
// interfaces exist — pending re-registration entries are in the
// keep-set and the mtime grace covers fresh writes. First sweep runs
// on the first tick after storage init, then every 15 minutes.
// keep-set and the mtime grace covers fresh writes. Storage init
// defers the first sweep, which then repeats every 5 minutes.
if now - self.last_announce_cache_sweep >= ANNOUNCE_CACHE_SWEEP_INTERVAL
&& self.maybe_sweep_announce_cache()
{
@@ -393,6 +404,7 @@ impl TransportActor {
self.last_announces_check = 0.0;
self.last_cache_clean = 0.0;
self.last_announce_cache_sweep = 0.0;
self.last_known_destinations_clean = 0.0;
self.last_blackhole_check = 0.0;
self.last_rate_cull = 0.0;
self.last_held_announce_check = 0.0;
@@ -612,13 +624,21 @@ impl TransportActor {
/// Sweep `recent_announces`, mirroring Python
/// `Identity.clean_known_destinations`: retained + pathed entries are
/// kept; pathless never-used entries die after `UNUSED_DESTINATION_LINGER`
/// (6 min); pathless used entries die after `DESTINATION_TIMEOUT * 1.25`
/// idle since last use.
/// kept; a pathless entry is stale when never used and announced more than
/// `UNUSED_DESTINATION_LINGER` ago, or when more than
/// `DESTINATION_TIMEOUT * 1.25` has passed since its use marker. A
/// never-used entry's marker is 0, so it is stale on any pass.
pub(super) fn cleanup_known_destinations(&mut self, now: f64) {
let used_threshold = DESTINATION_TIMEOUT as f64 * 1.25;
let before = self.recent_announces.len();
// Python loads persisted paths at start; Rust stages them until their
// interface registers, so a staged path counts as a path here.
let pending: HashSet<&[u8]> = self
.pending_path_entries
.iter()
.map(|pe| pe.destination_hash.as_slice())
.collect();
// Collect into a Vec; the has-path borrow on path_table fights an
// in-place `retain` closure on recent_announces.
let to_drop: Vec<[u8; 16]> = self
@@ -628,13 +648,15 @@ impl TransportActor {
if a.retained {
return None;
}
if self.path_table.has_path(&a.dest_hash) {
if self.path_table.has_path(&a.dest_hash)
|| pending.contains(a.dest_hash.as_slice())
{
return None;
}
let stale = match a.last_used {
None => now - a.timestamp > UNUSED_DESTINATION_LINGER,
Some(last_used) => now - last_used.max(a.timestamp) > used_threshold,
};
let unused_for = now - a.last_used.unwrap_or(0.0);
let stale = (a.last_used.is_none()
&& now - a.timestamp > UNUSED_DESTINATION_LINGER)
|| unused_for > used_threshold;
if stale { Some(a.dest_hash) } else { None }
})
.collect();
@@ -643,6 +665,7 @@ impl TransportActor {
for hash in &to_drop {
self.recent_announces.remove(hash);
}
self.state_dirty = true;
debug!(
removed = to_drop.len(),
remaining = self.recent_announces.len(),
@@ -742,6 +765,29 @@ mod cleanup_tests {
assert_eq!(actor.recent_announces.len(), 1);
}
#[test]
fn staged_persisted_path_keeps_entry_through_cleanup() {
let (mut actor, _tx) = TransportActor::new();
let now = 10_000_000.0;
insert_entry(&mut actor, 0x04, 0.0, /*retained=*/ false);
actor
.pending_path_entries
.push(crate::persistence::PersistedPathEntry {
destination_hash: vec![0x04; 16],
timestamp: now,
next_hop: None,
hops: 1,
expires: now + 1_000.0,
random_blobs: Vec::new(),
interface_id: 0,
interface_name: Some("not yet registered".into()),
interface_hash: None,
packet_hash: None,
});
actor.cleanup_known_destinations(now);
assert_eq!(actor.recent_announces.len(), 1);
}
#[test]
fn pathless_never_used_kept_inside_linger() {
let (mut actor, _tx) = TransportActor::new();
+59 -7
View File
@@ -180,10 +180,13 @@ pub struct TransportActor {
last_receipts_check: f64,
last_announces_check: f64,
last_cache_clean: f64,
/// Last on-disk announce-cache sweep. 0.0 until the first sweep is
/// actually scheduled, so a tick that fires before storage init doesn't
/// consume the boot slot.
/// Last on-disk announce-cache sweep. Storage init sets it 60 s ahead so
/// the first sweep is deferred like Python's.
last_announce_cache_sweep: f64,
last_known_destinations_clean: f64,
last_known_destinations_flush: f64,
/// Last full persist (scheduled or requested by a departing local client).
last_data_persist: f64,
last_blackhole_check: f64,
last_rate_cull: f64,
last_held_announce_check: f64,
@@ -255,6 +258,9 @@ pub struct TransportActor {
/// set it; queued/synchronous save paths can clear it before success is known.
/// It is not a reliable comparison between memory and durable disk state.
pub state_dirty: bool,
/// A known-destination flush took `state_dirty`; the routing tables still
/// wait for their periodic save.
routing_save_pending: bool,
/// Whether an asynchronous routing writer is in flight. The separate
/// publication lock and generation counter coordinate queued and synchronous
/// snapshots; this flag alone is not a cross-process writer lock.
@@ -464,6 +470,9 @@ impl TransportActor {
last_announces_check: 0.0,
last_cache_clean: 0.0,
last_announce_cache_sweep: 0.0,
last_known_destinations_clean: now_f64(),
last_known_destinations_flush: 0.0,
last_data_persist: now_f64(),
last_blackhole_check: 0.0,
last_rate_cull: 0.0,
last_held_announce_check: 0.0,
@@ -486,6 +495,7 @@ impl TransportActor {
hashlist_load_attempted: false,
last_state_save: 0.0,
state_dirty: false,
routing_save_pending: false,
routing_save_in_flight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
routing_save_generation: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
routing_save_lock: std::sync::Arc::new(std::sync::Mutex::new(())),
@@ -561,7 +571,7 @@ impl TransportActor {
self.handle_announce_dispatch(request);
}
Some(()) = self.persistence_rx.recv() => {
self.save_state_async();
self.persist_data_async();
}
Some(request) = self.path_recovery_rx.recv() => {
self.recover_local_link_path(request);
@@ -1602,7 +1612,9 @@ impl TransportActor {
/// `timestamp` stays the announce time (Python keeps announce time and
/// use time as separate fields); the linger sweep reads `last_used`.
pub(super) fn use_destination(&mut self, dest_hash: &[u8; 16]) -> bool {
if let Some(entry) = self.recent_announces.get_mut(dest_hash) {
if let Some(entry) = self.recent_announces.get_mut(dest_hash)
&& !entry.retained
{
entry.last_used = Some(now_f64());
self.state_dirty = true;
true
@@ -1611,11 +1623,11 @@ impl TransportActor {
}
}
/// Release a pin set by `retain_destination`; cleanup runs by `timestamp` again.
#[allow(dead_code)]
/// Release a pin set by `retain_destination`; the release counts as a use.
pub(super) fn unretain_destination(&mut self, dest_hash: &[u8; 16]) -> bool {
if let Some(entry) = self.recent_announces.get_mut(dest_hash) {
entry.retained = false;
entry.last_used = Some(now_f64());
self.state_dirty = true;
true
} else {
@@ -1691,6 +1703,9 @@ impl TransportActor {
self.retire_path_request_admissions(id);
self.retire_announce_interface(id);
self.interfaces.remove(&id);
if role == Some(InterfaceRole::LocalClient) {
self.maybe_gracious_persist();
}
if role == Some(InterfaceRole::SharedInstancePeer) {
tracing::warn!(
interface_id = id,
@@ -7856,6 +7871,10 @@ mod tests {
held_after_bypass, held_before,
"an announce whose destination is in path_requests must NOT be held"
);
assert!(
actor.recent_announces[&dest_match].last_used.is_some(),
"an announce answering our path request marks the destination used"
);
// Discovery requests on behalf of another peer use the same bypass.
let (raw_discovery, dest_discovery) = make_valid_announce("test.path_req.discovery", 1);
@@ -11597,6 +11616,10 @@ mod tests {
!actor.discovery_path_requests.contains_key(&dest),
"a validated discovery response consumes its live requesters once"
);
assert!(
actor.recent_announces[&dest].last_used.is_some(),
"answering a discovery path request marks the destination used"
);
}
#[test]
@@ -11902,6 +11925,7 @@ mod tests {
requestor_rx.try_recv().is_err(),
"must not answer a path request when the requestor is our next hop"
);
assert!(actor.recent_announces[&dest].last_used.is_none());
actor.handle_inbound_path_request(
&make_path_request_payload_with_tag(dest, Some([0xCD; 16]), [0xB6; 16]),
@@ -11917,6 +11941,10 @@ mod tests {
.expect("known path response should be queued");
assert!(queued.block_rebroadcast);
assert_eq!(queued.attached_interface, Some(1));
assert!(
actor.recent_announces[&dest].last_used.is_some(),
"answering a path request marks the destination used"
);
actor.flush_pending_announces();
let response = requestor_rx
@@ -12204,11 +12232,35 @@ mod tests {
crate::path_table::PathEntry::new(None, 0, 1, InterfaceMode::Gateway),
);
actor.recent_announces.insert(
dest,
RecentAnnounce {
dest_hash: dest,
hops: 0,
app_data: None,
timestamp: now_f64(),
public_key: None,
ratchet: None,
packet_hash: None,
is_path_response: false,
retained: false,
last_used: None,
name_hash: [0u8; 10],
stamp: None,
stamp_value: 0.0,
lr_cost: None,
},
);
actor.handle_inbound_path_request(&make_path_request_payload(dest, None), 2);
assert!(
actor.pending_local_path_requests.contains_key(&dest),
"external request for a local-client destination should be tracked"
);
assert!(
actor.recent_announces[&dest].last_used.is_some(),
"a path request for a local client's destination marks it used"
);
assert!(
local_rx.try_recv().is_ok(),
"external path request should be forwarded to local clients"
@@ -709,6 +709,7 @@ impl TransportActor {
{
self.pending_local_path_requests
.insert(requested_dest, interface_id);
self.use_destination(&requested_dest);
}
// Python Transport.py: local shared clients are allowed to use the
@@ -793,6 +794,9 @@ impl TransportActor {
source_interface: None,
},
);
if !self.shared_instance_client_mode {
self.use_destination(&requested_dest);
}
return;
}
}
+184 -42
View File
@@ -111,6 +111,16 @@ pub(super) struct RoutingSnapshot {
pub transport_identity_hash: Option<[u8; 16]>,
}
/// Persist known-destination metadata (`announce_cache.msgpack`).
pub(super) fn write_announce_metadata(dir: &std::path::Path, announces: &[RecentAnnounce]) {
let announce_path = dir.join("announce_cache.msgpack");
if let Err(e) = crate::persistence::save_announce_cache(announces.iter(), &announce_path) {
trace!("failed to save announce cache: {}", e);
} else {
debug!("saved announce cache ({} entries)", announces.len());
}
}
/// Persist a routing snapshot. Runs on the blocking pool for periodic saves
/// and inline for shutdown; must not touch the actor.
pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSnapshot) {
@@ -157,17 +167,7 @@ pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSn
}
}
let announce_path = dir.join("announce_cache.msgpack");
if let Err(e) =
crate::persistence::save_announce_cache(snapshot.recent_announces.iter(), &announce_path)
{
trace!("failed to save announce cache: {}", e);
} else {
debug!(
"saved announce cache ({} entries)",
snapshot.recent_announces.len()
);
}
write_announce_metadata(dir, &snapshot.recent_announces);
// Per-announce Python cache files are written event-driven at receive
// (`cache_announce_to_disk`), not re-serialized here every cycle.
@@ -229,10 +229,11 @@ impl TransportActor {
/// Event-driven announce cache write at receive (Python parity:
/// `Transport.cache(packet, force_cache=True)` on announce ingest).
/// One file per announce packet; skipped when the file already exists
/// (SINGLE announces are retransmitted byte-identical). No fsync — the
/// cache is best-effort and rebuilt from live traffic, and an fsync
/// chain here would stall the actor on every announce.
/// One file per announce packet; a later write for the same packet hash
/// replaces the bytes and interface reference, like Python's
/// `AnnounceCache.store`. No fsync — the cache is best-effort and rebuilt
/// from live traffic, and an fsync chain here would stall the actor on
/// every announce.
pub(super) fn cache_announce_to_disk(
&self,
packet_hash: &[u8; 32],
@@ -250,7 +251,7 @@ impl TransportActor {
.interfaces
.get(&interface_id)
.map(|entry| entry.name.clone());
if let Err(e) = crate::persistence::write_python_cached_announce_if_absent(
if let Err(e) = crate::persistence::write_python_cached_announce(
&announce_cache_dir,
packet_hash,
raw,
@@ -277,6 +278,70 @@ impl TransportActor {
}
}
/// Flush known-destination metadata (`announce_cache.msgpack`) on the
/// `KD_FLUSH_INTERVAL` cadence, off-actor and behind the routing writer's
/// in-flight guard. The routing tables keep their own periodic save.
pub(super) fn flush_known_destinations_async(&mut self) {
if self.shared_instance_client_mode {
self.last_known_destinations_flush = now();
return;
}
let Some(dir) = self.storage_dir.clone() else {
return;
};
if self
.routing_save_in_flight
.load(std::sync::atomic::Ordering::Acquire)
{
return;
}
self.routing_save_in_flight
.store(true, std::sync::atomic::Ordering::Release);
let announces: Vec<RecentAnnounce> = self.recent_announces.values().cloned().collect();
// A newer synchronous snapshot bumps the generation and supersedes this one.
let generation = self
.routing_save_generation
.load(std::sync::atomic::Ordering::Acquire);
let latest_generation = self.routing_save_generation.clone();
let write_lock = self.routing_save_lock.clone();
let in_flight = self.routing_save_in_flight.clone();
let write = move || {
let _guard = write_lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if latest_generation.load(std::sync::atomic::Ordering::Acquire) == generation {
write_announce_metadata(&dir, &announces);
}
in_flight.store(false, std::sync::atomic::Ordering::Release);
};
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
handle.spawn_blocking(write);
}
Err(_) => write(),
}
if self.state_dirty {
self.state_dirty = false;
self.routing_save_pending = true;
}
self.last_known_destinations_flush = now();
}
/// Full persist of routing state, known destinations and the hashlist
/// (Python `Reticulum.__persist_data`), off-actor.
pub(super) fn persist_data_async(&mut self) {
self.save_state_async();
self.last_data_persist = now();
}
/// Python `Reticulum._should_persist_data`, called when a local client
/// disconnects: persist unless one ran within `GRACIOUS_PERSIST_INTERVAL`.
pub(super) fn maybe_gracious_persist(&mut self) {
if now() > self.last_data_persist + GRACIOUS_PERSIST_INTERVAL {
self.persist_data_async();
}
}
/// Periodic flush used by `on_tick`: snapshot on the actor (cheap clones)
/// and push the fsync-heavy writes to the blocking pool. A save already
/// in flight keeps `state_dirty` set so the next tick retries — two
@@ -331,14 +396,15 @@ impl TransportActor {
}
}
self.state_dirty = false;
self.routing_save_pending = false;
self.last_state_save = now();
}
/// Reference-counted prune of the on-disk announce cache — Python
/// `Transport.clean_announce_cache` parity. The keep-set is every packet
/// hash a path response could still be served from: live paths, tunnel
/// paths, RPC-retained announces (Rust pin extension), and persisted
/// entries still waiting for their interface to re-register. The walk
/// paths, and persisted entries still waiting for their interface to
/// re-register (Rust restores paths lazily). The walk
/// and unlinks run on the blocking pool; the actor only snapshots.
/// Returns true when a sweep was scheduled (or ran inline).
pub(super) fn maybe_sweep_announce_cache(&mut self) -> bool {
@@ -366,12 +432,6 @@ impl TransportActor {
.tunnel_paths()
.filter_map(|(_, p)| p.packet_hash),
);
keep.extend(
self.recent_announces
.values()
.filter(|a| a.retained)
.filter_map(|a| a.packet_hash),
);
keep.extend(
self.pending_path_entries
.iter()
@@ -456,6 +516,7 @@ impl TransportActor {
write_routing_snapshot(&dir, &snapshot);
}
self.state_dirty = false;
self.routing_save_pending = false;
self.last_state_save = now();
}
@@ -634,6 +695,8 @@ impl TransportActor {
return;
};
let now_ts = now();
// Python defers the first announce-cache clean (Transport.py:509).
self.last_announce_cache_sweep = now_ts + ANNOUNCE_CACHE_SWEEP_DEFER;
// Python destination_table — canonical interop shape. Defer interface
// hash remap until matching interfaces register.
@@ -926,18 +989,11 @@ impl TransportActor {
};
if let Some(entries) = loaded {
let count = entries.len();
let mut expired = 0usize;
// Python loads every known destination; cleaning decides retention.
for ae in entries {
if ae.destination_hash.len() == 16 {
let mut hash = [0u8; 16];
hash.copy_from_slice(&ae.destination_hash);
let stale_pathless = !ae.retained
&& !self.recent_announces.contains_key(&hash)
&& now_ts - ae.timestamp > DESTINATION_TIMEOUT as f64;
if stale_pathless {
expired += 1;
continue;
}
let public_key = ae.public_key.and_then(|k| {
if k.len() == 64 {
let mut arr = [0u8; 64];
@@ -992,7 +1048,7 @@ impl TransportActor {
});
}
}
debug!(count, expired, "loaded announce cache entries from disk");
debug!(count, "loaded announce cache entries from disk");
}
}
}
@@ -1231,10 +1287,9 @@ mod announce_sweep_actor_tests {
}
}
/// Keep-set covers every source a path response can be served from:
/// live paths, tunnel paths, retained pins, and persisted entries still
/// waiting for interface re-registration. Everything else, aged past the
/// grace window, is removed. No tokio runtime → the sweep runs inline,
/// Keep-set covers live paths, tunnel paths and persisted entries still
/// waiting for interface re-registration. Everything else, a retained
/// destination's announce included, is removed once past the grace window. No tokio runtime → the sweep runs inline,
/// making the test fully deterministic.
#[test]
fn sweep_keeps_all_reference_sources_and_removes_orphans() {
@@ -1307,7 +1362,6 @@ mod announce_sweep_actor_tests {
for (h, why) in [
(path_hash, "live path"),
(tunnel_hash, "tunnel path"),
(pin_hash, "retained pin"),
(pending_path_hash, "pending path entry"),
] {
assert!(
@@ -1315,10 +1369,9 @@ mod announce_sweep_actor_tests {
"{why} announce must survive the sweep"
);
}
assert!(
!dir.join(hex::encode(orphan_hash)).exists(),
"orphan must be removed"
);
for (h, why) in [(orphan_hash, "orphan"), (pin_hash, "retained pin")] {
assert!(!dir.join(hex::encode(h)).exists(), "{why} must be removed");
}
assert!(
!actor
.announce_sweep_in_flight
@@ -1409,6 +1462,95 @@ mod async_save_tests {
actor
}
/// Changed known-destination metadata reaches disk on the 10 s cadence
/// without waiting for the routing tables' periodic save.
#[test]
fn known_destinations_flush_on_their_own_cadence() {
let dir = temp_storage();
let mut actor = dirty_actor(&dir);
actor.recent_announces.insert(
[0x11; 16],
RecentAnnounce {
dest_hash: [0x11; 16],
hops: 1,
app_data: None,
timestamp: crate::now_f64(),
public_key: Some([0x25; 64]),
ratchet: None,
packet_hash: None,
is_path_response: false,
retained: false,
last_used: None,
name_hash: [0u8; 10],
stamp: None,
stamp_value: 0.0,
lr_cost: None,
},
);
let now = crate::now_f64();
actor.last_state_save = now;
actor.last_known_destinations_flush = now - KD_FLUSH_INTERVAL - 1.0;
actor.on_tick();
let announces =
crate::persistence::load_announce_cache(&dir.join("announce_cache.msgpack")).unwrap();
assert_eq!(announces.len(), 1);
assert!(
!dir.join("path_table.msgpack").exists(),
"routing tables wait for their own interval"
);
actor.last_state_save = now - STATE_SAVE_INTERVAL_SECS - 1.0;
actor.on_tick();
assert!(dir.join("path_table.msgpack").exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A departing local client triggers a full persist once
/// `GRACIOUS_PERSIST_INTERVAL` has passed since the last one.
#[test]
fn local_client_disconnect_persists_after_gracious_interval() {
let dir = temp_storage();
let mut actor = dirty_actor(&dir);
for id in [8, 9] {
let (tx, _rx) = tokio::sync::mpsc::channel(1);
let mut client = crate::messages::InterfaceEntry::new(
"local client".to_string(),
crate::constants::InterfaceMode::Gateway,
crate::constants::InterfaceDirection::bidirectional(),
1_000_000,
rns_wire::constants::MTU as u32,
tx,
);
client.role = InterfaceRole::LocalClient;
actor.interfaces.insert(id, client);
}
let path = dir.join("path_table.msgpack");
actor.last_data_persist = crate::now_f64() - GRACIOUS_PERSIST_INTERVAL + 5.0;
actor.deregister_interface(8);
assert!(
!path.exists(),
"inside the gracious interval nothing persists"
);
actor.last_data_persist = crate::now_f64() - GRACIOUS_PERSIST_INTERVAL - 1.0;
actor.deregister_interface(9);
assert!(path.exists(), "a late disconnect persists");
let _ = std::fs::remove_dir_all(&dir);
}
/// Storage init defers the first announce-cache sweep by 60 s.
#[test]
fn storage_init_defers_the_first_announce_cache_sweep() {
let dir = temp_storage();
let (mut actor, _tx) = TransportActor::new();
let before = crate::now_f64();
actor.initialize_storage(dir.clone());
assert!(actor.last_announce_cache_sweep >= before + ANNOUNCE_CACHE_SWEEP_DEFER);
let _ = std::fs::remove_dir_all(&dir);
}
/// The periodic save must never run the fsync chain on the actor: the
/// tick path schedules to the blocking pool and returns immediately,
/// clearing the dirty flag; the files appear once the pool task runs.
@@ -270,6 +270,10 @@ impl TransportActor {
if !now.is_finite() || now >= operation.timeout {
return;
}
// Python recalls the answered identity with use marking (Transport.py:2696).
if !operation.requesters.is_empty() {
self.use_destination(&destination);
}
for waiter in operation.requesters {
let id = waiter.token.interface;
let eligible = self.discovery_waiter_registered(&waiter)
+20 -3
View File
@@ -125,10 +125,27 @@ pub const PENDING_PRS_CHECK_INTERVAL: f64 = 30.0;
/// (5 minutes), after the interface-startup grace period has completed.
pub const CACHE_CLEAN_INTERVAL: f64 = 300.0;
/// On-disk announce cache sweep interval, in seconds (15 minutes). Scheduling
/// does not require the interface-startup grace period; it requires storage,
/// On-disk announce cache sweep interval, in seconds (5 minutes, Python
/// `cache_clean_interval`). The first sweep runs one interval after a
/// 60-second deferral from storage init. Scheduling requires storage,
/// non-client ownership and no sweep already in flight.
pub const ANNOUNCE_CACHE_SWEEP_INTERVAL: f64 = 900.0;
pub const ANNOUNCE_CACHE_SWEEP_INTERVAL: f64 = 300.0;
/// Deferral added to the first announce-cache sweep after storage init
/// (Python `cache_last_cleaned = time.time() + 60`).
pub const ANNOUNCE_CACHE_SWEEP_DEFER: f64 = 60.0;
/// Interval in seconds between known-destination cleaning passes, the first
/// one interval after the actor starts (Python `known_destinations_interval`).
pub const KNOWN_DESTINATIONS_INTERVAL: f64 = 300.0;
/// Interval in seconds between flushes of changed known-destination metadata
/// (Python `kd_flush_interval`).
pub const KD_FLUSH_INTERVAL: f64 = 10.0;
/// Minimum spacing in seconds between a full persist and one requested by a
/// local client disconnecting (Python `GRACIOUS_PERSIST_INTERVAL`).
pub const GRACIOUS_PERSIST_INTERVAL: f64 = 300.0;
/// Minimum age in seconds before an unreferenced announce-cache file is
/// eligible for removal. This grace reduces races with a keep-set snapshot;
+52 -6
View File
@@ -174,9 +174,11 @@ pub fn interface_hash_from_name(name: &str) -> [u8; 32] {
rns_crypto::sha::full_hash(name.as_bytes())
}
/// Save the Python-compatible eight-field destination rows. Entries without a
/// Save the Python-compatible nine-field destination rows. Entries without a
/// supplied interface name or cached announce hash are skipped; expired entries
/// are retained. Each row includes at most the last 32 random blobs.
/// are retained. Rows carry every in-memory random blob, as Python does. The
/// ninth field is Python's path `used` time; Rust does not track path use, so
/// it writes the path timestamp, as a Python loader assumes for legacy rows.
pub fn save_python_destination_table(
table: &PathTable,
interface_names: &HashMap<u64, String>,
@@ -192,7 +194,7 @@ pub fn save_python_destination_table(
};
let received_from = entry.next_hop.unwrap_or(*hash.as_bytes());
let random_blobs = entry
.blobs_for_persist()
.random_blobs
.iter()
.map(|b| Value::Binary(b.to_vec()))
.collect();
@@ -205,6 +207,7 @@ pub fn save_python_destination_table(
Value::Array(random_blobs),
Value::Binary(interface_hash_from_name(interface_name).to_vec()),
Value::Binary(packet_hash.to_vec()),
Value::F64(entry.timestamp),
]));
}
@@ -298,10 +301,23 @@ pub fn write_python_cached_announce_if_absent(
raw_packet: &[u8],
interface_name: Option<&str>,
) -> Result<(), PersistenceError> {
let path = announce_cache_dir.join(hex::encode(packet_hash));
if path.exists() {
if announce_cache_dir.join(hex::encode(packet_hash)).exists() {
return Ok(());
}
write_python_cached_announce(announce_cache_dir, packet_hash, raw_packet, interface_name)
}
/// Write raw packet bytes and an optional interface reference under the
/// supplied packet hash, replacing any earlier entry, like Python's
/// `AnnounceCache.store`. Same tmp-and-rename, no-fsync contract as
/// [`write_python_cached_announce_if_absent`].
pub fn write_python_cached_announce(
announce_cache_dir: &Path,
packet_hash: &[u8; 32],
raw_packet: &[u8],
interface_name: Option<&str>,
) -> Result<(), PersistenceError> {
let path = announce_cache_dir.join(hex::encode(packet_hash));
std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?;
let interface_reference = interface_name
.map(|name| Value::String(name.into()))
@@ -363,7 +379,8 @@ pub fn load_python_cached_announce(
/// Save Python-compatible tunnel rows, retaining expired tunnels and paths.
/// Nested paths without a cached announce hash are omitted; each saved path
/// keeps at most the last 32 random blobs. An unknown interface has no hash.
/// keeps at most the last 32 random blobs and, as its ninth field, the path
/// timestamp in place of Python's `used` time. An unknown interface has no hash.
pub fn save_python_tunnel_table(
table: &crate::tunnel::TunnelTable,
interface_names: &HashMap<u64, String>,
@@ -402,6 +419,7 @@ pub fn save_python_tunnel_table(
Value::Array(random_blobs),
interface_hash.clone(),
Value::Binary(packet_hash.to_vec()),
Value::F64(tunnel_path.timestamp),
]));
}
@@ -1602,6 +1620,34 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn cached_announce_write_replaces_bytes_and_interface() {
let dir = std::env::temp_dir().join(format!(
"reticulum_rs_test_announce_upsert_{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let packet_hash = [0xCD; 32];
write_python_cached_announce(&dir, &packet_hash, &[0x01; 40], Some("TCPInterface[first]"))
.unwrap();
write_python_cached_announce(
&dir,
&packet_hash,
&[0x02; 40],
Some("TCPInterface[second]"),
)
.unwrap();
let cached = load_python_cached_announce(&dir, &packet_hash)
.unwrap()
.unwrap();
assert_eq!(cached.raw_packet, vec![0x02; 40]);
assert_eq!(
cached.interface_reference.as_deref(),
Some("TCPInterface[second]")
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn cached_announce_write_if_absent_does_not_overwrite() {
let dir = std::env::temp_dir().join("reticulum_rs_test_announce_if_absent");