Skip to main content

vanity_core/
system.rs

1use rayon::ThreadPoolBuilder;
2use std::fmt;
3
4/// Named grind power profiles — frontends pass an id; core owns the thread math.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub enum GrindPreset {
7    /// ~25% of cores — cool / battery-friendly.
8    Eco,
9    /// Current auto-tune (usually cores − 1). Default.
10    #[default]
11    Balanced,
12    /// Use all logical CPUs (still respects memory caps).
13    Fast,
14    /// Same workers as Fast; denser progress reporting.
15    Extreme,
16}
17
18impl GrindPreset {
19    pub fn id(self) -> &'static str {
20        match self {
21            Self::Eco => "eco",
22            Self::Balanced => "balanced",
23            Self::Fast => "fast",
24            Self::Extreme => "extreme",
25        }
26    }
27
28    pub fn label(self) -> &'static str {
29        match self {
30            Self::Eco => "Eco",
31            Self::Balanced => "Balanced",
32            Self::Fast => "Fast",
33            Self::Extreme => "Extreme",
34        }
35    }
36
37    /// Parse a preset id or alias (`efficient`, `best`, `superman`, …).
38    pub fn parse(s: &str) -> Result<Self, String> {
39        match s.trim().to_ascii_lowercase().as_str() {
40            "eco" | "minimal" | "efficient" | "low" => Ok(Self::Eco),
41            "balanced" | "auto" | "default" | "moderate" => Ok(Self::Balanced),
42            "fast" | "best" | "performance" | "high" => Ok(Self::Fast),
43            "extreme" | "superman" | "max" | "all-out" | "allout" => Ok(Self::Extreme),
44            other => Err(format!(
45                "Unknown preset '{other}'. Use: eco, balanced, fast, extreme"
46            )),
47        }
48    }
49
50    pub const ALL: [GrindPreset; 4] = [Self::Eco, Self::Balanced, Self::Fast, Self::Extreme];
51}
52
53/// Detected host capabilities used to tune the grinder before work starts.
54#[derive(Debug, Clone)]
55pub struct SystemProfile {
56    pub logical_cpus: usize,
57    pub physical_cpus: Option<usize>,
58    pub total_memory_mb: u64,
59    pub available_memory_mb: u64,
60    pub worker_threads: usize,
61    pub progress_interval: u64,
62    pub memory_pressure: MemoryPressure,
63    /// Set after a live benchmark warm-up for accurate ETA.
64    pub measured_keys_per_sec: Option<f64>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum MemoryPressure {
69    Comfortable,
70    Moderate,
71    Low,
72}
73
74impl fmt::Display for MemoryPressure {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        match self {
77            MemoryPressure::Comfortable => write!(f, "comfortable"),
78            MemoryPressure::Moderate => write!(f, "moderate"),
79            MemoryPressure::Low => write!(f, "low"),
80        }
81    }
82}
83
84impl SystemProfile {
85    /// Probe the current machine and derive grinding settings.
86    pub fn detect() -> Self {
87        let logical_cpus = std::thread::available_parallelism()
88            .map(|n| n.get())
89            .unwrap_or(1);
90
91        let (physical_cpus, total_memory_mb, available_memory_mb) = probe_sysinfo();
92
93        let memory_pressure = classify_memory_pressure(available_memory_mb);
94        let worker_threads =
95            compute_worker_threads(logical_cpus, physical_cpus, available_memory_mb);
96        let progress_interval = compute_progress_interval(worker_threads);
97
98        Self {
99            logical_cpus,
100            physical_cpus,
101            total_memory_mb,
102            available_memory_mb,
103            worker_threads,
104            progress_interval,
105            memory_pressure,
106            measured_keys_per_sec: None,
107        }
108    }
109
110    /// Store a live benchmark result from `benchmark()`.
111    pub fn with_benchmark(mut self, keys_per_sec: f64) -> Self {
112        self.measured_keys_per_sec = Some(keys_per_sec.max(1.0));
113        self
114    }
115
116    /// Override thread count (e.g. from `--threads` CLI flag).
117    pub fn with_threads(mut self, threads: usize) -> Self {
118        let threads = threads.clamp(1, self.logical_cpus);
119        self.worker_threads = threads;
120        self.progress_interval = compute_progress_interval(threads);
121        self
122    }
123
124    /// Apply a named power preset. Call before `with_threads` if both are set
125    /// (explicit thread count should win at the call site).
126    pub fn with_preset(mut self, preset: GrindPreset) -> Self {
127        let logical = self.logical_cpus.max(1);
128        let mem_cap = memory_worker_cap(self.available_memory_mb);
129        let threads = match preset {
130            GrindPreset::Eco => (logical / 4).max(1).min(mem_cap),
131            GrindPreset::Balanced => {
132                compute_worker_threads(logical, self.physical_cpus, self.available_memory_mb)
133            }
134            GrindPreset::Fast | GrindPreset::Extreme => logical.min(mem_cap).max(1),
135        };
136        self.worker_threads = threads;
137        let base = compute_progress_interval(threads);
138        self.progress_interval = match preset {
139            GrindPreset::Extreme => (base / 2).max(50_000),
140            _ => base,
141        };
142        self
143    }
144
145    pub fn summary_line(&self) -> String {
146        let cores = self.cpu_description();
147
148        format!(
149            "{cores} · {:.1} GB RAM ({:.1} GB free) · {} workers · memory: {}",
150            self.total_memory_mb as f64 / 1024.0,
151            self.available_memory_mb as f64 / 1024.0,
152            self.worker_threads,
153            self.memory_pressure,
154        )
155    }
156
157    pub fn cpu_description(&self) -> String {
158        match self.physical_cpus {
159            Some(physical) if physical != self.logical_cpus => {
160                format!("{} logical · {} physical", self.logical_cpus, physical)
161            }
162            Some(physical) => format!("{physical} cores"),
163            None => format!("{} cores", self.logical_cpus),
164        }
165    }
166
167    pub fn worker_description(&self) -> String {
168        let reserved = self.logical_cpus.saturating_sub(self.worker_threads);
169        if reserved > 0 {
170            format!(
171                "{} threads grinding · {} core{} reserved for OS",
172                self.worker_threads,
173                reserved,
174                if reserved == 1 { "" } else { "s" }
175            )
176        } else {
177            format!("{} threads (all cores)", self.worker_threads)
178        }
179    }
180
181    pub fn estimated_keys_per_sec(&self, chain_id: &str) -> f64 {
182        if let Some(measured) = self.measured_keys_per_sec {
183            return measured;
184        }
185        let per_thread = match chain_id {
186            "evm" | "evm-contract" | "trx-contract" | "create2" | "aptos" | "sui" | "near" => {
187                35_000.0
188            }
189            _ => 80_000.0,
190        };
191        per_thread * self.worker_threads as f64
192    }
193}
194
195fn probe_sysinfo() -> (Option<usize>, u64, u64) {
196    let mut sys = sysinfo::System::new();
197    sys.refresh_memory();
198
199    let total_memory_mb = sys.total_memory() / 1024 / 1024;
200    let mut available_memory_mb = sys.available_memory() / 1024 / 1024;
201
202    // macOS often reports near-zero "available" RAM — use a sane fallback.
203    if available_memory_mb < 256 && total_memory_mb > 512 {
204        available_memory_mb = (total_memory_mb * 3) / 4;
205    }
206
207    let physical_cpus = sys.physical_core_count();
208
209    (physical_cpus, total_memory_mb, available_memory_mb)
210}
211
212fn classify_memory_pressure(available_mb: u64) -> MemoryPressure {
213    if available_mb < 512 {
214        MemoryPressure::Low
215    } else if available_mb < 2_048 {
216        MemoryPressure::Moderate
217    } else {
218        MemoryPressure::Comfortable
219    }
220}
221
222/// How many rayon workers to spawn for this host.
223pub fn compute_worker_threads(
224    logical_cpus: usize,
225    physical_cpus: Option<usize>,
226    available_mem_mb: u64,
227) -> usize {
228    let logical_cpus = logical_cpus.max(1);
229
230    // Leave one core for the OS / terminal on machines with headroom.
231    let mut threads = match logical_cpus {
232        1 => 1,
233        2 => 2,
234        n => n - 1,
235    };
236
237    // Prefer not to oversubscribe physical cores when SMT is present.
238    if let Some(physical) = physical_cpus {
239        if physical > 0 && threads > physical {
240            threads = physical;
241        }
242    }
243
244    // Back off when memory is tight — each worker holds crypto state on its stack.
245    threads.min(memory_worker_cap(available_mem_mb)).max(1)
246}
247
248fn memory_worker_cap(available_mem_mb: u64) -> usize {
249    match available_mem_mb {
250        m if m < 512 => 1,
251        m if m < 1_024 => 2,
252        m if m < 2_048 => 4,
253        m if m < 4_096 => 8,
254        _ => usize::MAX,
255    }
256}
257
258/// Progress callback frequency — scales with worker count, bounded to limit overhead.
259pub fn compute_progress_interval(worker_threads: usize) -> u64 {
260    (50_000_u64 * worker_threads as u64).clamp(100_000, 2_000_000)
261}
262
263/// Build a rayon pool sized for this profile.
264pub fn build_thread_pool(profile: &SystemProfile) -> Result<rayon::ThreadPool, String> {
265    ThreadPoolBuilder::new()
266        .num_threads(profile.worker_threads)
267        .thread_name(|i| format!("vanity-worker-{i}"))
268        .build()
269        .map_err(|e| format!("Failed to configure thread pool: {e}"))
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn single_core_machine_uses_one_worker() {
278        assert_eq!(compute_worker_threads(1, Some(1), 16_384), 1);
279    }
280
281    #[test]
282    fn reserves_core_on_typical_laptop() {
283        assert_eq!(compute_worker_threads(8, Some(8), 16_384), 7);
284    }
285
286    #[test]
287    fn low_memory_caps_workers() {
288        assert_eq!(compute_worker_threads(16, Some(16), 800), 2);
289    }
290
291    #[test]
292    fn progress_interval_scales_with_threads() {
293        assert_eq!(compute_progress_interval(1), 100_000);
294        assert_eq!(compute_progress_interval(8), 400_000);
295        assert_eq!(compute_progress_interval(64), 2_000_000);
296    }
297
298    fn profile(logical: usize, physical: Option<usize>, mem_mb: u64) -> SystemProfile {
299        SystemProfile {
300            logical_cpus: logical,
301            physical_cpus: physical,
302            total_memory_mb: mem_mb,
303            available_memory_mb: mem_mb,
304            worker_threads: 1,
305            progress_interval: 100_000,
306            memory_pressure: MemoryPressure::Comfortable,
307            measured_keys_per_sec: None,
308        }
309    }
310
311    #[test]
312    fn eco_on_8_cores_uses_2() {
313        let p = profile(8, Some(8), 16_384).with_preset(GrindPreset::Eco);
314        assert_eq!(p.worker_threads, 2);
315    }
316
317    #[test]
318    fn balanced_matches_compute_worker_threads() {
319        let p = profile(8, Some(8), 16_384).with_preset(GrindPreset::Balanced);
320        assert_eq!(p.worker_threads, compute_worker_threads(8, Some(8), 16_384));
321    }
322
323    #[test]
324    fn fast_uses_all_logical_cpus() {
325        let p = profile(8, Some(8), 16_384).with_preset(GrindPreset::Fast);
326        assert_eq!(p.worker_threads, 8);
327    }
328
329    #[test]
330    fn extreme_same_threads_as_fast_tighter_progress() {
331        let fast = profile(8, Some(8), 16_384).with_preset(GrindPreset::Fast);
332        let extreme = profile(8, Some(8), 16_384).with_preset(GrindPreset::Extreme);
333        assert_eq!(extreme.worker_threads, fast.worker_threads);
334        assert!(extreme.progress_interval < fast.progress_interval);
335        assert_eq!(
336            extreme.progress_interval,
337            (compute_progress_interval(8) / 2).max(50_000)
338        );
339    }
340
341    #[test]
342    fn parse_accepts_aliases() {
343        assert_eq!(GrindPreset::parse("efficient").unwrap(), GrindPreset::Eco);
344        assert_eq!(GrindPreset::parse("best").unwrap(), GrindPreset::Fast);
345        assert_eq!(
346            GrindPreset::parse("performance").unwrap(),
347            GrindPreset::Fast
348        );
349        assert_eq!(
350            GrindPreset::parse("superman").unwrap(),
351            GrindPreset::Extreme
352        );
353        assert!(GrindPreset::parse("nope").is_err());
354    }
355
356    #[test]
357    fn mem_cap_still_limits_extreme() {
358        let p = profile(16, Some(16), 800).with_preset(GrindPreset::Extreme);
359        assert_eq!(p.worker_threads, 2);
360    }
361
362    #[test]
363    fn eco_on_dual_core_still_one_worker_min() {
364        let p = profile(2, Some(2), 16_384).with_preset(GrindPreset::Eco);
365        assert_eq!(p.worker_threads, 1);
366    }
367}