diff --git a/crates/disktree-app/Cargo.toml b/crates/disktree-app/Cargo.toml index 867d564..4bc758a 100644 --- a/crates/disktree-app/Cargo.toml +++ b/crates/disktree-app/Cargo.toml @@ -20,6 +20,7 @@ disktree-core = { workspace = true } anyhow = { workspace = true } dunce = "1.0.5" rustc-hash = { workspace = true } +tempfile = "3" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_System_Console"] } @@ -30,4 +31,3 @@ gpui-kit = { version = "=0.6.6", default-features = false, features = [ "assets", "test-support", ] } -tempfile = "3" diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 4af9de7..92fa2f7 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -16,6 +16,7 @@ mod appearance; mod git; mod marks; mod palette; +mod power; mod state; #[cfg(test)] mod tests; @@ -43,6 +44,7 @@ struct Args { root: PathBuf, options: ScanOptions, depth: u32, + power: Option, } const USAGE: &str = "\ @@ -65,7 +67,11 @@ options: also measure other disks, network shares and pseudo filesystems mounted below PATH (off by default) -d, --depth N how many levels to draw at once (1-6, default 3) - --scan-threads N maximum directory jobs per scan (macOS default 8) + --power-efficiency PRESET + miser, balanced (default), aggressive, drain-my-battery + --scan-threads N fixed scan workers, capped by available CPU count + --adaptive-threads + experimental adaptive admission (opt-in) --fixed-threads disable adaptive admission and CPU governor --thread-throughput-percent N retain this percent of sampled initial throughput (80) @@ -85,7 +91,16 @@ fn main() -> Result<()> { } fn run() -> Result<()> { - let args = parse_args(std::env::args_os().skip(1))?; + let saved = power::settings_path() + .map_or_else( + || Ok(power::PowerEfficiency::default()), + |path| power::load(&path), + ) + .unwrap_or_else(|error| { + eprintln!("Cannot load Power Efficiency: {error}; using Balanced"); + power::PowerEfficiency::default() + }); + let args = parse_args_with_power(std::env::args_os().skip(1), saved)?; // When the app executable is reached through the command-line symlink, // cmux sends SIGTERM to its foreground process group as AppKit takes @@ -164,12 +179,14 @@ fn run() -> Result<()> { appearance::follow(window); } cx.new(|cx| { - Disktree::new( + let mut app = Disktree::new( root_for_app.clone(), options.clone(), depth, cx, - ) + ); + app.power_choice = args.power; + app }) }, ) @@ -187,15 +204,21 @@ fn run() -> Result<()> { } /// Read the command line, program name already skipped. -fn parse_args( +#[cfg(test)] +fn parse_args(args: impl Iterator) -> Result { + parse_args_with_power(args, power::PowerEfficiency::default()) +} + +fn parse_args_with_power( mut args: impl Iterator, + preset: power::PowerEfficiency, ) -> Result { let mut root: Option = None; - let mut options = ScanOptions::default(); - if cfg!(target_os = "macos") { - options.threads.max_threads = 8; - options.threads.adaptive = true; - } + let mut options = ScanOptions { + threads: preset.policy(power::cpu_threads()), + ..ScanOptions::default() + }; + let mut power = Some(preset); let mut depth = 3_u32; let mut disk = false; // `std::env::args` panics on a name that is not Unicode, and a path is @@ -229,7 +252,16 @@ fn parse_args( "--depth must be 1 to 6" ); } + "--power-efficiency" => { + let value = + text(args.next(), "--power-efficiency needs a preset")?; + let preset = power::PowerEfficiency::parse(&value) + .context("unknown Power Efficiency preset")?; + options.threads = preset.policy(power::cpu_threads()); + power = Some(preset); + } "--scan-threads" => { + power = None; let value = text(args.next(), "--scan-threads needs a number")?; options.threads.max_threads = value .parse() @@ -239,7 +271,15 @@ fn parse_args( "--scan-threads must be positive" ); } - "--fixed-threads" => options.threads.adaptive = false, + "--fixed-threads" => { + options.threads.adaptive = false; + power = None; + } + "--adaptive-threads" => { + options.threads.adaptive = true; + options.threads.system_cpu_limit = Some(0.80); + power = None; + } "--thread-throughput-percent" => { let value = text( args.next(), @@ -316,6 +356,7 @@ fn parse_args( root, options, depth: depth.clamp(1, 6), + power, }) } @@ -368,13 +409,9 @@ mod argument_tests { let args = parse_args(arguments(&[])).expect("defaults"); assert_eq!( args.options.threads.max_threads, - if cfg!(target_os = "macos") { - 8 - } else { - usize::MAX - } + 4.min(power::cpu_threads()) ); - assert_eq!(args.options.threads.adaptive, cfg!(target_os = "macos")); + assert!(!args.options.threads.adaptive); let args = parse_args(arguments(&[ "--scan-threads", "4", @@ -394,6 +431,40 @@ mod argument_tests { assert_eq!(args.options.threads.system_cpu_limit, None); } + #[test] + fn saved_power_is_loaded_before_cli_overrides() { + use power::PowerEfficiency as Power; + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("power-efficiency"); + power::save(&path, Power::Miser).expect("save"); + let saved = power::load(&path).expect("load"); + let args = parse_args_with_power(arguments(&[]), saved).expect("saved"); + assert_eq!(args.power, Some(Power::Miser)); + assert_eq!( + args.options.threads.max_threads, + 2.min(power::cpu_threads()) + ); + let args = parse_args_with_power( + arguments(&["--power-efficiency", "drain-my-battery"]), + saved, + ) + .expect("override"); + assert_eq!(args.power, Some(Power::DrainMyBattery)); + assert_eq!(args.options.threads.max_threads, power::cpu_threads()); + let args = parse_args_with_power( + arguments(&["--scan-threads", "8", "--adaptive-threads"]), + saved, + ) + .expect("experiment"); + assert!(args.power.is_none()); + assert!(args.options.threads.adaptive); + assert_eq!(args.options.threads.max_threads, 8); + assert_eq!(power::load(&path).expect("unchanged"), saved); + assert!( + parse_args(arguments(&["--power-efficiency", "invalid"])).is_err() + ); + } + // APFS rejects these filename bytes; Linux filesystems permit them. #[cfg(target_os = "linux")] #[test] diff --git a/crates/disktree-app/src/power.rs b/crates/disktree-app/src/power.rs new file mode 100644 index 0000000..6f6428c --- /dev/null +++ b/crates/disktree-app/src/power.rs @@ -0,0 +1,157 @@ +//! Saved fixed worker presets. Read before the first scan starts. + +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; + +use disktree_core::scan_threads::ScanThreads; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PowerEfficiency { + Miser, + #[default] + Balanced, + Aggressive, + DrainMyBattery, +} + +impl PowerEfficiency { + pub const ALL: [Self; 4] = [ + Self::Miser, + Self::Balanced, + Self::Aggressive, + Self::DrainMyBattery, + ]; + + pub const fn key(self) -> &'static str { + match self { + Self::Miser => "miser", + Self::Balanced => "balanced", + Self::Aggressive => "aggressive", + Self::DrainMyBattery => "drain-my-battery", + } + } + + pub const fn name(self) -> &'static str { + match self { + Self::Miser => "Miser", + Self::Balanced => "Balanced", + Self::Aggressive => "Aggressive", + Self::DrainMyBattery => "Drain My Battery", + } + } + + pub fn parse(value: &str) -> Option { + Self::ALL.into_iter().find(|preset| preset.key() == value) + } + + pub fn threads(self, cpus: usize) -> usize { + let cpus = cpus.max(1); + match self { + Self::Miser => 2.min(cpus), + Self::Balanced => 4.min(cpus), + Self::Aggressive => 8.min(cpus), + Self::DrainMyBattery => cpus, + } + } + + pub fn label(self, cpus: usize) -> String { + let count = self.threads(cpus); + let unit = if count == 1 { "thread" } else { "threads" }; + format!("{} ({count} {unit})", self.name()) + } + + pub fn policy(self, cpus: usize) -> ScanThreads { + ScanThreads { + max_threads: self.threads(cpus), + adaptive: false, + system_cpu_limit: None, + ..ScanThreads::default() + } + } +} + +pub fn cpu_threads() -> usize { + std::thread::available_parallelism().map_or(1, usize::from) +} + +/// Follow each desktop's user configuration location; never write beside +/// the executable or scanned root. No home/config location means session-only. +pub fn settings_path() -> Option { + let home = std::env::home_dir(); + let base = if cfg!(target_os = "macos") { + home.map(|home| home.join("Library/Application Support")) + } else if cfg!(windows) { + std::env::var_os("APPDATA").map(PathBuf::from) + } else { + std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .or_else(|| home.map(|home| home.join(".config"))) + }; + base.map(|base| base.join("disktree/power-efficiency")) +} + +pub fn load(path: &Path) -> io::Result { + match std::fs::read_to_string(path) { + Ok(value) => PowerEfficiency::parse(value.trim()).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "unknown power preset") + }), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + Ok(PowerEfficiency::default()) + } + Err(error) => Err(error), + } +} + +pub fn save(path: &Path, preset: PowerEfficiency) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "no settings directory") + })?; + std::fs::create_dir_all(parent)?; + // Atomic replacement leaves the previous choice intact after a failed + // write, and readers never see a half-written setting. + let mut file = tempfile::NamedTempFile::new_in(parent)?; + writeln!(file, "{}", preset.key())?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_are_fixed_and_show_the_effective_cpu_limit() { + for (preset, expected) in + PowerEfficiency::ALL.into_iter().zip([2, 4, 8, 18]) + { + let policy = preset.policy(18); + assert_eq!(policy.max_threads, expected); + assert!(!policy.adaptive); + assert_eq!(policy.system_cpu_limit, None); + assert_eq!(preset.threads(1), 1); + } + assert_eq!(PowerEfficiency::Balanced.threads(3), 3); + assert_eq!( + PowerEfficiency::DrainMyBattery.label(18), + "Drain My Battery (18 threads)" + ); + } + + #[test] + fn saved_choice_survives_replacement_and_bad_data_is_reported() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("config/power-efficiency"); + assert_eq!(load(&path).expect("missing"), PowerEfficiency::Balanced); + for preset in PowerEfficiency::ALL { + save(&path, preset).expect("save"); + assert_eq!(load(&path).expect("load"), preset); + } + std::fs::write(&path, "not-a-preset").expect("corrupt"); + assert_eq!( + load(&path).expect_err("invalid").kind(), + io::ErrorKind::InvalidData + ); + assert!(save(dir.path(), PowerEfficiency::Miser).is_err()); + } +} diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 46195f2..83d091a 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -327,6 +327,10 @@ pub struct Disktree { pub root_path: PathBuf, pub home: Option, pub options: ScanOptions, + pub power_choice: Option, + pub power_settings_path: Option, + pub power_menu_open: bool, + pub cpu_threads: usize, pub tree: Option>, pub scan: Option, pub scan_epoch: u64, @@ -462,6 +466,10 @@ impl Disktree { root_path, home, options, + power_choice: None, + power_settings_path: crate::power::settings_path(), + power_menu_open: false, + cpu_threads: crate::power::cpu_threads(), tree: None, scan: None, scan_epoch: 0, @@ -799,6 +807,35 @@ impl Disktree { cx.notify(); } + /// Changing resource policy leaves the current scan and result intact; + /// rescan, navigation to a new root and restart use the new fixed budget. + pub fn set_power_efficiency( + &mut self, + preset: crate::power::PowerEfficiency, + cx: &mut Context<'_, Self>, + ) { + self.options.threads = preset.policy(self.cpu_threads); + self.power_choice = Some(preset); + self.power_menu_open = false; + self.notice = Some(match self.power_settings_path.as_deref() { + Some(path) => match crate::power::save(path, preset) { + Ok(()) => ( + format!("{} saved; applies to the next scan", preset.label(self.cpu_threads)), + Status::Success, + ), + Err(error) => ( + format!("Applies to the next scan, but could not save Power Efficiency: {error}"), + Status::Warning, + ), + }, + None => ( + "Power Efficiency applies to the next scan; no settings directory is available".into(), + Status::Warning, + ), + }); + cx.notify(); + } + /// Start a fresh scan, abandoning any walk still in progress. pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) { if let Some(scan) = &self.scan { @@ -2935,8 +2972,11 @@ impl Disktree { } else { &self.root_path }; - let args = + let mut args = restart_args(&self.options, self.layout_options.max_depth, root); + if let Some(preset) = self.power_choice { + args.extend(["--power-efficiency".into(), preset.key().into()]); + } // Off the UI thread: the prompt runs its own message loop, which // would re-enter this window while it is still being handled. let restart = cx.background_executor().spawn(async move { @@ -2982,6 +3022,25 @@ pub fn restart_args( if options.metric == Metric::Files { args.push("files".into()); } + args.push("--scan-threads".into()); + args.push(options.threads.max_threads.to_string().into()); + args.push(if options.threads.adaptive { + "--adaptive-threads".into() + } else { + "--fixed-threads".into() + }); + args.push("--thread-throughput-percent".into()); + args.push( + format!("{:.0}", options.threads.retained_throughput * 100.0).into(), + ); + args.push("--thread-system-cpu-percent".into()); + args.push( + format!( + "{:.0}", + options.threads.system_cpu_limit.unwrap_or(0.0) * 100.0 + ) + .into(), + ); args.push("--depth".into()); args.push(depth.to_string().into()); args.push(root.as_os_str().to_owned()); diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 2eb15d2..168e9ae 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -1614,6 +1614,12 @@ fn restart_arguments_parse_back_to_the_same_scan() { include_hidden: false, one_filesystem: false, metric: Metric::Files, + threads: disktree_core::scan_threads::ScanThreads { + max_threads: 8, + adaptive: true, + retained_throughput: 0.85, + system_cpu_limit: Some(0.70), + }, ..ScanOptions::default() }; for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] { @@ -1622,6 +1628,18 @@ fn restart_arguments_parse_back_to_the_same_scan() { assert_eq!(parsed.root, root); assert_eq!(parsed.depth, depth); let got = &parsed.options; + assert_eq!(got.threads.max_threads, options.threads.max_threads); + assert_eq!(got.threads.adaptive, options.threads.adaptive); + assert!( + (got.threads.retained_throughput + - options.threads.retained_throughput) + .abs() + < f64::EPSILON + ); + assert_eq!( + got.threads.system_cpu_limit, + options.threads.system_cpu_limit + ); assert_eq!( ( got.apparent_size, @@ -1640,3 +1658,54 @@ fn restart_arguments_parse_back_to_the_same_scan() { ); } } + +#[gpui_kit::test] +fn power_efficiency_menu_saves_without_discarding_the_tree( + cx: &mut TestAppContext, +) { + use crate::power::{self, PowerEfficiency as Power}; + use gpui_kit::Modifiers; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let config = tempfile::tempdir().expect("config"); + let path = config.path().join("power-efficiency"); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + update(&view, cx, |app, _| { + app.power_settings_path = Some(path.clone()); + }); + let epoch = read(&view, cx, |app| app.scan_epoch); + for preset in Power::ALL { + draw(cx); + let button = cx.debug_bounds("power-efficiency").expect("control"); + cx.simulate_click(button.center(), Modifiers::none()); + draw(cx); + let choice = cx.debug_bounds(preset.key()).expect("preset"); + cx.simulate_click(choice.center(), Modifiers::none()); + draw(cx); + assert_eq!(power::load(&path).expect("saved"), preset); + read(&view, cx, |app| { + assert_eq!(app.power_choice, Some(preset)); + assert_eq!( + app.options.threads.max_threads, + preset.threads(app.cpu_threads) + ); + assert!(!app.options.threads.adaptive); + assert!(!app.power_menu_open); + assert_eq!(app.scan_epoch, epoch); + assert!(app.tree.is_some()); + }); + } + // Persistence failure must not masquerade as a saved preference. + update(&view, cx, |app, cx| { + app.power_settings_path = Some(config.path().to_owned()); + app.set_power_efficiency(Power::Miser, cx); + }); + assert!(read(&view, cx, |app| app + .notice + .as_ref() + .is_some_and(|(message, _)| message.contains("could not save")))); + update(&view, cx, Disktree::start_scan); + assert_eq!(read(&view, cx, |app| app.scan_epoch), epoch + 1); +} diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index b3b4b61..57d842d 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -969,15 +969,114 @@ fn view_settings( div() .flex() - .flex_row() - .items_center() - .gap(space::SM) + .flex_col() + .items_end() + .gap(space::XS) .flex_shrink_0() - .child(history) - .child(mode) - .child(hidden) - .child(apparent) - .child(depth_control) + .child( + div() + .flex() + .items_center() + .gap(space::SM) + .child(history) + .child(mode) + .child(hidden) + .child(apparent) + .child(depth_control), + ) + .child(power_efficiency(app, cx)) +} + +/// Keep the four labeled choices in a popup so even the smallest window can +/// show the controls. Like the other settings, focus returns to the treemap. +fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { + let label = app.power_choice.map_or_else( + || "Custom".to_owned(), + |preset| preset.label(app.cpu_threads), + ); + let mut control = div().relative().child( + div() + .id("power-efficiency") + .debug_selector(|| "power-efficiency".into()) + .child( + button( + "power-toggle", + format!("Power Efficiency: {label}"), + ButtonVariant::Secondary, + cx, + ) + .tab_stop(false) + .on_click(cx.listener( + |this, _, window, cx| { + this.power_menu_open = !this.power_menu_open; + window.focus(&this.focus, cx); + cx.notify(); + }, + )), + ), + ); + if app.power_menu_open { + let theme = cx.omarchy().clone(); + let mut menu = div() + .id("power-menu") + .debug_selector(|| "power-menu".into()) + .occlude() + .flex() + .flex_col() + .w(size::SIBLING_MENU) + .p(space::SM) + .gap(space::XS) + .bg(theme.surface) + .border_1() + .border_color(theme.control_border()) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.power_menu_open = false; + cx.notify(); + })); + for preset in crate::power::PowerEfficiency::ALL { + let variant = if app.power_choice == Some(preset) { + ButtonVariant::Primary + } else { + ButtonVariant::Secondary + }; + menu = menu.child( + div() + .id(preset.key()) + .debug_selector(move || preset.key().into()) + .child( + button( + preset.key(), + preset.label(app.cpu_threads), + variant, + cx, + ) + .w_full() + .tab_stop(false) + .on_click(cx.listener( + move |this, _, window, cx| { + this.set_power_efficiency(preset, cx); + window.focus(&this.focus, cx); + }, + )), + ), + ); + } + menu = menu.child(div().text_size(text::CAPTION) + .text_color(theme.secondary) + .child("Saved for the next scan. Limits scan workers, not whole-app CPU or battery use.")); + control = control.child( + div().absolute().top_full().right_0().child( + deferred( + anchored() + .snap_to_window_with_margin(px(space::SM.0 * app.rem)) + .child(menu), + ) + .with_priority(2), + ), + ); + } + control } // ── trail and legend ──────────────────────────────────────────────────── diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index d62ce5e..5ff2531 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -769,6 +769,32 @@ impl PendingDir { } fn scan_blocking(root: &Path, context: &Arc) -> io::Result { + let owned = fixed_pool(context.options.threads)?; + let pool = owned.as_ref().unwrap_or_else(|| &WALK_POOL); + scan_on_pool(root, context, pool) +} + +/// Explicit fixed budgets cover enumeration, the Windows file-table path and +/// tree finishing. A scan owns its pool so a new setting needs no global reset. +/// Default core callers and experimental adaptive scans retain the shared pool. +fn fixed_pool(threads: ScanThreads) -> io::Result> { + if threads.adaptive || threads.max_threads == usize::MAX { + return Ok(None); + } + let cpus = thread::available_parallelism().map_or(1, usize::from); + rayon::ThreadPoolBuilder::new() + .num_threads(threads.max_threads.clamp(1, cpus)) + .thread_name(|index| format!("disktree-scan-{index}")) + .build() + .map(Some) + .map_err(io::Error::other) +} + +fn scan_on_pool( + root: &Path, + context: &Arc, + pool: &rayon::ThreadPool, +) -> io::Result { let root_meta = fs::metadata(root)?; if !root_meta.is_dir() { return Err(io::Error::new( @@ -800,7 +826,7 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { #[cfg(windows)] { let progress = &context.progress; - let read = WALK_POOL.install(|| { + let read = pool.install(|| { crate::mft::scan(root, canonical, &context.options, progress) }); if let Some(node) = read { @@ -810,7 +836,7 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { if progress.is_cancelled() { return Err(crate::mft::cancelled()); } - let node = finish_tree(node, &context.options); + let node = finish_tree(node, &context.options, pool); // The reader counted every file on the volume; the tree may // hold fewer. progress.settle(node.files, node.dirs, node.bytes); @@ -842,7 +868,7 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { 0, )); let context: &WalkContext = context; - WALK_POOL.install(|| { + pool.install(|| { let mut threads = context.options.threads.normalized(); threads.max_threads = threads.max_threads.min(rayon::current_num_threads()); @@ -887,7 +913,7 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { let node = node.ok_or_else(|| { io::Error::other(format!("{} produced no tree", root.display())) })?; - Ok(finish_tree(node, &context.options)) + Ok(finish_tree(node, &context.options, pool)) } /// The walk's workers, and the file table reader's. Listing directories @@ -1093,8 +1119,12 @@ fn signal_done(dir: &Arc, context: &WalkContext) { /// Charge a hardlinked file once, derive every aggregate from the result, /// then classify. On the walk's pool: the UI's own work on the global pool /// must not queue behind a scan finishing. -fn finish_tree(mut node: Node, options: &ScanOptions) -> Node { - WALK_POOL.install(|| { +fn finish_tree( + mut node: Node, + options: &ScanOptions, + pool: &rayon::ThreadPool, +) -> Node { + pool.install(|| { if options.dedup_hardlinks { aggregate_deduped(&mut node, options.metric, &Seen::new()); } else { @@ -1302,7 +1332,40 @@ mod tests { } #[test] - fn fixed_admission_preserves_a_wide_deep_tree() { + fn fixed_worker_pools_change_size_without_reinitializing_rayon() { + let cpus = thread::available_parallelism().map_or(1, usize::from); + // Two live pools have independent limits; constructing the first must + // not freeze the choice for a later scan or the global UI pool. + let make = |count| { + fixed_pool(ScanThreads { + max_threads: count, + ..ScanThreads::default() + }) + .expect("pool") + .expect("explicit fixed pool") + }; + let small = make(1); + let large = make(4); + assert_eq!(small.install(rayon::current_num_threads), 1); + assert_eq!(large.install(rayon::current_num_threads), 4.min(cpus)); + assert!( + fixed_pool(ScanThreads::default()) + .expect("default") + .is_none() + ); + assert!( + fixed_pool(ScanThreads { + adaptive: true, + max_threads: 4, + ..ScanThreads::default() + }) + .expect("adaptive") + .is_none() + ); + } + + #[test] + fn fixed_worker_pools_preserve_a_wide_deep_tree() { let temp = TempDir::new().expect("tempdir"); for index in 0..96 { write(temp.path(), &format!("d{index}/nested/file"), index + 1); diff --git a/crates/disktree-core/src/scan_threads.rs b/crates/disktree-core/src/scan_threads.rs index f285b8a..bd1767a 100644 --- a/crates/disktree-core/src/scan_threads.rs +++ b/crates/disktree-core/src/scan_threads.rs @@ -6,7 +6,9 @@ use std::sync::{Mutex, MutexGuard, PoisonError}; /// A scan crossing several volumes shares this budget; separate scans do not. #[derive(Clone, Copy, Debug)] pub struct ScanThreads { - /// Maximum admitted directory jobs, including jobs awaiting a Rayon worker. + /// Fixed scan workers, capped by available CPUs; `usize::MAX` uses the + /// shared platform-default pool. With `adaptive`, maximum admitted directory + /// jobs instead, including jobs awaiting a Rayon worker. pub max_threads: usize, /// Search below the cap and respond to whole-system CPU pressure. pub adaptive: bool, @@ -19,10 +21,10 @@ pub struct ScanThreads { impl Default for ScanThreads { fn default() -> Self { Self { - // Preserve core callers' pool-sized fixed concurrency. The macOS - // application explicitly selects its measured adaptive budget. + // Preserve core callers' pool-sized fixed concurrency. The app + // supplies the user's Power Efficiency preset before scanning. max_threads: usize::MAX, - // Core callers opt in; the application selects adaptive admission. + // Adaptive admission remains an explicit experimental opt-in. adaptive: false, retained_throughput: 0.80, system_cpu_limit: Some(0.80),