From 5a974ae1158ecbf8a67fe6b82282ff732956c4df Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:19:22 -0700 Subject: [PATCH] stamps: [stamps] max_workers and worker_niceness --- crates/rns-identity/src/stamps.rs | 166 +++++++++++++++++++++++++++- crates/rns-runtime/src/reticulum.rs | 57 ++++++++++ 2 files changed, 219 insertions(+), 4 deletions(-) diff --git a/crates/rns-identity/src/stamps.rs b/crates/rns-identity/src/stamps.rs index 5561072..6f8fb55 100644 --- a/crates/rns-identity/src/stamps.rs +++ b/crates/rns-identity/src/stamps.rs @@ -6,7 +6,7 @@ use std::num::NonZeroUsize; use std::sync::Arc; use std::sync::Mutex; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; use std::time::Instant; use rand::RngCore; @@ -471,6 +471,85 @@ pub fn stamp_valid_fp(stamp: &[u8], target_fp: u16, workblock: &[u8]) -> Result< Ok(target_from_fp(target_fp)?.accepts(&hash_with(workblock, stamp))) } +/// Python `Stamps.NICENESS`. +pub const DEFAULT_WORKER_NICENESS: u8 = 16; +/// Upper clamp of `[stamps] worker_niceness`. +pub const MAX_WORKER_NICENESS: u8 = 20; + +static MAX_WORKERS: AtomicUsize = AtomicUsize::new(0); +static WORKER_NICENESS: AtomicU8 = AtomicU8::new(DEFAULT_WORKER_NICENESS); + +/// Process-wide limits on stamp search threads: Python `Stamps.MAX_WORKERS` +/// and `Stamps.NICENESS`, set from `[stamps] max_workers` and `worker_niceness`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StampWorkers { + /// Cap on the threads of one search; `None` keeps the caller's count. + pub max_workers: Option, + /// Nice increment each thread of a multi-threaded search applies to + /// itself, `0..=20`. Linux only, where nice values are per thread; a no-op + /// elsewhere. + pub niceness: u8, +} + +impl Default for StampWorkers { + fn default() -> Self { + Self { + max_workers: None, + niceness: DEFAULT_WORKER_NICENESS, + } + } +} + +impl StampWorkers { + /// Python `max(1, v)`. + pub fn clamp_max_workers(value: i64) -> NonZeroUsize { + usize::try_from(value) + .ok() + .and_then(NonZeroUsize::new) + .unwrap_or(NonZeroUsize::MIN) + } + + /// Python `min(20, max(0, v))`. + pub fn clamp_niceness(value: i64) -> u8 { + value.clamp(0, i64::from(MAX_WORKER_NICENESS)) as u8 + } + + /// The installed process settings. + pub fn current() -> Self { + Self { + max_workers: NonZeroUsize::new(MAX_WORKERS.load(Ordering::Relaxed)), + niceness: WORKER_NICENESS.load(Ordering::Relaxed), + } + } + + /// Install for every later search in this process. + pub fn install(self) { + MAX_WORKERS.store( + self.max_workers.map_or(0, NonZeroUsize::get), + Ordering::Relaxed, + ); + WORKER_NICENESS.store(self.niceness.min(MAX_WORKER_NICENESS), Ordering::Relaxed); + } + + /// `threads` capped at `max_workers`. + pub fn cap(&self, threads: NonZeroUsize) -> NonZeroUsize { + self.max_workers.map_or(threads, |max| threads.min(max)) + } +} + +#[cfg(target_os = "linux")] +fn renice_search_thread(increment: u8) { + if increment > 0 { + // SAFETY: nice(2) only adjusts the calling thread; errors are ignored, as upstream ignores them. + unsafe { + libc::nice(libc::c_int::from(increment)); + } + } +} + +#[cfg(not(target_os = "linux"))] +fn renice_search_thread(_increment: u8) {} + /// Stop conditions and parallelism for a stamp search. #[derive(Debug, Clone)] pub struct StampControl { @@ -508,19 +587,30 @@ fn generation_target(cost: f64) -> Result { target_from_cost(cost) } -/// Run `worker` on `ctl.threads` threads until one returns a result or all stop. +/// Run `worker` on `ctl.threads` threads, capped by the installed +/// [`StampWorkers`], until one returns a result or all stop. fn search( ctl: &StampControl, worker: impl Fn(&AtomicBool) -> Option + Sync, +) -> Option { + search_with(ctl, StampWorkers::current(), worker) +} + +fn search_with( + ctl: &StampControl, + workers: StampWorkers, + worker: impl Fn(&AtomicBool) -> Option + Sync, ) -> Option { let found = AtomicBool::new(false); - if ctl.threads.get() == 1 { + let threads = workers.cap(ctl.threads).get(); + if threads == 1 { return worker(&found); } let result = Mutex::new(None); std::thread::scope(|scope| { - for _ in 0..ctl.threads.get() { + for _ in 0..threads { scope.spawn(|| { + renice_search_thread(workers.niceness); if let Some(hit) = worker(&found) { found.store(true, Ordering::Relaxed); result @@ -730,6 +820,74 @@ mod tests { assert_eq!(stamp_valid(&stamp, 10.0, &workblock), Ok(true)); } + #[test] + fn worker_settings_clamp_as_python() { + assert_eq!(StampWorkers::default().max_workers, None); + assert_eq!(StampWorkers::default().niceness, 16); + assert_eq!(StampWorkers::clamp_max_workers(0).get(), 1); + assert_eq!(StampWorkers::clamp_max_workers(-3).get(), 1); + assert_eq!(StampWorkers::clamp_max_workers(6).get(), 6); + assert_eq!(StampWorkers::clamp_niceness(-3), 0); + assert_eq!(StampWorkers::clamp_niceness(25), 20); + assert_eq!(StampWorkers::clamp_niceness(7), 7); + } + + #[test] + fn max_workers_caps_search_threads() { + let ctl = StampControl { + threads: NonZeroUsize::new(4).unwrap(), + ..StampControl::default() + }; + let count = |workers: StampWorkers| { + let started = AtomicUsize::new(0); + search_with(&ctl, workers, |_| { + started.fetch_add(1, Ordering::Relaxed); + None::<()> + }); + started.into_inner() + }; + let capped = StampWorkers { + max_workers: NonZeroUsize::new(2), + niceness: 0, + }; + assert_eq!(count(capped), 2); + assert_eq!( + count(StampWorkers { + niceness: 0, + ..StampWorkers::default() + }), + 4 + ); + let above = StampWorkers { + max_workers: NonZeroUsize::new(9), + niceness: 0, + }; + assert_eq!(count(above), 4); + } + + #[cfg(target_os = "linux")] + #[test] + fn pooled_search_threads_are_niced() { + // SAFETY: getpriority(2) reads the calling thread's nice value. + let nice = || unsafe { libc::getpriority(libc::PRIO_PROCESS, 0) }; + let base = nice(); + let ctl = StampControl { + threads: NonZeroUsize::new(2).unwrap(), + ..StampControl::default() + }; + let workers = StampWorkers { + max_workers: None, + niceness: 16, + }; + assert_eq!( + search_with(&ctl, workers, |_| Some(nice())), + Some((base + 16).min(19)) + ); + let single = StampControl::default(); + assert_eq!(search_with(&single, workers, |_| Some(nice())), Some(base)); + assert_eq!(nice(), base); + } + #[test] fn generation_rejects_costs_python_rejects() { let ctl = StampControl::default(); diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 0307ef2..60e0cee 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -3201,6 +3201,8 @@ pub struct ReticulumConfig { /// Network stamp policy from the `[stamps]` section. pub stamps: rns_transport::stamps::StampPolicy, + /// `[stamps] max_workers` and `worker_niceness`, installed process-wide at init. + pub stamp_workers: rns_identity::stamps::StampWorkers, /// Destination-type filter and hop limiter from the `[filter]` section. pub filter: rns_transport::destination_filter::FilterPolicy, } @@ -3249,6 +3251,7 @@ impl Default for ReticulumConfig { log_timestamps: true, bootstrap_configs: Vec::new(), stamps: rns_transport::stamps::StampPolicy::default(), + stamp_workers: rns_identity::stamps::StampWorkers::default(), filter: rns_transport::destination_filter::FilterPolicy::default(), } } @@ -3373,6 +3376,21 @@ fn apply_stamps_section( Ok(()) } +/// Python `[stamps] max_workers` and `worker_niceness`: `as_int`, then clamped. +fn apply_stamp_workers( + workers: &mut rns_identity::stamps::StampWorkers, + sec: &ConfigSection, +) -> Result<(), ConfigError> { + use rns_identity::stamps::StampWorkers; + if let Some(v) = config_int("stamps", sec, "max_workers")? { + workers.max_workers = Some(StampWorkers::clamp_max_workers(v)); + } + if let Some(v) = config_int("stamps", sec, "worker_niceness")? { + workers.niceness = StampWorkers::clamp_niceness(v); + } + Ok(()) +} + fn config_u16( section_name: &str, section: &ConfigSection, @@ -3552,6 +3570,7 @@ impl ReticulumConfig { if let Some(sec) = config.section("stamps") { apply_stamps_section(&mut rc.stamps, sec)?; + apply_stamp_workers(&mut rc.stamp_workers, sec)?; } rc.filter = config.filter_policy()?; @@ -3970,6 +3989,7 @@ pub async fn init_with_policy( let _ = transport_tx.try_send(TransportMessage::SetBlackholeSources { sources: rc.blackhole_sources.clone(), }); + rc.stamp_workers.install(); let _ = transport_tx.try_send(TransportMessage::SetStampPolicy { policy: rc.stamps.clone(), }); @@ -17673,6 +17693,43 @@ egress_control = Yes } } + #[test] + fn stamps_section_worker_keys_clamp_as_python() { + let parse = |body: &str| { + let config = Config::parse(&format!("[stamps]\n{body}\n")).unwrap(); + ReticulumConfig::try_from_config(&config).map(|rc| rc.stamp_workers) + }; + let workers = parse("max_workers = 3\nworker_niceness = 7").unwrap(); + assert_eq!(workers.max_workers.map(usize::from), Some(3)); + assert_eq!(workers.niceness, 7); + let workers = parse("max_workers = 0\nworker_niceness = 25").unwrap(); + assert_eq!( + (workers.max_workers.map(usize::from), workers.niceness), + (Some(1), 20) + ); + let workers = parse("max_workers = -3\nworker_niceness = -3").unwrap(); + assert_eq!( + (workers.max_workers.map(usize::from), workers.niceness), + (Some(1), 0) + ); + let workers = parse("destination_cost = 20").unwrap(); + assert_eq!(workers, rns_identity::stamps::StampWorkers::default()); + for body in [ + "max_workers = x", + "max_workers = 2.5", + "worker_niceness = high", + ] { + assert!( + matches!( + parse(body), + Err(ConfigError::InvalidValue { ref key, .. }) + if key == body.split(' ').next().unwrap() + ), + "{body}" + ); + } + } + #[test] fn default_config_parses_to_default_stamp_policy() { let config = Config::parse(Config::default_config()).unwrap();