Skip to main content

vanity_core/
system.rs

1use rayon::ThreadPoolBuilder;
2use std::fmt;
3
4/// Detected host capabilities used to tune the grinder before work starts.
5#[derive(Debug, Clone)]
6pub struct SystemProfile {
7    pub logical_cpus: usize,
8    pub physical_cpus: Option<usize>,
9    pub total_memory_mb: u64,
10    pub available_memory_mb: u64,
11    pub worker_threads: usize,
12    pub progress_interval: u64,
13    pub memory_pressure: MemoryPressure,
14    /// Set after a live benchmark warm-up for accurate ETA.
15    pub measured_keys_per_sec: Option<f64>,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum MemoryPressure {
20    Comfortable,
21    Moderate,
22    Low,
23}
24
25impl fmt::Display for MemoryPressure {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            MemoryPressure::Comfortable => write!(f, "comfortable"),
29            MemoryPressure::Moderate => write!(f, "moderate"),
30            MemoryPressure::Low => write!(f, "low"),
31        }
32    }
33}
34
35impl SystemProfile {
36    /// Probe the current machine and derive grinding settings.
37    pub fn detect() -> Self {
38        let logical_cpus = std::thread::available_parallelism()
39            .map(|n| n.get())
40            .unwrap_or(1);
41
42        let (physical_cpus, total_memory_mb, available_memory_mb) = probe_sysinfo();
43
44        let memory_pressure = classify_memory_pressure(available_memory_mb);
45        let worker_threads =
46            compute_worker_threads(logical_cpus, physical_cpus, available_memory_mb);
47        let progress_interval = compute_progress_interval(worker_threads);
48
49        Self {
50            logical_cpus,
51            physical_cpus,
52            total_memory_mb,
53            available_memory_mb,
54            worker_threads,
55            progress_interval,
56            memory_pressure,
57            measured_keys_per_sec: None,
58        }
59    }
60
61    /// Store a live benchmark result from `benchmark()`.
62    pub fn with_benchmark(mut self, keys_per_sec: f64) -> Self {
63        self.measured_keys_per_sec = Some(keys_per_sec.max(1.0));
64        self
65    }
66
67    /// Override thread count (e.g. from `--threads` CLI flag).
68    pub fn with_threads(mut self, threads: usize) -> Self {
69        let threads = threads.clamp(1, self.logical_cpus);
70        self.worker_threads = threads;
71        self.progress_interval = compute_progress_interval(threads);
72        self
73    }
74
75    pub fn summary_line(&self) -> String {
76        let cores = self.cpu_description();
77
78        format!(
79            "{cores} · {:.1} GB RAM ({:.1} GB free) · {} workers · memory: {}",
80            self.total_memory_mb as f64 / 1024.0,
81            self.available_memory_mb as f64 / 1024.0,
82            self.worker_threads,
83            self.memory_pressure,
84        )
85    }
86
87    pub fn cpu_description(&self) -> String {
88        match self.physical_cpus {
89            Some(physical) if physical != self.logical_cpus => {
90                format!("{} logical · {} physical", self.logical_cpus, physical)
91            }
92            Some(physical) => format!("{physical} cores"),
93            None => format!("{} cores", self.logical_cpus),
94        }
95    }
96
97    pub fn worker_description(&self) -> String {
98        let reserved = self.logical_cpus.saturating_sub(self.worker_threads);
99        if reserved > 0 {
100            format!(
101                "{} threads grinding · {} core{} reserved for OS",
102                self.worker_threads,
103                reserved,
104                if reserved == 1 { "" } else { "s" }
105            )
106        } else {
107            format!("{} threads (all cores)", self.worker_threads)
108        }
109    }
110
111    pub fn estimated_keys_per_sec(&self, chain_id: &str) -> f64 {
112        if let Some(measured) = self.measured_keys_per_sec {
113            return measured;
114        }
115        let per_thread = match chain_id {
116            "evm" | "aptos" | "sui" | "near" => 35_000.0,
117            _ => 80_000.0,
118        };
119        per_thread * self.worker_threads as f64
120    }
121}
122
123fn probe_sysinfo() -> (Option<usize>, u64, u64) {
124    let mut sys = sysinfo::System::new();
125    sys.refresh_memory();
126
127    let total_memory_mb = sys.total_memory() / 1024 / 1024;
128    let mut available_memory_mb = sys.available_memory() / 1024 / 1024;
129
130    // macOS often reports near-zero "available" RAM — use a sane fallback.
131    if available_memory_mb < 256 && total_memory_mb > 512 {
132        available_memory_mb = (total_memory_mb * 3) / 4;
133    }
134
135    let physical_cpus = sys.physical_core_count();
136
137    (physical_cpus, total_memory_mb, available_memory_mb)
138}
139
140fn classify_memory_pressure(available_mb: u64) -> MemoryPressure {
141    if available_mb < 512 {
142        MemoryPressure::Low
143    } else if available_mb < 2_048 {
144        MemoryPressure::Moderate
145    } else {
146        MemoryPressure::Comfortable
147    }
148}
149
150/// How many rayon workers to spawn for this host.
151pub fn compute_worker_threads(
152    logical_cpus: usize,
153    physical_cpus: Option<usize>,
154    available_mem_mb: u64,
155) -> usize {
156    let logical_cpus = logical_cpus.max(1);
157
158    // Leave one core for the OS / terminal on machines with headroom.
159    let mut threads = match logical_cpus {
160        1 => 1,
161        2 => 2,
162        n => n - 1,
163    };
164
165    // Prefer not to oversubscribe physical cores when SMT is present.
166    if let Some(physical) = physical_cpus {
167        if physical > 0 && threads > physical {
168            threads = physical;
169        }
170    }
171
172    // Back off when memory is tight — each worker holds crypto state on its stack.
173    let mem_cap = match available_mem_mb {
174        m if m < 512 => 1,
175        m if m < 1_024 => 2,
176        m if m < 2_048 => 4,
177        m if m < 4_096 => 8,
178        _ => usize::MAX,
179    };
180
181    threads.min(mem_cap).max(1)
182}
183
184/// Progress callback frequency — scales with worker count, bounded to limit overhead.
185pub fn compute_progress_interval(worker_threads: usize) -> u64 {
186    (50_000_u64 * worker_threads as u64).clamp(100_000, 2_000_000)
187}
188
189/// Build a rayon pool sized for this profile.
190pub fn build_thread_pool(profile: &SystemProfile) -> Result<rayon::ThreadPool, String> {
191    ThreadPoolBuilder::new()
192        .num_threads(profile.worker_threads)
193        .thread_name(|i| format!("vanity-worker-{i}"))
194        .build()
195        .map_err(|e| format!("Failed to configure thread pool: {e}"))
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn single_core_machine_uses_one_worker() {
204        assert_eq!(compute_worker_threads(1, Some(1), 16_384), 1);
205    }
206
207    #[test]
208    fn reserves_core_on_typical_laptop() {
209        assert_eq!(compute_worker_threads(8, Some(8), 16_384), 7);
210    }
211
212    #[test]
213    fn low_memory_caps_workers() {
214        assert_eq!(compute_worker_threads(16, Some(16), 800), 2);
215    }
216
217    #[test]
218    fn progress_interval_scales_with_threads() {
219        assert_eq!(compute_progress_interval(1), 100_000);
220        assert_eq!(compute_progress_interval(8), 400_000);
221        assert_eq!(compute_progress_interval(64), 2_000_000);
222    }
223}