From 6c4be2c6bb0d670af08c3e374b994890cf899c3a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 20:42:57 -0700 Subject: [PATCH 1/7] ALI-2600: One message per failed copy or move, and undo a copy that fills its destination MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copying an 11 GB folder to a nearly full /tmp gave one notice per file left over, in the system's words ("e4_8b_pool_ld.upk: Disk quota exceeded"), four at a time. Now a job tells each reason once, and a full destination undoes the job instead of leaving half a folder behind. - Plainer reasons, by error kind, keeping "file name: reason" for a single failure: no space or quota ("There isn't enough space in “tmp”, which has 4.2 MB free"), permission (to change the folder written in, or to read the item), read-only drive, name too long, I/O error, and gone. Other kinds keep the system's words. - Failures are gathered during the job and told when it ends. Several with the same reason become one notice with a count ("12 files: You don't have permission to read them"), so a screen reader hears one announcement. - A copy, or a move to another disk, is measured before it starts. When the destination is on another filesystem and not a network share, the size is compared with the smaller of statvfs's free space and what's left of the user's quota (quotactl_fd, Q_GETQUOTA). If it won't fit, nothing starts: "“Life Is Strange” needs 11 GB, but “tmp” only has 6.3 GB free". - The first ENOSPC or EDQUOT stops the job. Everything it made is removed: the cut-short file, each folder it created (with what it put there), and, inside folders it merged into, each file it added. What a Replace sent to the Trash comes back. Nothing that was there before is touched. One message: "Couldn't copy “Life Is Strange”: there isn't enough space in “tmp”. Nothing was copied". - A move to another disk copies everything first and removes the originals only once all of it has arrived. If the destination fills, the copies go and the originals stay. A file that changed while it was being copied is kept, with a notice. - Extracting several archives that fail the same way is told once too. Tests: unit tests for each reason, for the grouping, and, on 4 MiB tmpfs disks that scripts/sandbox-run.sh now mounts, for a copy refused before it starts, one that fills partway, a merge that fills, and a move that fills. e2e checks for the same three cases on a 4 MiB tmpfs in the app's sandbox. GANNET_SKIP_SPACE_CHECK (bench builds only) lets a check fill a disk partway. Copy speed, home (btrfs) to /tmp (tmpfs), median of alternating runs: 2 GB file 405.1 ms on main, 401.9 ms here; 20,000 files 174.9 ms on main, 173.7 ms here. --- crates/app/src/main.rs | 2 + crates/core/src/lib.rs | 1 + crates/core/src/ops.rs | 776 ++++++++++++++++++++++++++++++++++----- crates/core/src/space.rs | 76 ++++ scripts/sandbox-run.sh | 5 + tests/e2e.py | 122 +++++- 6 files changed, 885 insertions(+), 97 deletions(-) create mode 100644 crates/core/src/space.rs diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 4587e9f..ff0fc7e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -267,6 +267,8 @@ fn main() { app.slow_read = std::env::var("GANNET_SLOW_READ_MS").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_millis); app.slow_preview = std::env::var("GANNET_SLOW_PREVIEW_MS").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_millis); app.engine.slow_copy = std::env::var("GANNET_SLOW_COPY_MS").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_millis); + // So the end-to-end checks can fill a disk partway through a move. + app.engine.skip_space_check = std::env::var_os("GANNET_SKIP_SPACE_CHECK").is_some(); // So the end-to-end checks can ask about an archive of a few MiB. if let Some(bytes) = std::env::var("GANNET_EXTRACT_ASK_AFTER").ok().and_then(|v| v.parse().ok()) { app.engine.extract_limits.ask_after = bytes; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2c954a6..4bc7f97 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -26,6 +26,7 @@ pub mod search; pub mod servers; pub mod settings; pub mod sort; +pub mod space; pub mod terminal; pub mod theme; pub mod thumbcache; diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index 4afd3ee..32c9f9e 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -6,10 +6,14 @@ //! - Nothing gets overwritten. Replace first moves the item already there to the Trash, //! and if it can't go there, both stay as they were. //! - Symlinks are copied and moved as symlinks, never followed. -//! - One item failing doesn't stop the others. Each failure gets reported. Renaming several -//! items at once is the exception: it's all or nothing, so the names never end up half -//! changed. -//! - A move across disks removes each source only after its copy succeeded. +//! - One item failing doesn't stop the others. Each failure gets reported, once per job for +//! items that failed the same way. Renaming several items at once is the exception: it's all +//! or nothing, so the names never end up half changed. +//! - A full destination is the other exception. A copy or move stops at the first "no space", +//! and everything the job made is taken away again, never anything that was there before. +//! A copy to another disk is checked for room before it starts, when that's cheap. +//! - A move across disks removes the sources only once all of it has been copied, and each +//! source only if its copy succeeded. //! - Folders never get replaced wholesale. Replace on two folders means merge. //! - Delete and cross-disk move stop at mount points inside a folder: another disk's //! contents are never removed because it happens to be mounted there. @@ -32,7 +36,8 @@ use std::time::{Duration, Instant}; use rustix::fs::{AtFlags, CWD, RenameFlags, StatxAttributes, StatxFlags, Timespec, Timestamps, XattrFlags, copy_file_range, fgetxattr, flistxattr, fsetxattr, futimens, renameat_with, sendfile, statx, syncfs}; use rustix::io::Errno; -use crate::listing::describe; +use crate::listing::{describe, size}; +use crate::space; use crate::trash::{self, MountCache, TrashConfig, TrashError, Trashed}; #[derive(Clone, Debug)] @@ -257,6 +262,8 @@ pub struct Engine { pub force_sync_error: bool, /// Test seam: copy with read and write, as on a kernel that refuses `sendfile`. pub force_no_sendfile: bool, + /// Test seam: don't check for room before a copy, so one can fill its destination partway. + pub skip_space_check: bool, /// Test seam: wait this long between a file's chunks as `copy_file_range` copies it, so a /// copy lasts long enough to follow its progress without writing gigabytes. The `sendfile` /// and read-and-write fallbacks don't wait. @@ -269,7 +276,7 @@ pub struct Engine { impl Engine { pub fn new(trash: TrashConfig, sink: Sink) -> Self { - Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } + Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, skip_space_check: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } } pub fn start(&self, request: Request) -> Job { @@ -283,11 +290,13 @@ impl Engine { force_exdev: self.force_exdev, force_sync_error: self.force_sync_error, force_no_sendfile: self.force_no_sendfile, + skip_space_check: self.skip_space_check, slow_copy: self.slow_copy, extractor: self.extractor.clone(), extract_limits: self.extract_limits, asked_expands: false, errors: 0, + failures: Vec::new(), noted_leftovers: 0, private_seen: false, sticky_files: None, @@ -295,6 +304,12 @@ impl Engine { last_merged: false, last_replaced: None, top_dev: 0, + need: 0, + measured: Default::default(), + full: false, + made: Vec::new(), + inside_new: false, + to_delete: Vec::new(), steps: Vec::new(), trashed: Vec::new(), mounts: MountCache::default(), @@ -311,6 +326,7 @@ impl Engine { run.execute(request); let trashed = std::mem::take(&mut run.trashed); run.sync_trash(&trashed); + run.tell_failures(); let steps = std::mem::take(&mut run.steps); let outcome = Outcome { job: run.job.id, @@ -487,6 +503,158 @@ enum Flow { Stop, } +/// Which side of a change an error came from, so its reason names the right thing. +#[derive(Clone, Copy)] +enum Side<'a> { + /// Reading the item. + Read, + /// Writing in this folder. + Write(&'a Path), + /// Changing the item where it is, as renaming or deleting it does. + Change, +} + +/// Which file of a copy an error came from. +enum End { + Source, + Copy, +} + +/// What went wrong, in plain words. `one` follows a single item's name, and `many` follows a +/// count of items that failed the same way. Failures with the same `key` are told as one. +#[derive(Debug, PartialEq)] +struct Reason { + key: String, + one: String, + many: String, +} + +impl Reason { + fn same(text: String) -> Reason { + Reason { key: text.clone(), one: text.clone(), many: text } + } +} + +/// `“name”`, for a path in a message. +fn quoted(p: &Path) -> String { + format!("“{}”", p.file_name().unwrap_or(p.as_os_str()).to_string_lossy()) +} + +/// Says why `item` failed, by the kind of error rather than the system's words for it, which +/// stay for kinds not listed here. +fn reason(e: &io::Error, item: &Path, side: Side) -> Reason { + let folder = match side { + Side::Read => None, + Side::Write(f) => Some(f), + Side::Change => item.parent().filter(|p| !p.as_os_str().is_empty()), + }; + let kind = e.raw_os_error().map(Errno::from_raw_os_error); + let fixed = |key: &str, one: &str, many: &str| Reason { key: key.into(), one: one.into(), many: many.into() }; + match (kind, folder) { + (Some(Errno::NOSPC | Errno::DQUOT), Some(f)) => { + let short = format!("There isn't enough space in {}", quoted(f)); + let text = match space::free(f) { + Some(free) => format!("{short}, which has {} free", size(free)), + None => short.clone(), + }; + Reason { key: short, one: text.clone(), many: text } + } + (Some(Errno::ACCESS | Errno::PERM), Some(f)) => Reason::same(format!("You don't have permission to change {}", quoted(f))), + (Some(Errno::ACCESS | Errno::PERM), None) => fixed("read permission", "You don't have permission to read it", "You don't have permission to read them"), + (Some(Errno::ROFS), Some(f)) => Reason::same(format!("{} is on a read-only drive", quoted(f))), + (Some(Errno::NAMETOOLONG), Some(f)) => Reason { key: format!("too long {}", f.display()), one: format!("The name is too long for {}", quoted(f)), many: format!("The names are too long for {}", quoted(f)) }, + (Some(Errno::IO), _) => Reason { + key: "io".into(), + one: format!("The drive couldn't read or write {}. It may be failing or have been unplugged", quoted(item)), + many: "The drive couldn't read or write them. It may be failing or have been unplugged".into(), + }, + // The folder being written in has gone. + (Some(Errno::NOENT), Some(f)) if matches!(side, Side::Write(_)) => Reason::same(format!("{} is no longer there", quoted(f))), + (Some(Errno::NOENT), _) => Reason { key: "gone".into(), one: format!("{} is no longer there", quoted(item)), many: "They're no longer there".into() }, + _ => Reason::same(describe(e)), + } +} + +/// Whether an error means the destination has no room left, on the disk or in the user's quota. +fn is_full(e: &io::Error) -> bool { + matches!(e.raw_os_error().map(Errno::from_raw_os_error), Some(Errno::NOSPC | Errno::DQUOT)) +} + +/// `20000` as `20,000`. +fn thousands(n: usize) -> String { + let digits = n.to_string(); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +/// One failure, told when the job ends, together with any others that failed the same way. +struct Failure { + path: PathBuf, + reason: Reason, +} + +/// The failures to tell, in the order they happened: one message for each reason. A reason +/// only one item had keeps the item's name first; several items with the same reason are +/// counted instead of named. +fn told(failures: Vec) -> Vec<(PathBuf, String)> { + let mut groups: Vec> = Vec::new(); + let mut by_key: std::collections::HashMap = std::collections::HashMap::new(); + for f in failures { + match by_key.get(&f.reason.key) { + Some(&i) => groups[i].push(f), + None => { + by_key.insert(f.reason.key.clone(), groups.len()); + groups.push(vec![f]); + } + } + } + groups + .into_iter() + .map(|mut g| { + if g.len() == 1 { + let f = g.remove(0); + return (f.path, f.reason.one); + } + let folders = g.iter().any(|f| fs::symlink_metadata(&f.path).is_ok_and(|m| m.is_dir())); + let noun = if folders { "items" } else { "files" }; + // The newest words, as how much space is free changes as a job goes on. + let last = g.pop().map(|f| f.reason.many).unwrap_or_default(); + (PathBuf::new(), format!("{} {noun}: {last}", thousands(g.len() + 1))) + }) + .collect() +} + +/// A top-level item placed by a copy or move, noted once the job settles. +struct Top { + src: PathBuf, + target: Option, + merged: bool, + replaced: Option, +} + +/// What a copy or move made, so a full destination can take it away again. +enum Made { + /// A file, link or folder that wasn't there before. A folder is taken away with + /// everything in it, which this job put there. + Item(PathBuf), + /// What a Replace moved to the Trash, to put back. + Replaced(Trashed), +} + +/// A source a move across disks has copied, removed once everything has been. +enum Moved { + /// With what it was when it was copied, so a file changed since is kept. + File { src: PathBuf, ino: u64, len: u64, mtime: (i64, i64) }, + /// Removed once empty. `clean` if nothing in it failed or was left on purpose. + Folder { src: PathBuf, clean: bool }, +} + struct Run { job: Job, sink: Sink, @@ -501,6 +669,8 @@ struct Run { /// once: Keep going covers the rest of the job's archives too. asked_expands: bool, errors: usize, + /// What went wrong, told when the job ends. See [`told`]. + failures: Vec, /// Items left in place on purpose, so a folder that won't empty isn't a surprise. noted_leftovers: usize, /// Whether `scan` met anything other users can't read. @@ -515,6 +685,19 @@ struct Run { /// a hard link of the same file can be what it replaces. last_replaced: Option, top_dev: u64, + /// What the scanned files will take on a disk. + need: u64, + /// Sources scanned before a move, so they aren't again when the move turns out to cross disks. + measured: std::collections::HashSet, + /// The destination filled up, so the copy or move stops and is undone. + full: bool, + /// What this copy or move made, outside the folders it made. See [`Made`]. + made: Vec, + /// Inside a folder this job made, whose contents go with it. + inside_new: bool, + /// What a move across disks has copied, for removing once it all has. + to_delete: Vec, + skip_space_check: bool, /// What this job changed, for its undo. steps: Vec, /// Everything this job moved to the Trash, to save to disk at the end. @@ -534,12 +717,21 @@ impl Run { fn execute(&mut self, request: Request) { match request { Request::Copy { sources, dest } => { - self.scan(&sources); - self.place_all(&sources, &dest, Mode::Copy); + let need = self.measure(&sources, &dest); + if self.room_for(&sources, &dest, need) { + self.place_all(&sources, &dest, Mode::Copy); + } } Request::Move { sources, dest } => { self.job.progress.total_items.store(sources.len() as u64, Ordering::Relaxed); - self.place_all(&sources, &dest, Mode::Move); + // What goes to another disk is copied, so it's measured first, as a copy is. + let dest_dev = fs::metadata(&dest).map(|m| m.dev()).ok(); + let away: Vec = sources.iter().filter(|s| self.force_exdev || fs::symlink_metadata(s).is_ok_and(|m| Some(m.dev()) != dest_dev)).cloned().collect(); + let need = self.measure(&away, &dest); + self.measured = away.into_iter().collect(); + if self.room_for(&sources, &dest, need) { + self.place_all(&sources, &dest, Mode::Move); + } } Request::Link { sources, dest } => { self.job.progress.total_items.store(sources.len() as u64, Ordering::Relaxed); @@ -637,7 +829,7 @@ impl Run { let Some(parent) = archive.parent() else { return }; let file = match File::open(archive) { Ok(f) => f, - Err(e) => return self.fail(archive, &e), + Err(e) => return self.fail_as(archive, &e, Side::Read), }; let tmp = temp_name(archive); if let Err(e) = fs::create_dir(&tmp) { @@ -1093,7 +1285,9 @@ impl Run { Step::Moved { from, to } => { self.last_target = None; let flow = self.place(&to.path, from.clone(), Mode::Move); - self.record_top_level(&to.path, Mode::Move); + let top = self.top(&to.path); + let back_in = from.parent().unwrap_or(&from).to_path_buf(); + self.settle(vec![top], std::slice::from_ref(&to.path), &back_in, Mode::Move); self.touch_parent(&from); self.touch_parent(&to.path); return flow; @@ -1153,12 +1347,37 @@ impl Run { } fn fail(&mut self, path: &Path, e: &io::Error) { - self.report(path, describe(e)); + self.fail_as(path, e, Side::Change); } + fn fail_as(&mut self, path: &Path, e: &io::Error, side: Side) { + self.errors += 1; + self.failures.push(Failure { path: path.to_path_buf(), reason: reason(e, path, side) }); + } + + /// Notes a failure, told when the job ends. An empty path is a message about no one item. fn report(&mut self, path: &Path, message: String) { self.errors += 1; - (self.sink)(Event::Error { job: self.job.id, path: path.to_path_buf(), message }); + self.failures.push(Failure { path: path.to_path_buf(), reason: Reason::same(message) }); + } + + /// Tells the job's failures, one message for each reason, so a folder of files that all + /// failed the same way gives one notice and one announcement, not one for each file. + fn tell_failures(&mut self) { + for (path, message) in told(std::mem::take(&mut self.failures)) { + (self.sink)(Event::Error { job: self.job.id, path, message }); + } + } + + /// A copy failed. A full destination stops the whole job, which is then undone, and says + /// so once; anything else is reported and the job goes on. + fn copy_failed(&mut self, item: &Path, e: &io::Error, side: Side) -> Flow { + if is_full(e) { + self.full = true; + return Flow::Stop; + } + self.fail_as(item, e, side); + Flow::Go } fn tick(&mut self) { @@ -1174,6 +1393,39 @@ impl Run { } } + /// Scans the sources for progress, and says what those on another disk than `dest` will + /// take there. On the same disk a copy can share the blocks, so it isn't counted. + fn measure(&mut self, sources: &[PathBuf], dest: &Path) -> u64 { + let dest_dev = fs::metadata(dest).map(|m| m.dev()).ok(); + let mut need = 0; + for src in sources { + let before = self.need; + self.scan(std::slice::from_ref(src)); + if fs::symlink_metadata(src).is_ok_and(|m| Some(m.dev()) != dest_dev) { + need += self.need - before; + } + } + need + } + + /// Whether `dest` has room for what's about to go there. If not, says so and nothing starts. + /// Skipped on a network share, where asking costs a round trip. + fn room_for(&mut self, sources: &[PathBuf], dest: &Path, need: u64) -> bool { + if need == 0 || self.skip_space_check || self.job.is_cancelled() || space::is_remote(dest) { + return true; + } + let Some(free) = space::free(dest) else { return true }; + if need <= free { + return true; + } + let what = match sources { + [one] => format!("{} needs", quoted(one)), + many => format!("These {} items need", thousands(many.len())), + }; + self.report(Path::new(""), format!("{what} {}, but {} only has {} free", size(need), quoted(dest), size(free))); + false + } + /// Adds up the bytes and items so progress has totals. fn scan(&mut self, paths: &[PathBuf]) { let progress = self.job.progress.clone(); @@ -1194,6 +1446,9 @@ impl Run { } } else { progress.total_bytes.fetch_add(m.len(), Ordering::Relaxed); + if m.is_file() { + self.need += space::on_disk(m.len()); + } } self.tick(); } @@ -1262,9 +1517,10 @@ impl Run { } fn place_all(&mut self, sources: &[PathBuf], dest: &Path, mode: Mode) { + let mut tops = Vec::with_capacity(sources.len()); for src in sources { if self.job.is_cancelled() { - return; + break; } let Some(name) = src.file_name() else { self.report(src, "This can't be copied or moved".into()); @@ -1277,7 +1533,7 @@ impl Run { let target = dest.join(name); self.last_target = None; let flow = self.place(src, target, mode); - self.record_top_level(src, mode); + tops.push(self.top(src)); if mode == Mode::Move { self.touch_parent(src); self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); @@ -1287,26 +1543,122 @@ impl Run { } self.tick(); if let Flow::Stop = flow { - return; + break; + } + } + self.settle(tops, sources, dest, mode); + } + + /// What `place` noted about the top-level item it just placed. + fn top(&mut self, src: &Path) -> Top { + Top { src: src.to_path_buf(), target: self.last_target.take(), merged: std::mem::take(&mut self.last_merged), replaced: self.last_replaced.take() } + } + + /// Ends a copy or move. If the destination filled up, everything the job made is taken away + /// and the sources are left as they were. If not, the sources of what was copied to another + /// disk are removed, now that all of it is there. + fn settle(&mut self, tops: Vec, sources: &[PathBuf], dest: &Path, mode: Mode) { + if !std::mem::take(&mut self.full) { + self.made.clear(); + self.delete_moved(); + for top in tops { + self.record_top_level(top, mode); + } + return; + } + self.undo_made(); + self.to_delete.clear(); + // Renamed on the same disk, so they took no room and have gone where they were asked to. + let mut moved = 0; + for top in tops { + if mode == Mode::Move && fs::symlink_metadata(&top.src).is_err() { + self.record_top_level(top, mode); + moved += 1; + } + } + let what = match sources { + [one] => quoted(one), + many => format!("{} items", thousands(many.len())), + }; + let (verb, done) = if mode == Mode::Copy { ("copy", "copied") } else { ("move", "moved") }; + let rest = match moved { + 0 => format!("Nothing was {done}"), + n => format!("{n} on the same drive were {done}, and the rest were left where they were"), + }; + self.report(Path::new(""), format!("Couldn't {verb} {what}: there isn't enough space in {}. {rest}", quoted(dest))); + } + + /// Takes away what this copy or move made, newest first, and puts back what it replaced. + fn undo_made(&mut self) { + for m in std::mem::take(&mut self.made).into_iter().rev() { + match m { + Made::Item(p) => { + remove_partial(&p); + self.touch_parent(&p); + } + Made::Replaced(t) => { + self.steps.retain(|s| !matches!(s, Step::Trashed { item, .. } if *item == t)); + self.trashed.retain(|x| *x != t); + self.touch_parent(&t.original); + self.put_back(t); + } + } + } + } + + /// Removes the sources a move across disks copied, last first, so each folder is empty by + /// the time it's reached. A file that changed since it was copied stays, as does anything + /// that couldn't be removed, and the folders holding them. + fn delete_moved(&mut self) { + let mut kept: Vec = Vec::new(); + for m in std::mem::take(&mut self.to_delete) { + match m { + Moved::File { src, ino, len, mtime } => match fs::symlink_metadata(&src) { + Ok(now) if now.ino() == ino && now.len() == len && (now.mtime(), now.mtime_nsec()) == mtime => { + if let Err(e) = fs::remove_file(&src) { + self.fail(&src, &e); + kept.push(src); + } + } + Ok(_) => { + self.report(&src, "This changed while it was being moved, so the original was kept as well".into()); + kept.push(src); + } + // Gone already, which is what was wanted. + Err(_) => {} + }, + Moved::Folder { src, clean } => match fs::remove_dir(&src) { + Ok(()) => {} + // Expected if something in it stayed. If not, something new appeared while + // the move went on, and that deserves a mention. + Err(e) if e.raw_os_error() == Some(Errno::NOTEMPTY.raw_os_error()) => { + if clean && !kept.iter().any(|k| k.starts_with(&src)) { + self.report(&src, "Something new appeared here during the move, so the folder was kept".into()); + } + kept.push(src); + } + Err(e) => { + self.fail(&src, &e); + kept.push(src); + } + }, } } } /// Notes where a top-level item ended up. Only top-level items are steps and things to /// select: undoing a folder's move or copy takes its contents with it. - fn record_top_level(&mut self, src: &Path, mode: Mode) { - let merged = std::mem::take(&mut self.last_merged); - let replaced = self.last_replaced.take(); - let Some(target) = self.last_target.take() else { return }; + fn record_top_level(&mut self, top: Top, mode: Mode) { + let Some(target) = top.target else { return }; let Some(stamp) = Stamp::of(&target) else { return }; - if replaced == Some(false) { + if top.replaced == Some(false) { return; } // Undoing a merge would also take what was in the destination before, so it has no undo. - if !merged { + if !top.merged { match mode { // A move that left its source behind went only partway, and isn't undone as a whole. - Mode::Move if fs::symlink_metadata(src).is_err() => self.steps.push(Step::Moved { from: src.to_path_buf(), to: stamp }), + Mode::Move if fs::symlink_metadata(&top.src).is_err() => self.steps.push(Step::Moved { from: top.src, to: stamp }), Mode::Move => {} Mode::Copy => self.steps.push(Step::Made(stamp)), } @@ -1323,7 +1675,7 @@ impl Run { let smeta = match fs::symlink_metadata(src) { Ok(m) => m, Err(e) => { - self.fail(src, &e); + self.fail_as(src, &e, Side::Read); return Flow::Go; } }; @@ -1403,7 +1755,7 @@ impl Run { } // Across disks: copy then remove, measuring what's about to move. The // top item's scan covers everything below it. - if self.depth == 0 { + if self.depth == 0 && !self.measured.contains(src) { self.scan(&[src.to_path_buf()]); } } @@ -1411,18 +1763,21 @@ impl Run { if let Some(t) = old { self.put_back(t); } - self.fail(src, &e); + // A move changes both folders, so name the one it can't write in. + let into = parent_of(&target); + let side = if rustix::fs::access(into, rustix::fs::Access::WRITE_OK).is_err() { Side::Write(into) } else { Side::Change }; + self.fail_as(src, &e, side); return Flow::Go; } } - } else if mode == Mode::Move && !merge && self.depth == 0 { + } else if mode == Mode::Move && !merge && self.depth == 0 && !self.measured.contains(src) { self.scan(&[src.to_path_buf()]); } let ft = smeta.file_type(); if ft.is_dir() { self.copy_dir(src, &target, &smeta, mode, merge) } else if ft.is_symlink() { - self.copy_symlink(src, &target, replace, mode) + self.copy_symlink(src, &target, &smeta, replace, mode) } else if ft.is_file() { self.copy_file(src, &target, &smeta, replace, mode) } else { @@ -1515,119 +1870,133 @@ impl Run { let mut b = fs::DirBuilder::new(); b.mode(smeta.permissions().mode() & 0o7777 | 0o700); if let Err(e) = b.create(target) { - self.fail(target, &e); - return Flow::Go; + return self.copy_failed(target, &e, Side::Write(parent_of(target))); } created = true; + if !self.inside_new { + self.made.push(Made::Item(target.to_path_buf())); + } } let entries = match fs::read_dir(src) { Ok(rd) => rd, Err(e) => { - self.fail(src, &e); + self.fail_as(src, &e, Side::Read); // Nothing went in, and an empty folder would look like a successful copy. if created { let _ = fs::remove_dir(target); + if !self.inside_new { + self.made.pop(); + } } return Flow::Go; } }; let leftovers_before = self.errors + self.noted_leftovers; + // What goes in a folder this job made goes with it, so it needn't be noted one by one. + let outer = self.inside_new; + self.inside_new |= created; + let mut flow = Flow::Go; for e in entries { let e = match e { Ok(e) => e, Err(err) => { - self.fail(src, &err); + self.fail_as(src, &err, Side::Read); continue; } }; self.depth += 1; - let flow = self.place(&e.path(), target.join(e.file_name()), mode); + flow = self.place(&e.path(), target.join(e.file_name()), mode); self.depth -= 1; if let Flow::Stop = flow { - if created { - finish_folder(target, smeta); - } - return Flow::Stop; + break; } } + self.inside_new = outer; if created { finish_folder(target, smeta); } + if let Flow::Stop = flow { + return Flow::Stop; + } if mode == Mode::Move { - // Fails only if something stayed behind (skipped or errored). That's right: it stays. - match fs::remove_dir(src) { - Ok(()) => {} - // Expected if something below was skipped or failed. If not, something - // new appeared while we worked, and that deserves a mention. - Err(e) if e.raw_os_error() == Some(Errno::NOTEMPTY.raw_os_error()) => { - if self.errors + self.noted_leftovers == leftovers_before { - self.report(src, "Something new appeared here during the move, so the folder was kept".into()); - } - } - Err(e) => self.fail(src, &e), - } + // Removed once the whole move has been copied. It stays if anything in it was + // skipped or failed, which is right. + self.to_delete.push(Moved::Folder { src: src.to_path_buf(), clean: self.errors + self.noted_leftovers == leftovers_before }); } self.job.progress.done_items.fetch_add(u64::from(mode == Mode::Copy), Ordering::Relaxed); self.tick(); Flow::Go } - fn copy_symlink(&mut self, src: &Path, target: &Path, replace: bool, mode: Mode) -> Flow { + fn copy_symlink(&mut self, src: &Path, target: &Path, smeta: &Metadata, replace: bool, mode: Mode) -> Flow { + let points_to = match fs::read_link(src) { + Ok(p) => p, + Err(e) => { + self.fail_as(src, &e, Side::Read); + return Flow::Go; + } + }; let tmp = temp_name(target); - if let Err(e) = fs::read_link(src).and_then(|dest| std::os::unix::fs::symlink(&dest, &tmp)) { - self.fail(target, &e); - return Flow::Go; + if let Err(e) = std::os::unix::fs::symlink(&points_to, &tmp) { + return self.copy_failed(target, &e, Side::Write(parent_of(target))); } - self.put_in_place(src, &tmp, target, replace, mode); - Flow::Go + self.put_in_place(src, &tmp, target, smeta, replace, mode) } /// Renames a finished copy at `tmp` to `target`, first moving what's there to the Trash /// if it replaces it. Whatever goes wrong, the copy is removed and the rest is left as it was. - fn put_in_place(&mut self, src: &Path, tmp: &Path, target: &Path, replace: bool, mode: Mode) { + fn put_in_place(&mut self, src: &Path, tmp: &Path, target: &Path, smeta: &Metadata, replace: bool, mode: Mode) -> Flow { let old = match replace { true => match self.trash_replaced(src, target) { Some(t) => Some(t), None => { let _ = fs::remove_file(tmp); - return; + return Flow::Go; } }, false => None, }; match rename_noreplace(tmp, target) { Ok(()) => { + // Noted before the copy, so undoing them puts the copy away first. if let Some(t) = old { + self.made.push(Made::Replaced(t.clone())); self.kept_replaced(t); } - self.finish_item(src, target, mode); + if !self.inside_new { + self.made.push(Made::Item(target.to_path_buf())); + } + self.finish_item(src, target, smeta, mode) } Err(e) => { let _ = fs::remove_file(tmp); if let Some(t) = old { self.put_back(t); } - self.fail(target, &e); + self.copy_failed(target, &e, Side::Write(parent_of(target))) } } } /// Bookkeeping once something is fully in place. - fn finish_item(&mut self, src: &Path, target: &Path, mode: Mode) { + fn finish_item(&mut self, src: &Path, target: &Path, smeta: &Metadata, mode: Mode) -> Flow { if mode == Mode::Move { // The name must be on disk too before the only other copy goes away. let synced = target.parent().map_or(Ok(()), |p| File::open(p).and_then(|d| self.sync_for_move(&d))); if let Err(e) = synced { + if is_full(&e) { + self.full = true; + return Flow::Stop; + } self.report(src, format!("Copied, but couldn't confirm it reached the disk, so the original stays: {}", describe(&e))); - return; - } - if let Err(e) = fs::remove_file(src) { - self.fail(src, &e); + return Flow::Go; } + self.to_delete.push(Moved::File { src: src.to_path_buf(), ino: smeta.ino(), len: smeta.len(), mtime: (smeta.mtime(), smeta.mtime_nsec()) }); } else { self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); } self.tick(); + Flow::Go } fn copy_file(&mut self, src: &Path, target: &Path, smeta: &Metadata, replace: bool, mode: Mode) -> Flow { @@ -1638,20 +2007,24 @@ impl Run { let _ = fs::remove_file(&tmp); return Flow::Stop; } - Err(e) => { + Err((e, end)) => { + // The part copied so far goes too, full destination or not. let _ = fs::remove_file(&tmp); - self.fail(src, &e); - return Flow::Go; + let side = match end { + End::Source => Side::Read, + End::Copy => Side::Write(parent_of(target)), + }; + return self.copy_failed(src, &e, side); } } - self.put_in_place(src, &tmp, target, replace, mode); - Flow::Go + self.put_in_place(src, &tmp, target, smeta, replace, mode) } - /// Copies bytes and metadata to `tmp`. `Ok(false)` means cancelled. - fn copy_contents(&mut self, src: &Path, tmp: &Path, smeta: &Metadata, mode: Mode) -> io::Result { - let input = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(src)?; - let output = OpenOptions::new().write(true).create_new(true).mode(0o600).open(tmp)?; + /// Copies bytes and metadata to `tmp`. `Ok(false)` means cancelled. An error says which + /// file it came from. + fn copy_contents(&mut self, src: &Path, tmp: &Path, smeta: &Metadata, mode: Mode) -> Result { + let input = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(src).map_err(|e| (e, End::Source))?; + let output = OpenOptions::new().write(true).create_new(true).mode(0o600).open(tmp).map_err(|e| (e, End::Copy))?; let mut copied = 0u64; let mut fallback = false; const CHUNK: usize = 8 * 1024 * 1024; @@ -1675,7 +2048,7 @@ impl Run { break; } Err(Errno::INTR) => continue, - Err(e) => return Err(e.into()), + Err(e) => return Err((e.into(), End::Copy)), } } // Some pseudo filesystems report no bytes from copy_file_range but have data. @@ -1686,7 +2059,8 @@ impl Run { progress.done_bytes.fetch_add(n, Ordering::Relaxed); self.tick(); !self.job.is_cancelled() - })?; + }) + .map_err(|e| (e, End::Copy))?; match sent { Sent::Cancelled => return Ok(false), Sent::Complete(n) => { @@ -1707,12 +2081,12 @@ impl Run { let n = match input.read(&mut buf) { Ok(n) => n, Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, - Err(e) => return Err(e), + Err(e) => return Err((e, End::Source)), }; if n == 0 { break; } - out.write_all(&buf[..n])?; + out.write_all(&buf[..n]).map_err(|e| (e, End::Copy))?; copied += n as u64; progress.done_bytes.fetch_add(n as u64, Ordering::Relaxed); self.tick(); @@ -1720,20 +2094,20 @@ impl Run { } } if copied < smeta.len() { - return Err(io::Error::other("The file got shorter while it was being copied")); + return Err((io::Error::other("The file got shorter while it was being copied"), End::Source)); } copy_xattrs(&input, &output); // Setuid and setgid are dropped: the copy belongs to whoever made it. Some // filesystems (FAT, some FUSE) refuse chmod, and that's no reason to fail. match output.set_permissions(fs::Permissions::from_mode(smeta.permissions().mode() & 0o777)) { - Err(e) if !matches!(e.raw_os_error().map(Errno::from_raw_os_error), Some(Errno::PERM | Errno::OPNOTSUPP)) => return Err(e), + Err(e) if !matches!(e.raw_os_error().map(Errno::from_raw_os_error), Some(Errno::PERM | Errno::OPNOTSUPP)) => return Err((e, End::Copy)), _ => {} } let _ = set_mtime(&output, smeta); if mode == Mode::Move { - self.sync_for_move(&output)?; + self.sync_for_move(&output).map_err(|e| (e, End::Copy))?; } - close_checked(output)?; + close_checked(output).map_err(|e| (e, End::Copy))?; Ok(true) } @@ -1752,7 +2126,7 @@ impl Run { let meta = match fs::symlink_metadata(path) { Ok(m) => m, Err(e) => { - self.fail(path, &e); + self.fail_as(path, &e, Side::Read); return; } }; @@ -1767,12 +2141,12 @@ impl Run { for e in rd { match e { Ok(e) => self.delete_tree(&e.path()), - Err(err) => self.fail(path, &err), + Err(err) => self.fail_as(path, &err, Side::Read), } } } Err(e) => { - self.fail(path, &e); + self.fail_as(path, &e, Side::Read); return; } } @@ -1798,6 +2172,11 @@ impl Run { } } +/// The folder `path` is in, for saying where something couldn't be written. +fn parent_of(path: &Path) -> &Path { + path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(path) +} + /// True if `path`, a folder below a top-level item on device `top_dev`, is a mount point. /// The device check catches ordinary mounts and the attribute catches bind mounts. fn is_mount_boundary(path: &Path, m: &Metadata, top_dev: u64) -> bool { @@ -1912,8 +2291,8 @@ fn only_folder(dir: &Path) -> Option { Some(one.file_name()) } -/// Removes what a failed or cancelled extract left, whatever the job's cancel says. It never -/// follows a link, and stays on the disk it started on. +/// Removes what a failed or cancelled extract left, or a copy that filled its destination, +/// whatever the job's cancel says. It never follows a link, and stays on the disk it started on. fn remove_partial(path: &Path) { fn go(path: &Path, dev: u64) { let Ok(m) = fs::symlink_metadata(path) else { return }; @@ -2365,7 +2744,7 @@ mod tests { let done = finish(&rx, vec![]); fs::set_permissions(&bad, fs::Permissions::from_mode(0o600)).unwrap(); assert_eq!(done.errors.len(), 1, "{:?}", done.errors); - assert!(done.errors[0].1.contains("denied")); + assert_eq!(done.errors[0], (bad.clone(), "You don't have permission to read it".to_string())); assert!(s.path().join("dest/good").exists()); assert!(!s.path().join("dest/bad").exists()); no_partials(&s.path().join("dest")); @@ -3453,8 +3832,9 @@ mod tests { crafted_tar(&links, &[("ln", b"", Some("../..")), ("ln/through.txt", b"bad", None)]); e.start(Request::Extract { archives: vec![evil, links] }); let done = finish(&rx, vec![]); - assert_eq!(done.errors.len(), 2, "{:?}", done.errors); - assert!(done.errors.iter().all(|(_, m)| m.contains("outside its folder")), "{:?}", done.errors); + // Told once for both. + assert_eq!(done.errors, [(PathBuf::new(), "2 files: It holds items that would land outside its folder, so nothing was extracted".to_string())]); + assert_eq!(done.outcome.errors, 2); assert!(done.outcome.created.is_empty() && done.outcome.undo.is_none()); assert!(!s.path().join("escaped.txt").exists() && !s.path().join("through.txt").exists()); assert_eq!(names_in(&work), ["evil.tar", "links.tar"]); @@ -3474,8 +3854,7 @@ mod tests { crafted_tar(&dot, &[("x", b"", Some(".")), ("y", b"", Some("x/.."))]); e.start(Request::Extract { archives: vec![up, absolute, dot] }); let done = finish(&rx, vec![]); - assert_eq!(done.errors.len(), 3, "{:?}", done.errors); - assert!(done.errors.iter().all(|(_, m)| m.contains("outside its folder")), "{:?}", done.errors); + assert_eq!(done.errors, [(PathBuf::new(), "3 files: It holds items that would land outside its folder, so nothing was extracted".to_string())]); assert!(done.outcome.created.is_empty() && done.outcome.undo.is_none()); assert_eq!(names_in(&work), ["absolute.tar", "dot.tar", "up.tar"]); @@ -3501,8 +3880,7 @@ mod tests { crafted_tar(&sib, &[("proj/a.txt", b"a", None), ("proj/sib", b"", Some("../sib"))]); e.start(Request::Extract { archives: vec![up, sib] }); let done = finish(&rx, vec![]); - assert_eq!(done.errors.len(), 2, "{:?}", done.errors); - assert!(done.errors.iter().all(|(_, m)| m.contains("outside its folder")), "{:?}", done.errors); + assert_eq!(done.errors, [(PathBuf::new(), "2 files: It holds items that would land outside its folder, so nothing was extracted".to_string())]); assert_eq!(names_in(&work), ["sib.tar", "up.tar"]); let fine = work.join("fine.tar"); @@ -3608,9 +3986,10 @@ mod tests { e.start(Request::Extract { archives: vec![garbage, truncated, locked] }); let done = finish(&rx, vec![]); let messages: Vec<&str> = done.errors.iter().map(|(_, m)| m.as_str()).collect(); - assert_eq!(messages.len(), 3, "{messages:?}"); - assert!(messages[0].contains("damaged") && messages[1].contains("damaged"), "{messages:?}"); - assert!(messages[2].contains("password"), "{messages:?}"); + // The two damaged ones are told together. + assert_eq!(messages.len(), 2, "{messages:?}"); + assert!(messages[0].starts_with("2 files: ") && messages[0].contains("damaged"), "{messages:?}"); + assert!(messages[1].contains("password"), "{messages:?}"); assert!(done.outcome.created.is_empty()); assert_eq!(names_in(&work), ["broken.zip", "locked.zip", "truncated.zip"]); } @@ -4298,4 +4677,209 @@ mod tests { assert_eq!(done.outcome.undo, None, "nothing is left to undo"); assert!(done.outcome.created.is_empty()); } + + fn errno(e: Errno) -> io::Error { + io::Error::from_raw_os_error(e.raw_os_error()) + } + + #[test] + fn each_kind_of_failure_has_plain_words() { + let s = Scratch::new(); + let folder = s.dir("Backups"); + let item = folder.join("photo.jpg"); + let one = |e: Errno, side: Side| reason(&errno(e), &item, side).one; + let many = |e: Errno, side: Side| reason(&errno(e), &item, side).many; + let w = Side::Write(&folder); + for full in [Errno::NOSPC, Errno::DQUOT] { + let said = one(full, w); + assert!(said.starts_with("There isn't enough space in “Backups”, which has ") && said.ends_with(" free"), "{said}"); + } + assert_eq!(one(Errno::ACCESS, w), "You don't have permission to change “Backups”"); + assert_eq!(one(Errno::PERM, w), "You don't have permission to change “Backups”"); + assert_eq!(one(Errno::ACCESS, Side::Read), "You don't have permission to read it"); + assert_eq!(many(Errno::PERM, Side::Read), "You don't have permission to read them"); + assert_eq!(one(Errno::ROFS, w), "“Backups” is on a read-only drive"); + assert_eq!(one(Errno::NAMETOOLONG, w), "The name is too long for “Backups”"); + assert_eq!(many(Errno::NAMETOOLONG, w), "The names are too long for “Backups”"); + assert_eq!(one(Errno::IO, w), "The drive couldn't read or write “photo.jpg”. It may be failing or have been unplugged"); + assert_eq!(many(Errno::IO, Side::Read), "The drive couldn't read or write them. It may be failing or have been unplugged"); + assert_eq!(one(Errno::NOENT, Side::Read), "“photo.jpg” is no longer there"); + assert_eq!(many(Errno::NOENT, Side::Read), "They're no longer there"); + assert_eq!(one(Errno::NOENT, w), "“Backups” is no longer there", "the folder being written in went"); + // Changing an item where it is names its folder. + assert_eq!(one(Errno::ACCESS, Side::Change), "You don't have permission to change “Backups”"); + assert_eq!(one(Errno::NOENT, Side::Change), "“photo.jpg” is no longer there"); + // Anything else keeps the system's words. + assert_eq!(one(Errno::BUSY, w), "Device or resource busy"); + } + + fn failure(path: &str, e: Errno, side: Side) -> Failure { + Failure { path: PathBuf::from(path), reason: reason(&errno(e), Path::new(path), side) } + } + + #[test] + fn one_failure_keeps_its_name_and_repeats_are_counted() { + let one = told(vec![failure("/x/a.txt", Errno::ACCESS, Side::Read)]); + assert_eq!(one, [(PathBuf::from("/x/a.txt"), "You don't have permission to read it".to_string())]); + let mut many: Vec = (0..12).map(|i| failure(&format!("/x/{i}.txt"), Errno::ACCESS, Side::Read)).collect(); + many.insert(3, failure("/x/gone.txt", Errno::NOENT, Side::Read)); + assert_eq!( + told(many), + [(PathBuf::new(), "12 files: You don't have permission to read them".to_string()), (PathBuf::from("/x/gone.txt"), "“gone.txt” is no longer there".to_string())], + "a group is told where its first failure was" + ); + let same_text: Vec = (0..2).map(|i| Failure { path: PathBuf::from(format!("/x/{i}")), reason: Reason::same("Special files like sockets and devices aren't copied".into()) }).collect(); + assert_eq!(told(same_text)[0].1, "2 files: Special files like sockets and devices aren't copied"); + assert_eq!(thousands(20000), "20,000"); + assert_eq!(thousands(999), "999"); + assert_eq!(thousands(1_234_567), "1,234,567"); + } + + #[test] + fn a_folder_among_the_failures_counts_them_as_items() { + let s = Scratch::new(); + let d = s.dir("d"); + let f = s.file("f", b""); + let both = vec![Failure { path: d, reason: Reason::same("x".into()) }, Failure { path: f, reason: Reason::same("x".into()) }]; + assert_eq!(told(both)[0].1, "2 items: x"); + } + + #[test] + fn a_job_with_many_unreadable_files_tells_them_once() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + for i in 0..5 { + let f = s.file(&format!("src/locked{i}"), b"x"); + fs::set_permissions(&f, fs::Permissions::from_mode(0o000)).unwrap(); + } + s.file("src/fine", b"y"); + e.start(Request::Copy { sources: vec![s.path().join("src")], dest: s.dir("dest") }); + let done = finish(&rx, vec![]); + for i in 0..5 { + fs::set_permissions(s.path().join(format!("src/locked{i}")), fs::Permissions::from_mode(0o600)).unwrap(); + } + assert_eq!(done.errors, [(PathBuf::new(), "5 files: You don't have permission to read them".to_string())]); + assert_eq!(done.outcome.errors, 5); + assert!(s.path().join("dest/src/fine").exists()); + } + + /// A tiny disk of its own, 4 MiB, that scripts/sandbox-run.sh mounts for this test alone. + fn small_disk(name: &str) -> PathBuf { + let d = Path::new("/run/gannet-small").join(name); + assert!(fs::metadata(&d).is_ok(), "run tests with scripts/test.sh"); + d + } + + /// `n` files of 1 MiB in `dir`, more than a small disk holds. + fn megabytes(s: &Scratch, dir: &str, n: usize) { + for i in 0..n { + s.file(&format!("{dir}/part{i}.bin"), &patterned(1 << 20)); + } + } + + fn contents(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names + } + + #[test] + fn a_copy_that_wont_fit_doesnt_start() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + megabytes(&s, "Big Folder", 6); + let disk = small_disk("refuse"); + e.start(Request::Copy { sources: vec![s.path().join("Big Folder")], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors.len(), 1, "{:?}", done.errors); + let (path, said) = &done.errors[0]; + assert_eq!(path, Path::new("")); + assert!(said.starts_with("“Big Folder” needs 6.3 MB, but “refuse” only has ") && said.ends_with(" free"), "{said}"); + assert!(contents(&disk).is_empty(), "nothing was started"); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_copy_that_fills_its_disk_partway_is_taken_away() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + megabytes(&s, "Big Folder/inner", 6); + let disk = small_disk("fill"); + let job = e.start(Request::Copy { sources: vec![s.path().join("Big Folder")], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “Big Folder”: there isn't enough space in “fill”. Nothing was copied".to_string())]); + assert!(contents(&disk).is_empty(), "{:?}", contents(&disk)); + assert_eq!(done.outcome.undo, None); + assert!(done.outcome.created.is_empty()); + assert!(job.progress.done_bytes.load(Ordering::Relaxed) > 0, "it did start"); + } + + #[test] + fn a_full_merge_takes_away_only_what_it_added() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + let disk = small_disk("merge"); + let top = disk.clone(); + // Replace sends what it replaces to that disk's own Trash. + e.trash.mount_of = Arc::new(move |p| p.starts_with(&top).then(|| top.clone())); + fs::create_dir_all(disk.join("data/kept")).unwrap(); + fs::write(disk.join("data/old.txt"), b"was here").unwrap(); + fs::write(disk.join("data/kept/inside"), b"also here").unwrap(); + fs::write(disk.join("data/a.bin"), b"old a").unwrap(); + s.file("data/a.bin", b"new a"); + megabytes(&s, "data", 3); + megabytes(&s, "data/kept", 1); + megabytes(&s, "data/new folder", 2); + e.start(Request::Copy { sources: vec![s.path().join("data")], dest: disk.clone() }); + // Replace merges the folders, and applies to the files as well. + let done = finish(&rx, vec![answer(Choice::Replace), answer(Choice::Replace), all(Choice::Replace)]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “data”: there isn't enough space in “merge”. Nothing was copied".to_string())]); + assert_eq!(contents(&disk.join("data")), ["a.bin", "kept", "old.txt"]); + assert_eq!(contents(&disk.join("data/kept")), ["inside"]); + assert_eq!(fs::read(disk.join("data/old.txt")).unwrap(), b"was here"); + assert_eq!(fs::read(disk.join("data/a.bin")).unwrap(), b"old a", "what a Replace sent to the Trash is back"); + no_partials(&disk); + } + + #[test] + fn a_move_to_a_disk_that_fills_leaves_the_originals() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + megabytes(&s, "src/Life/maps", 3); + megabytes(&s, "src/Life", 3); + s.file("src/notes.txt", b"small"); + let before = contents(&s.path().join("src/Life")); + let disk = small_disk("move"); + e.start(Request::Move { sources: vec![s.path().join("src/notes.txt"), s.path().join("src/Life")], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't move 2 items: there isn't enough space in “move”. Nothing was moved".to_string())]); + assert!(contents(&disk).is_empty(), "{:?}", contents(&disk)); + assert_eq!(contents(&s.path().join("src/Life")), before); + assert_eq!(contents(&s.path().join("src/Life/maps")).len(), 3); + assert_eq!(fs::read(s.path().join("src/notes.txt")).unwrap(), b"small", "moved first, and still kept"); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_move_across_disks_keeps_a_file_changed_while_it_was_copied() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.force_exdev = true; + // Two chunks, with a pause between them. + e.slow_copy = Some(Duration::from_millis(500)); + let f = s.file("src/d/a", &patterned(CHUNK_FOR_TESTS)); + let d = s.dir("dest"); + e.start(Request::Move { sources: vec![s.path().join("src/d")], dest: d.clone() }); + std::thread::sleep(Duration::from_millis(150)); + fs::OpenOptions::new().append(true).open(&f).unwrap().write_all(b"more").unwrap(); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(f.clone(), "This changed while it was being moved, so the original was kept as well".to_string())]); + assert_eq!(fs::read(&f).unwrap().len(), CHUNK_FOR_TESTS + 4); + assert_eq!(done.outcome.undo, None); + } + + const CHUNK_FOR_TESTS: usize = 8 * 1024 * 1024 + 1; } diff --git a/crates/core/src/space.rs b/crates/core/src/space.rs new file mode 100644 index 0000000..1f98e02 --- /dev/null +++ b/crates/core/src/space.rs @@ -0,0 +1,76 @@ +//! How much room a folder's filesystem has left for this user. + +use std::fs::File; +use std::os::fd::AsRawFd; +use std::path::Path; + +use crate::mounts; + +/// The bytes this user can still write in `folder`: the smaller of what the filesystem has free +/// and what's left of the user's quota on it. `/tmp` on a tmpfs mounted with `usrquota` can +/// say gigabytes are free while the quota has room for far less. `None` if it can't be told. +pub fn free(folder: &Path) -> Option { + let f = File::open(folder).ok()?; + let vfs = rustix::fs::fstatvfs(&f).ok()?; + let disk = vfs.f_bavail.saturating_mul(vfs.f_frsize); + Some(quota_left(&f).map_or(disk, |q| q.min(disk))) +} + +/// What's left of this user's block quota on the file's filesystem, if it has one. +fn quota_left(f: &File) -> Option { + // QCMD(Q_GETQUOTA, USRQUOTA): the command above the type's byte. + const GET_USER_QUOTA: libc::c_uint = (libc::Q_GETQUOTA as libc::c_uint) << 8; + // SAFETY: an all-zero dqblk is valid; it's plain integers. + let mut q: libc::dqblk = unsafe { std::mem::zeroed() }; + // SAFETY: the fd is open for the call, and q is a dqblk the kernel fills in. + let r = unsafe { libc::syscall(libc::SYS_quotactl_fd, f.as_raw_fd(), GET_USER_QUOTA, libc::getuid(), &mut q as *mut libc::dqblk) }; + if r != 0 || q.dqb_valid & libc::QIF_BLIMITS == 0 || q.dqb_bhardlimit == 0 { + return None; + } + // The limit is in 1 KiB blocks and the use in bytes. + Some(q.dqb_bhardlimit.saturating_mul(1024).saturating_sub(q.dqb_curspace)) +} + +/// Whether `folder` is on a network share or FUSE, where asking for free space is a round +/// trip that can hang. A FUSE drive on a local disk (`fuseblk`, as ntfs-3g) is asked. +pub fn is_remote(folder: &Path) -> bool { + let all = mounts::read_mounts(); + let Some(point) = mounts::mount_point_of(&all, folder) else { return false }; + all.iter().rev().find(|m| m.point == point).is_some_and(|m| mounts::inodes_may_change(&m.fs_type) && m.fs_type != "fuseblk") +} + +/// What a file of `len` bytes takes on a disk with 4 KiB blocks, which most use. +pub fn on_disk(len: u64) -> u64 { + len.div_ceil(4096).saturating_mul(4096) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_file_takes_whole_blocks() { + assert_eq!(on_disk(0), 0); + assert_eq!(on_disk(1), 4096); + assert_eq!(on_disk(4096), 4096); + assert_eq!(on_disk(4097), 8192); + } + + #[test] + fn free_space_is_never_more_than_the_disk_has() { + let s = crate::testutil::Scratch::new(); + let disk = rustix::fs::statvfs(s.path()).map(|v| v.f_bavail * v.f_frsize).unwrap(); + let free = free(s.path()).unwrap(); + assert!(free <= disk, "{free} > {disk}"); + } + + #[test] + fn a_small_tmpfs_says_how_little_it_has() { + // scripts/sandbox-run.sh mounts these, 4 MiB each. + let free = free(Path::new(SMALL)).unwrap(); + assert!(free <= 4 << 20 && free > 0, "{free}"); + assert!(!is_remote(Path::new(SMALL))); + } + + const SMALL: &str = "/run/gannet-small/space"; +} diff --git a/scripts/sandbox-run.sh b/scripts/sandbox-run.sh index 444d508..5f1c788 100755 --- a/scripts/sandbox-run.sh +++ b/scripts/sandbox-run.sh @@ -6,7 +6,12 @@ BIN=$(realpath "$1"); shift SCRATCH=$(mktemp -d "$ROOT/target/test/sandbox.XXXXXX") trap 'rm -rf "$SCRATCH"' EXIT mkdir -p "$SCRATCH/home" "$SCRATCH/tmp" +# Tiny disks of their own, for tests of a destination that fills up. One for each such test, +# as tests run side by side. +small=() +for name in space refuse fill merge move; do small+=(--size 4194304 --tmpfs "/run/gannet-small/$name"); done bwrap --die-with-parent --unshare-pid --unshare-net --ro-bind / / --dev /dev --proc /proc --tmpfs /run --tmpfs /run/gannet-tree/mnt --tmpfs "$HOME" \ + "${small[@]}" \ --bind "$SCRATCH/home" "$SCRATCH/home" --bind "$SCRATCH/tmp" /tmp \ --ro-bind "$BIN" "$BIN" --ro-bind "$ROOT" "$ROOT" --bind "$SCRATCH" "$SCRATCH" \ --chdir "$ROOT" \ diff --git a/tests/e2e.py b/tests/e2e.py index 076062b..b4d22bb 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -3471,6 +3471,126 @@ def long_copies_show_progress_and_cancel(h): a.close() +def AppWithSmallDisk(h, start, disk, extra_env=None): + """A window with a 4 MiB disk of its own at `disk`, which the test can't see from outside.""" + disk.mkdir(exist_ok=True) + return App(h, start, extra_env=extra_env, bwrap_extra=("--size", str(4 << 20), "--tmpfs", str(disk))) + + +def megabytes(fs, folder, n): + """`n` files of 1 MiB in `folder`, so a few of them fill the small disk.""" + for i in range(n): + p = fs / folder / f"part{i}.bin" + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(os.urandom(1 << 20)) + + +def paste_into(a, folder, copy=True): + a.key("a", mods=["ctrl"]) + a.key("c" if copy else "x", mods=["ctrl"]) + time.sleep(0.1) + a.key("l", mods=["ctrl"]) + a.type(str(folder)) + a.key("Return") + a.wait(lambda s: s["dir"] == str(folder) and not s["loading"], f"at {folder}") + a.key("v", mods=["ctrl"]) + + +@check +def a_copy_too_big_for_the_disk_never_starts(h): + fs = fresh_fs() + disk = SCRATCH / "smalldisk" + megabytes(fs, "src/Life Is Strange", 6) + a = AppWithSmallDisk(h, fs / "src", disk) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "refused") + a.shot("copy-wont-fit") + assert len(s["notices"]) == 1, s["notices"] + assert re.fullmatch(r"“Life Is Strange” needs 6\.3 MB, but “smalldisk” only has [0-9.]+ [kM]B free", s["notices"][0]), s["notices"] + time.sleep(0.3) + assert a.state()["names"] == [], "nothing was started" + a.close() + + +@check +def a_copy_that_fills_the_disk_is_undone_even_in_a_merge(h): + fs = fresh_fs() + disk = SCRATCH / "smalldisk" + tree(fs, {"old/data/old.txt": "was here", "old/data/kept/inside.txt": "also here"}) + megabytes(fs, "new/data", 3) + megabytes(fs, "new/data/kept", 1) + megabytes(fs, "new/data/new folder", 2) + megabytes(fs, "big/Big Folder", 6) + # Skips the check before starting, so the copies fill the disk partway. + a = AppWithSmallDisk(h, fs / "big", disk, extra_env={"GANNET_SKIP_SPACE_CHECK": "1"}) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "filled and undone") + a.shot("copy-filled") + assert s["notices"] == ["Couldn't copy “Big Folder”: there isn't enough space in “smalldisk”. Nothing was copied"], s["notices"] + assert s["names"] == [], s["names"] + a.key("Escape") + a.wait(lambda s: not s["notices"]) + # A folder that was there before keeps everything it had. + a.key("l", mods=["ctrl"]) + a.type(str(fs / "old")) + a.key("Return") + a.wait(lambda s: s["dir"] == str(fs / "old") and s["count"] == 1) + paste_into(a, disk) + a.wait(lambda s: s["jobs"] == 0 and s["names"] == ["data"], "the folder that will be merged into") + a.key("l", mods=["ctrl"]) + a.type(str(fs / "new")) + a.key("Return") + a.wait(lambda s: s["dir"] == str(fs / "new") and s["count"] == 1) + paste_into(a, disk) + a.wait(lambda s: s["dialog"] == "conflict", "asks about the folder") + time.sleep(0.45) # A new conflict ignores input for a moment. + a.type("a") # For every folder: "kept" clashes too. + a.key("Left") + a.key("Return") # Merge. + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "merge filled and undone") + assert s["notices"] == ["Couldn't copy “data”: there isn't enough space in “smalldisk”. Nothing was copied"], s["notices"] + a.key("Escape") + a.key("l", mods=["ctrl"]) + a.type(str(disk / "data")) + a.key("Return") + s = a.wait(lambda s: s["dir"] == str(disk / "data") and not s["loading"], "in the merged folder") + assert sorted(s["names"]) == ["kept", "old.txt"], s["names"] + a.key("l", mods=["ctrl"]) + a.type(str(disk / "data/kept")) + a.key("Return") + s = a.wait(lambda s: s["dir"] == str(disk / "data/kept") and not s["loading"], "in the folder inside") + assert s["names"] == ["inside.txt"], s["names"] + a.close() + + +@check +def a_move_that_fills_the_other_disk_leaves_the_originals(h): + fs = fresh_fs() + disk = SCRATCH / "smalldisk" + megabytes(fs, "src/Life/maps", 3) + megabytes(fs, "src/Life", 3) + before = sorted(str(p.relative_to(fs)) for p in (fs / "src").rglob("*")) + a = AppWithSmallDisk(h, fs / "src", disk, extra_env={"GANNET_SKIP_SPACE_CHECK": "1"}) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk, copy=False) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "filled and undone") + a.shot("move-filled") + assert s["notices"] == ["Couldn't move “Life”: there isn't enough space in “smalldisk”. Nothing was moved"], s["notices"] + assert s["names"] == [], s["names"] + assert sorted(str(p.relative_to(fs)) for p in (fs / "src").rglob("*")) == before, "the originals are all there" + # Without the skip, the same move is refused before it starts. + a.close() + a = AppWithSmallDisk(h, fs / "src", disk) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk, copy=False) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "refused") + assert s["notices"][0].startswith("“Life” needs 6.3 MB, but “smalldisk” only has "), s["notices"] + assert sorted(str(p.relative_to(fs)) for p in (fs / "src").rglob("*")) == before + a.close() + + @check def failures_are_visible(h): fs = fresh_fs() @@ -3489,7 +3609,7 @@ def failures_are_visible(h): a.key("v", mods=["ctrl"]) s = a.wait(lambda s: s["jobs"] == 0 and len(s["notices"]) >= 2, "each failure reported") a.shot("failures") - assert any("denied" in n for n in s["notices"]), s["notices"] + assert any("You don't have permission" in n for n in s["notices"]), s["notices"] assert [p.name for p in (fs / "ro").iterdir()] == ["x"] # They stay until dismissed. time.sleep(0.5) From 3df15e09ff01c2d6fea16836930388e8a805ce9f Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:56:30 -0700 Subject: [PATCH 2/7] ALI-2600: Skip the free-space check on the same mounts path completion avoids space::is_remote now uses complete::avoided_fs, as the path bar's completion does: network shares, autofs and FUSE other than fuseblk, never /, and any mount inside one of them counts as it. --- crates/core/src/space.rs | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/core/src/space.rs b/crates/core/src/space.rs index 1f98e02..d932670 100644 --- a/crates/core/src/space.rs +++ b/crates/core/src/space.rs @@ -4,7 +4,7 @@ use std::fs::File; use std::os::fd::AsRawFd; use std::path::Path; -use crate::mounts; +use crate::{complete, mounts}; /// The bytes this user can still write in `folder`: the smaller of what the filesystem has free /// and what's left of the user's quota on it. `/tmp` on a tmpfs mounted with `usrquota` can @@ -31,12 +31,16 @@ fn quota_left(f: &File) -> Option { Some(q.dqb_bhardlimit.saturating_mul(1024).saturating_sub(q.dqb_curspace)) } -/// Whether `folder` is on a network share or FUSE, where asking for free space is a round -/// trip that can hang. A FUSE drive on a local disk (`fuseblk`, as ntfs-3g) is asked. +/// Whether `folder` is on, or inside, a network share, autofs or FUSE mount, where asking for +/// free space is a round trip that can hang. The same mounts the path bar's completion keeps +/// out of ([`complete::avoided_fs`]): a FUSE drive on a local disk (`fuseblk`, as ntfs-3g) is +/// asked, and so is `/`, even as a container's fuse-overlayfs root. pub fn is_remote(folder: &Path) -> bool { - let all = mounts::read_mounts(); - let Some(point) = mounts::mount_point_of(&all, folder) else { return false }; - all.iter().rev().find(|m| m.point == point).is_some_and(|m| mounts::inodes_may_change(&m.fs_type) && m.fs_type != "fuseblk") + remote_in(&mounts::read_mounts(), folder) +} + +fn remote_in(all: &[mounts::Mount], folder: &Path) -> bool { + all.iter().any(|m| complete::avoided_fs(&m.fs_type) && m.point != Path::new("/") && folder.starts_with(&m.point)) } /// What a file of `len` bytes takes on a disk with 4 KiB blocks, which most use. @@ -72,5 +76,17 @@ mod tests { assert!(!is_remote(Path::new(SMALL))); } + #[test] + fn shares_and_fuse_are_never_asked_but_local_disks_are() { + let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "fuse.fuse-overlayfs"), m("/mnt/nas", "cifs"), m("/mnt/nas/usb", "ext4"), m("/run/media/me/USB", "fuseblk"), m("/home/me/cloud", "fuse.rclone"), m("/net", "autofs")]; + assert!(!remote_in(&all, Path::new("/home/me/Documents")), "/ is never a share"); + assert!(remote_in(&all, Path::new("/mnt/nas/photos"))); + assert!(remote_in(&all, Path::new("/mnt/nas/usb")), "a mount inside a share counts as the share"); + assert!(!remote_in(&all, Path::new("/run/media/me/USB/x"))); + assert!(remote_in(&all, Path::new("/home/me/cloud"))); + assert!(remote_in(&all, Path::new("/net/host"))); + } + const SMALL: &str = "/run/gannet-small/space"; } From a8333a4e41ca500250e44925de2dbf73c956c5af Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 23:14:04 -0700 Subject: [PATCH 3/7] ALI-2600: Review round 1: a clearer space check, stopped moves taken back, names kept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The check for room counts the blocks the sources have allocated, not their size rounded up, and is skipped when the answer isn't clear: a source's name is already in the destination (a merge or a conflict), or the destination is on btrfs, zfs or bcachefs (compression, shared or deduped blocks), a network share or FUSE. Sources on the destination's device, as through a bind mount, still aren't counted. A plain overflow is still refused, and only the sources from other devices are counted in "These N items need". - Stopping a move across disks, by Cancel or by the dialog, removes the copies it made and deletes no original: "Stopped moving “X”. Nothing was moved", in place of "Stopped: Moving…" (Outcome::stopped). - A collapsed notice keeps the first 5 paths and the count in Event::Error. The job keeps a count per reason and those 5 paths, not every failure. The command line tells each failure with its own path (Engine::tell_each), and an error about no one item has no path. - Removing the sources of a move: only "not found" counts as gone. Another error is reported and the source stays, and isn't recorded as moved. - A rename that fails with no space is handled as a full destination. - Asking for free space for the "not enough space" reason skips shares. - Wording: "It's no longer there" and "couldn't read or write it" after the name, "1 on the same drive was moved", and no-space reasons in two folders with one name are told apart. - Module doc notes two known limits: the paths a big move holds until the end, and a folder the job made going with what others put in it. --- crates/app/src/app.rs | 4 +- crates/app/tests/cli.rs | 13 ++ crates/core/src/cli.rs | 6 +- crates/core/src/ops.rs | 429 ++++++++++++++++++++++++++++++--------- crates/core/src/space.rs | 39 ++-- scripts/sandbox-run.sh | 2 +- 6 files changed, 384 insertions(+), 109 deletions(-) diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index acbd218..a7e817f 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -3279,8 +3279,8 @@ impl App { if o.cancelled && let Some(v) = &view { - // The user asked for it, so it only tells. - self.note(format!("Stopped: {}", v.job.label)); + // The user asked for it, so it only tells. A move taken back says so. + self.note(o.stopped.clone().unwrap_or_else(|| format!("Stopped: {}", v.job.label))); } if let (Some(v), [made]) = (&view, o.created.as_slice()) && v.say_made diff --git a/crates/app/tests/cli.rs b/crates/app/tests/cli.rs index c1563d5..7035363 100644 --- a/crates/app/tests/cli.rs +++ b/crates/app/tests/cli.rs @@ -96,6 +96,19 @@ fn failures_go_to_stderr_with_exit_code_1() { assert!(text(&out.stdout).ends_with(&want), "{}", text(&out.stdout)); } +#[test] +fn each_path_that_fails_gets_its_own_error() { + let h = Home::new("each-path"); + // They fail alike, which the window tells as one notice, but here each keeps its path. + let out = h.gannet(&["trash", "--json", "a", "b", "c"]); + assert_eq!(out.status.code(), Some(1)); + let json = text(&out.stdout); + for name in ["a", "b", "c"] { + assert!(json.contains(&format!("{{\"path\":\"{}\",", h.work().join(name).display())), "{name}: {json}"); + } + assert!(!json.contains("\"path\":\"\""), "no error without its path: {json}"); +} + #[test] fn help_names_the_commands() { let h = Home::new("help"); diff --git a/crates/core/src/cli.rs b/crates/core/src/cli.rs index e7f70bd..0ea291e 100644 --- a/crates/core/src/cli.rs +++ b/crates/core/src/cli.rs @@ -342,9 +342,11 @@ fn trash_record(cfg: &TrashConfig, path: &Path) -> Option> { /// Runs one job in the operations engine, as the window would, and waits for it. fn run_job(env: &Env, request: Request, report: &mut Report) -> Option { let (tx, rx) = mpsc::channel(); - let engine = Engine::new(env.trash.clone(), Arc::new(move |e| { + let mut engine = Engine::new(env.trash.clone(), Arc::new(move |e| { let _ = tx.send(e); })); + // Each path given gets its own result, not one message for all that failed alike. + engine.tell_each = true; engine.start(request); // Only the job's thread can send now, so a job that dies ends the wait instead of hanging it. drop(engine); @@ -359,7 +361,7 @@ fn run_job(env: &Env, request: Request, report: &mut Report) -> Option let _ = q.reply.send(false); } // The window's advice about Shift+Delete means nothing here. - Event::Error { path, message, .. } => report.fail(Some(&path), message.trim_end_matches(" Shift+Delete deletes for good.")), + Event::Error { path, message, .. } => report.fail(Some(path.as_path()).filter(|p| !p.as_os_str().is_empty()), message.trim_end_matches(" Shift+Delete deletes for good.")), Event::Finished(o) => return Some(o), } } diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index d231edb..a4b9684 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -11,13 +11,18 @@ //! or nothing, so the names never end up half changed. //! - A full destination is the other exception. A copy or move stops at the first "no space", //! and everything the job made is taken away again, never anything that was there before. -//! A copy to another disk is checked for room before it starts, when that's cheap. +//! A copy to another disk is checked for room before it starts, when that's cheap and the +//! answer is clear. A move across disks that is stopped is taken back the same way. //! - A move across disks removes the sources only once all of it has been copied, and each //! source only if its copy succeeded. //! - Folders never get replaced wholesale. Replace on two folders means merge. //! - Delete and cross-disk move stop at mount points inside a folder: another disk's //! contents are never removed because it happens to be mounted there. //! - A cross-disk move syncs each copy to disk before removing its source. +//! - Two known limits of taking a copy back. A move across disks notes each source it copied +//! until the end, so a tree of millions of files holds millions of paths for a while. And a +//! folder the job made goes with everything in it, which includes anything another program +//! put there while the job ran. //! - Undo and redo act only on the item a change left behind, told apart by its disk, //! inode, birth time and inode generation, never on something else that has since taken //! its name. Neither ever deletes anything but an empty folder that the change made. @@ -238,6 +243,8 @@ pub struct Outcome { pub created: Vec, /// Folders that changed, so the UI can refresh them if inotify can't see them. pub touched: Vec, + /// For a cancelled job that was taken back, what to say instead of that it stopped. + pub stopped: Option, } pub enum Event { @@ -245,7 +252,10 @@ pub enum Event { Progress(u64), Conflict(Conflict), Expands(Expands), - Error { job: u64, path: PathBuf, message: String }, + /// Something went wrong, told when the job ends, one message for each reason. `path` is + /// the item when only one failed this way, and empty when the message counts several or is + /// about no one item. `paths` holds the first few that failed this way, of `count` in all. + Error { job: u64, path: PathBuf, message: String, paths: Vec, count: usize }, Finished(Outcome), } @@ -264,6 +274,9 @@ pub struct Engine { pub force_no_sendfile: bool, /// Test seam: don't check for room before a copy, so one can fill its destination partway. pub skip_space_check: bool, + /// Tell each failure as it happens, with its own path, rather than once per reason at the + /// end. For the command line, which reports each path it was given. + pub tell_each: bool, /// Test seam: wait this long between a file's chunks as `copy_file_range` copies it, so a /// copy lasts long enough to follow its progress without writing gigabytes. The `sendfile` /// and read-and-write fallbacks don't wait. @@ -276,7 +289,7 @@ pub struct Engine { impl Engine { pub fn new(trash: TrashConfig, sink: Sink) -> Self { - Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, skip_space_check: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } + Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, skip_space_check: false, tell_each: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } } /// A job for work done somewhere else, like formatting a drive, so it shows and can be @@ -304,7 +317,9 @@ impl Engine { extract_limits: self.extract_limits, asked_expands: false, errors: 0, - failures: Vec::new(), + failures: Failures::default(), + tell_each: self.tell_each, + stopped: None, noted_leftovers: 0, private_seen: false, sticky_files: None, @@ -345,6 +360,7 @@ impl Engine { reversed: run.reversed, created: std::mem::take(&mut run.created), touched: std::mem::take(&mut run.touched), + stopped: run.stopped.take(), }; (run.sink)(Event::Finished(outcome)); }) @@ -561,11 +577,13 @@ fn reason(e: &io::Error, item: &Path, side: Side) -> Reason { match (kind, folder) { (Some(Errno::NOSPC | Errno::DQUOT), Some(f)) => { let short = format!("There isn't enough space in {}", quoted(f)); - let text = match space::free(f) { + // Asking a share costs a round trip that can hang. + let free = if space::is_remote(f) { None } else { space::free(f) }; + let text = match free { Some(free) => format!("{short}, which has {} free", size(free)), - None => short.clone(), + None => short, }; - Reason { key: short, one: text.clone(), many: text } + Reason { key: format!("no space {}", f.display()), one: text.clone(), many: text } } (Some(Errno::ACCESS | Errno::PERM), Some(f)) => Reason::same(format!("You don't have permission to change {}", quoted(f))), (Some(Errno::ACCESS | Errno::PERM), None) => fixed("read permission", "You don't have permission to read it", "You don't have permission to read them"), @@ -573,12 +591,12 @@ fn reason(e: &io::Error, item: &Path, side: Side) -> Reason { (Some(Errno::NAMETOOLONG), Some(f)) => Reason { key: format!("too long {}", f.display()), one: format!("The name is too long for {}", quoted(f)), many: format!("The names are too long for {}", quoted(f)) }, (Some(Errno::IO), _) => Reason { key: "io".into(), - one: format!("The drive couldn't read or write {}. It may be failing or have been unplugged", quoted(item)), + one: "The drive couldn't read or write it. It may be failing or have been unplugged".into(), many: "The drive couldn't read or write them. It may be failing or have been unplugged".into(), }, // The folder being written in has gone. (Some(Errno::NOENT), Some(f)) if matches!(side, Side::Write(_)) => Reason::same(format!("{} is no longer there", quoted(f))), - (Some(Errno::NOENT), _) => Reason { key: "gone".into(), one: format!("{} is no longer there", quoted(item)), many: "They're no longer there".into() }, + (Some(Errno::NOENT), _) => fixed("gone", "It's no longer there", "They're no longer there"), _ => Reason::same(describe(e)), } } @@ -601,41 +619,70 @@ fn thousands(n: usize) -> String { out } -/// One failure, told when the job ends, together with any others that failed the same way. -struct Failure { - path: PathBuf, - reason: Reason, +/// How many of a group's paths are kept to tell, however many failed. +const NAMED: usize = 5; + +/// Failures with one reason, told together when the job ends. Only the first few paths are +/// kept, so a job where every file fails holds a count, not a list of them all. +struct Group { + one: String, + many: String, + paths: Vec, + count: usize, + folders: bool, +} + +/// What a job has failed at so far, by reason, in the order each reason first came up. +#[derive(Default)] +struct Failures { + groups: Vec, + by_key: std::collections::HashMap, } -/// The failures to tell, in the order they happened: one message for each reason. A reason -/// only one item had keeps the item's name first; several items with the same reason are -/// counted instead of named. -fn told(failures: Vec) -> Vec<(PathBuf, String)> { - let mut groups: Vec> = Vec::new(); - let mut by_key: std::collections::HashMap = std::collections::HashMap::new(); - for f in failures { - match by_key.get(&f.reason.key) { - Some(&i) => groups[i].push(f), +impl Failures { + fn add(&mut self, path: &Path, reason: Reason) { + let i = match self.by_key.get(&reason.key) { + Some(&i) => i, None => { - by_key.insert(f.reason.key.clone(), groups.len()); - groups.push(vec![f]); + self.by_key.insert(reason.key.clone(), self.groups.len()); + self.groups.push(Group { one: reason.one.clone(), many: String::new(), paths: Vec::new(), count: 0, folders: false }); + self.groups.len() - 1 } - } + }; + let g = &mut self.groups[i]; + g.count += 1; + // The newest words, as how much space is free changes as a job goes on. + g.many = reason.many; + if g.paths.len() < NAMED { + g.folders |= fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()); + g.paths.push(path.to_path_buf()); + } + } + + /// One message for each reason. A reason only one item had keeps the item's name first; + /// several items with the same reason are counted instead of named, and the first few + /// of them go with the message. + fn told(self) -> Vec { + self.groups + .into_iter() + .map(|g| { + if g.count == 1 { + return Told { path: g.paths[0].clone(), message: g.one, paths: g.paths, count: 1 }; + } + let noun = if g.folders { "items" } else { "files" }; + Told { path: PathBuf::new(), message: format!("{} {noun}: {}", thousands(g.count), g.many), paths: g.paths, count: g.count } + }) + .collect() } - groups - .into_iter() - .map(|mut g| { - if g.len() == 1 { - let f = g.remove(0); - return (f.path, f.reason.one); - } - let folders = g.iter().any(|f| fs::symlink_metadata(&f.path).is_ok_and(|m| m.is_dir())); - let noun = if folders { "items" } else { "files" }; - // The newest words, as how much space is free changes as a job goes on. - let last = g.pop().map(|f| f.reason.many).unwrap_or_default(); - (PathBuf::new(), format!("{} {noun}: {last}", thousands(g.len() + 1))) - }) - .collect() +} + +/// One message about a job's failures. See [`Event::Error`]. +#[derive(Debug, PartialEq)] +struct Told { + path: PathBuf, + message: String, + paths: Vec, + count: usize, } /// A top-level item placed by a copy or move, noted once the job settles. @@ -677,8 +724,11 @@ struct Run { /// once: Keep going covers the rest of the job's archives too. asked_expands: bool, errors: usize, - /// What went wrong, told when the job ends. See [`told`]. - failures: Vec, + /// What went wrong, told when the job ends. See [`Failures`]. + failures: Failures, + tell_each: bool, + /// Said instead of "Stopped" when a cancelled move was taken back. + stopped: Option, /// Items left in place on purpose, so a folder that won't empty isn't a surprise. noted_leftovers: usize, /// Whether `scan` met anything other users can't read. @@ -725,8 +775,8 @@ impl Run { fn execute(&mut self, request: Request) { match request { Request::Copy { sources, dest } => { - let need = self.measure(&sources, &dest); - if self.room_for(&sources, &dest, need) { + let (need, away) = self.measure(&sources, &dest); + if self.room_for(&away, &dest, need) { self.place_all(&sources, &dest, Mode::Copy); } } @@ -734,10 +784,10 @@ impl Run { self.job.progress.total_items.store(sources.len() as u64, Ordering::Relaxed); // What goes to another disk is copied, so it's measured first, as a copy is. let dest_dev = fs::metadata(&dest).map(|m| m.dev()).ok(); - let away: Vec = sources.iter().filter(|s| self.force_exdev || fs::symlink_metadata(s).is_ok_and(|m| Some(m.dev()) != dest_dev)).cloned().collect(); - let need = self.measure(&away, &dest); - self.measured = away.into_iter().collect(); - if self.room_for(&sources, &dest, need) { + let copied: Vec = sources.iter().filter(|s| self.force_exdev || fs::symlink_metadata(s).is_ok_and(|m| Some(m.dev()) != dest_dev)).cloned().collect(); + let (need, away) = self.measure(&copied, &dest); + self.measured = copied.into_iter().collect(); + if self.room_for(&away, &dest, need) { self.place_all(&sources, &dest, Mode::Move); } } @@ -1359,21 +1409,29 @@ impl Run { } fn fail_as(&mut self, path: &Path, e: &io::Error, side: Side) { - self.errors += 1; - self.failures.push(Failure { path: path.to_path_buf(), reason: reason(e, path, side) }); + let r = reason(e, path, side); + self.note_failure(path, r); } /// Notes a failure, told when the job ends. An empty path is a message about no one item. fn report(&mut self, path: &Path, message: String) { + self.note_failure(path, Reason::same(message)); + } + + fn note_failure(&mut self, path: &Path, reason: Reason) { self.errors += 1; - self.failures.push(Failure { path: path.to_path_buf(), reason: Reason::same(message) }); + if self.tell_each { + (self.sink)(Event::Error { job: self.job.id, path: path.to_path_buf(), message: reason.one, paths: vec![path.to_path_buf()], count: 1 }); + } else { + self.failures.add(path, reason); + } } /// Tells the job's failures, one message for each reason, so a folder of files that all /// failed the same way gives one notice and one announcement, not one for each file. fn tell_failures(&mut self) { - for (path, message) in told(std::mem::take(&mut self.failures)) { - (self.sink)(Event::Error { job: self.job.id, path, message }); + for t in std::mem::take(&mut self.failures).told() { + (self.sink)(Event::Error { job: self.job.id, path: t.path, message: t.message, paths: t.paths, count: t.count }); } } @@ -1401,32 +1459,45 @@ impl Run { } } - /// Scans the sources for progress, and says what those on another disk than `dest` will - /// take there. On the same disk a copy can share the blocks, so it isn't counted. - fn measure(&mut self, sources: &[PathBuf], dest: &Path) -> u64 { + /// Scans the sources for progress, and says which are on another device than `dest` and + /// what they take: the blocks allocated to them on their own disk, so a sparse file counts + /// only what it holds. Sources on the same device as `dest` aren't counted. A copy there + /// shares blocks only on a filesystem with reflinks, but a disk that fills is caught as the + /// copy goes, and the copy is taken back. + fn measure(&mut self, sources: &[PathBuf], dest: &Path) -> (u64, Vec) { let dest_dev = fs::metadata(dest).map(|m| m.dev()).ok(); let mut need = 0; + let mut away = Vec::new(); for src in sources { let before = self.need; self.scan(std::slice::from_ref(src)); if fs::symlink_metadata(src).is_ok_and(|m| Some(m.dev()) != dest_dev) { need += self.need - before; + away.push(src.clone()); } } - need + (need, away) } - /// Whether `dest` has room for what's about to go there. If not, says so and nothing starts. - /// Skipped on a network share, where asking costs a round trip. - fn room_for(&mut self, sources: &[PathBuf], dest: &Path, need: u64) -> bool { - if need == 0 || self.skip_space_check || self.job.is_cancelled() || space::is_remote(dest) { + /// Whether `dest` has room for `away`, the sources from other devices, which take `need`. + /// If clearly not, says so and nothing starts. Anything that makes the need unclear skips + /// the check, and a disk that fills anyway is caught as the copy goes: + /// - something with a source's name is already in `dest`, to be merged into or asked about; + /// - `dest` is on a network share or FUSE, where asking costs a round trip; + /// - `dest` is on btrfs, zfs or bcachefs, which can compress, share blocks with other + /// subvolumes of one pool, or dedupe. See [`space::worth_checking`]. + fn room_for(&mut self, away: &[PathBuf], dest: &Path, need: u64) -> bool { + if need == 0 || self.skip_space_check || self.job.is_cancelled() { + return true; + } + if away.iter().any(|s| s.file_name().is_some_and(|n| fs::symlink_metadata(dest.join(n)).is_ok())) || !space::worth_checking(dest) { return true; } let Some(free) = space::free(dest) else { return true }; if need <= free { return true; } - let what = match sources { + let what = match away { [one] => format!("{} needs", quoted(one)), many => format!("These {} items need", thousands(many.len())), }; @@ -1454,9 +1525,7 @@ impl Run { } } else { progress.total_bytes.fetch_add(m.len(), Ordering::Relaxed); - if m.is_file() { - self.need += space::on_disk(m.len()); - } + self.need += m.blocks() * 512; } self.tick(); } @@ -1566,7 +1635,11 @@ impl Run { /// and the sources are left as they were. If not, the sources of what was copied to another /// disk are removed, now that all of it is there. fn settle(&mut self, tops: Vec, sources: &[PathBuf], dest: &Path, mode: Mode) { - if !std::mem::take(&mut self.full) { + let full = std::mem::take(&mut self.full); + // A move stopped partway across disks is taken back too, so nothing is half moved: + // no original goes until all of it has arrived. + let stopped = mode == Mode::Move && self.job.is_cancelled() && !(self.made.is_empty() && self.to_delete.is_empty()); + if !full && !stopped { self.made.clear(); self.delete_moved(); for top in tops { @@ -1579,7 +1652,7 @@ impl Run { // Renamed on the same disk, so they took no room and have gone where they were asked to. let mut moved = 0; for top in tops { - if mode == Mode::Move && fs::symlink_metadata(&top.src).is_err() { + if mode == Mode::Move && is_gone(&top.src) { self.record_top_level(top, mode); moved += 1; } @@ -1591,9 +1664,14 @@ impl Run { let (verb, done) = if mode == Mode::Copy { ("copy", "copied") } else { ("move", "moved") }; let rest = match moved { 0 => format!("Nothing was {done}"), - n => format!("{n} on the same drive were {done}, and the rest were left where they were"), + 1 => format!("1 on the same drive was {done}, and the rest were left where they were"), + n => format!("{} on the same drive were {done}, and the rest were left where they were", thousands(n)), }; - self.report(Path::new(""), format!("Couldn't {verb} {what}: there isn't enough space in {}. {rest}", quoted(dest))); + if full { + self.report(Path::new(""), format!("Couldn't {verb} {what}: there isn't enough space in {}. {rest}", quoted(dest))); + } else { + self.stopped = Some(format!("Stopped moving {what}. {rest}")); + } } /// Takes away what this copy or move made, newest first, and puts back what it replaced. @@ -1614,9 +1692,10 @@ impl Run { } } - /// Removes the sources a move across disks copied, last first, so each folder is empty by - /// the time it's reached. A file that changed since it was copied stays, as does anything - /// that couldn't be removed, and the folders holding them. + /// Removes the sources a move across disks copied, in the order they were noted: each + /// folder after everything in it, so it's empty by the time it's reached. A file that changed + /// since it was copied stays, as does anything that couldn't be checked or removed, and the + /// folders holding them. fn delete_moved(&mut self) { let mut kept: Vec = Vec::new(); for m in std::mem::take(&mut self.to_delete) { @@ -1633,7 +1712,11 @@ impl Run { kept.push(src); } // Gone already, which is what was wanted. - Err(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => { + self.fail_as(&src, &e, Side::Read); + kept.push(src); + } }, Moved::Folder { src, clean } => match fs::remove_dir(&src) { Ok(()) => {} @@ -1666,7 +1749,7 @@ impl Run { if !top.merged { match mode { // A move that left its source behind went only partway, and isn't undone as a whole. - Mode::Move if fs::symlink_metadata(&top.src).is_err() => self.steps.push(Step::Moved { from: top.src, to: stamp }), + Mode::Move if is_gone(&top.src) => self.steps.push(Step::Moved { from: top.src, to: stamp }), Mode::Move => {} Mode::Copy => self.steps.push(Step::Made(stamp)), } @@ -1771,8 +1854,12 @@ impl Run { if let Some(t) = old { self.put_back(t); } - // A move changes both folders, so name the one it can't write in. let into = parent_of(&target); + // Renaming can need room for the name, which is the destination's. + if is_full(&e) { + return self.copy_failed(src, &e, Side::Write(into)); + } + // A move changes both folders, so name the one it can't write in. let side = if rustix::fs::access(into, rustix::fs::Access::WRITE_OK).is_err() { Side::Write(into) } else { Side::Change }; self.fail_as(src, &e, side); return Flow::Go; @@ -2180,6 +2267,12 @@ impl Run { } } +/// Whether nothing is at `path` now. An error other than "not found", as from a folder that +/// can't be read, doesn't say it's gone. +fn is_gone(path: &Path) -> bool { + matches!(fs::symlink_metadata(path), Err(e) if e.kind() == io::ErrorKind::NotFound) +} + /// The folder `path` is in, for saying where something couldn't be written. fn parent_of(path: &Path) -> &Path { path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(path) @@ -4709,47 +4802,80 @@ mod tests { assert_eq!(one(Errno::ROFS, w), "“Backups” is on a read-only drive"); assert_eq!(one(Errno::NAMETOOLONG, w), "The name is too long for “Backups”"); assert_eq!(many(Errno::NAMETOOLONG, w), "The names are too long for “Backups”"); - assert_eq!(one(Errno::IO, w), "The drive couldn't read or write “photo.jpg”. It may be failing or have been unplugged"); + assert_eq!(one(Errno::IO, w), "The drive couldn't read or write it. It may be failing or have been unplugged"); assert_eq!(many(Errno::IO, Side::Read), "The drive couldn't read or write them. It may be failing or have been unplugged"); - assert_eq!(one(Errno::NOENT, Side::Read), "“photo.jpg” is no longer there"); + assert_eq!(one(Errno::NOENT, Side::Read), "It's no longer there"); assert_eq!(many(Errno::NOENT, Side::Read), "They're no longer there"); assert_eq!(one(Errno::NOENT, w), "“Backups” is no longer there", "the folder being written in went"); // Changing an item where it is names its folder. assert_eq!(one(Errno::ACCESS, Side::Change), "You don't have permission to change “Backups”"); - assert_eq!(one(Errno::NOENT, Side::Change), "“photo.jpg” is no longer there"); + assert_eq!(one(Errno::NOENT, Side::Change), "It's no longer there"); // Anything else keeps the system's words. assert_eq!(one(Errno::BUSY, w), "Device or resource busy"); } - fn failure(path: &str, e: Errno, side: Side) -> Failure { - Failure { path: PathBuf::from(path), reason: reason(&errno(e), Path::new(path), side) } + fn told_of(failures: &[(&str, Reason)]) -> Vec { + let mut f = Failures::default(); + for (path, r) in failures { + f.add(Path::new(path), Reason { key: r.key.clone(), one: r.one.clone(), many: r.many.clone() }); + } + f.told() + } + + fn because(path: &str, e: Errno, side: Side) -> Reason { + reason(&errno(e), Path::new(path), side) } #[test] fn one_failure_keeps_its_name_and_repeats_are_counted() { - let one = told(vec![failure("/x/a.txt", Errno::ACCESS, Side::Read)]); - assert_eq!(one, [(PathBuf::from("/x/a.txt"), "You don't have permission to read it".to_string())]); - let mut many: Vec = (0..12).map(|i| failure(&format!("/x/{i}.txt"), Errno::ACCESS, Side::Read)).collect(); - many.insert(3, failure("/x/gone.txt", Errno::NOENT, Side::Read)); - assert_eq!( - told(many), - [(PathBuf::new(), "12 files: You don't have permission to read them".to_string()), (PathBuf::from("/x/gone.txt"), "“gone.txt” is no longer there".to_string())], - "a group is told where its first failure was" - ); - let same_text: Vec = (0..2).map(|i| Failure { path: PathBuf::from(format!("/x/{i}")), reason: Reason::same("Special files like sockets and devices aren't copied".into()) }).collect(); - assert_eq!(told(same_text)[0].1, "2 files: Special files like sockets and devices aren't copied"); + let one = told_of(&[("/x/a.txt", because("/x/a.txt", Errno::ACCESS, Side::Read))]); + assert_eq!(one, [Told { path: "/x/a.txt".into(), message: "You don't have permission to read it".into(), paths: vec!["/x/a.txt".into()], count: 1 }]); + let names: Vec = (0..12).map(|i| format!("/x/{i}.txt")).collect(); + let mut many: Vec<(&str, Reason)> = names.iter().map(|n| (n.as_str(), because(n, Errno::ACCESS, Side::Read))).collect(); + many.insert(3, ("/x/gone.txt", because("/x/gone.txt", Errno::NOENT, Side::Read))); + let told = told_of(&many); + assert_eq!(told.len(), 2, "a group is told where its first failure was"); + assert_eq!((told[0].path.as_os_str(), told[0].message.as_str(), told[0].count), ("".as_ref(), "12 files: You don't have permission to read them", 12)); + // Only the first few names are kept, however many failed. + assert_eq!(told[0].paths, names[..NAMED].iter().map(PathBuf::from).collect::>()); + assert_eq!((told[1].path.as_os_str(), told[1].message.as_str()), ("/x/gone.txt".as_ref(), "It's no longer there")); + let same = Reason::same("Special files like sockets and devices aren't copied".into()); + assert_eq!(told_of(&[("/x/0", Reason::same(same.one.clone())), ("/x/1", same)])[0].message, "2 files: Special files like sockets and devices aren't copied"); assert_eq!(thousands(20000), "20,000"); assert_eq!(thousands(999), "999"); assert_eq!(thousands(1_234_567), "1,234,567"); } + #[test] + fn a_hundred_thousand_failures_keep_five_names() { + let mut f = Failures::default(); + for i in 0..100_000 { + f.add(Path::new(&format!("/x/{i}")), Reason::same("x".into())); + } + assert_eq!(f.groups.len(), 1); + assert_eq!(f.groups[0].paths.len(), NAMED); + assert_eq!(f.told()[0].message, "100,000 files: x"); + } + + #[test] + fn no_space_in_two_folders_with_one_name_is_told_apart() { + let s = Scratch::new(); + let (a, b) = (s.dir("a/Backups"), s.dir("b/Backups")); + let ra = reason(&errno(Errno::NOSPC), &a.join("f"), Side::Write(&a)); + let rb = reason(&errno(Errno::NOSPC), &b.join("f"), Side::Write(&b)); + assert_ne!(ra.key, rb.key); + assert!(ra.one.starts_with("There isn't enough space in “Backups”"), "{}", ra.one); + } + #[test] fn a_folder_among_the_failures_counts_them_as_items() { let s = Scratch::new(); let d = s.dir("d"); let f = s.file("f", b""); - let both = vec![Failure { path: d, reason: Reason::same("x".into()) }, Failure { path: f, reason: Reason::same("x".into()) }]; - assert_eq!(told(both)[0].1, "2 items: x"); + let mut all = Failures::default(); + all.add(&d, Reason::same("x".into())); + all.add(&f, Reason::same("x".into())); + assert_eq!(all.told()[0].message, "2 items: x"); } #[test] @@ -4889,5 +5015,124 @@ mod tests { assert_eq!(done.outcome.undo, None); } + #[test] + fn a_name_already_there_skips_the_check_and_a_full_disk_still_takes_it_back() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + megabytes(&s, "Big Folder", 6); + let disk = small_disk("named"); + fs::create_dir(disk.join("Big Folder")).unwrap(); + fs::write(disk.join("Big Folder/mine.txt"), b"mine").unwrap(); + e.start(Request::Copy { sources: vec![s.path().join("Big Folder")], dest: disk.clone() }); + // Merged, so the check can't tell what it will take, and the copy starts. + let done = finish(&rx, vec![answer(Choice::Replace)]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “Big Folder”: there isn't enough space in “named”. Nothing was copied".to_string())]); + assert_eq!(contents(&disk.join("Big Folder")), ["mine.txt"]); + } + + #[test] + fn a_sparse_file_counts_only_what_it_holds() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + // 8 MiB long, nothing written: the check lets it start, and the copy writes the zeros. + let f = s.path().join("sparse.img"); + File::create(&f).unwrap().set_len(8 << 20).unwrap(); + let disk = small_disk("sparse"); + e.start(Request::Copy { sources: vec![f], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “sparse.img”: there isn't enough space in “sparse”. Nothing was copied".to_string())]); + assert!(contents(&disk).is_empty()); + } + + /// A bind mount shows the same device at another path, as a folder on one disk does, and + /// what's on one device isn't measured: it fills as it goes, and is taken back. + #[test] + fn a_copy_within_one_device_isnt_checked() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + let disk = small_disk("one"); + fs::create_dir(disk.join("src")).unwrap(); + for i in 0..3 { + fs::write(disk.join(format!("src/part{i}.bin")), patterned(1 << 20)).unwrap(); + } + let other = disk.join("other"); + fs::create_dir(&other).unwrap(); + e.start(Request::Copy { sources: vec![disk.join("src")], dest: other.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “src”: there isn't enough space in “other”. Nothing was copied".to_string())]); + assert!(contents(&other).is_empty()); + assert_eq!(contents(&disk.join("src")).len(), 3); + } + + #[test] + fn a_move_that_fills_says_what_was_renamed_on_the_same_drive() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + let disk = small_disk("mixed"); + fs::write(disk.join("here.txt"), b"same drive").unwrap(); + let dest = disk.join("dest"); + fs::create_dir(&dest).unwrap(); + megabytes(&s, "Big", 6); + e.start(Request::Move { sources: vec![disk.join("here.txt"), s.path().join("Big")], dest: dest.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't move 2 items: there isn't enough space in “dest”. 1 on the same drive was moved, and the rest were left where they were".to_string())]); + assert_eq!(contents(&dest), ["here.txt"]); + assert_eq!(contents(&s.path().join("Big")).len(), 6); + let Some(Undo(steps)) = &done.outcome.undo else { panic!("the rename can be undone") }; + assert!(matches!(&steps[..], [Step::Moved { .. }]), "{steps:?}"); + } + + #[test] + fn stopping_a_move_across_disks_takes_it_back() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.force_exdev = true; + // Each file copies in two chunks with a pause between, so the stop lands partway. + e.slow_copy = Some(Duration::from_millis(20)); + let sources: Vec = (0..50) + .map(|i| { + let f = s.path().join(format!("src/f{i:02}")); + fs::create_dir_all(f.parent().unwrap()).unwrap(); + File::create(&f).unwrap().set_len(CHUNK_FOR_TESTS as u64).unwrap(); + f + }) + .collect(); + let d = s.dir("dest"); + let job = e.start(Request::Move { sources: sources.clone(), dest: d.clone() }); + let started = Instant::now(); + while job.progress.done_items.load(Ordering::Relaxed) < 30 { + assert!(started.elapsed() < Duration::from_secs(20), "the move never got to 30"); + std::thread::sleep(Duration::from_millis(1)); + } + job.cancel(); + let done = finish(&rx, vec![]); + assert!(done.outcome.cancelled); + assert!(done.errors.is_empty(), "{:?}", done.errors); + assert_eq!(done.outcome.stopped.as_deref(), Some("Stopped moving 50 items. Nothing was moved")); + assert!(sources.iter().all(|f| f.exists()), "every original is there"); + assert!(contents(&d).is_empty(), "no copy is left: {:?}", contents(&d)); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_source_that_cant_be_checked_after_its_copy_stays() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.force_exdev = true; + e.slow_copy = Some(Duration::from_millis(500)); + let f = s.file("src/d/a", &patterned(CHUNK_FOR_TESTS)); + let d = s.dir("dest"); + e.start(Request::Move { sources: vec![s.path().join("src/d")], dest: d.clone() }); + std::thread::sleep(Duration::from_millis(150)); + // Its folder can't be searched any more, so whether it's still the file copied can't be told. + fs::set_permissions(s.path().join("src/d"), fs::Permissions::from_mode(0o600)).unwrap(); + let done = finish(&rx, vec![]); + fs::set_permissions(s.path().join("src/d"), fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(done.errors, [(f.clone(), "You don't have permission to read it".to_string())]); + assert_eq!(fs::read(&f).unwrap().len(), CHUNK_FOR_TESTS); + assert_eq!(done.outcome.undo, None, "not moved, as the original is still there"); + } + const CHUNK_FOR_TESTS: usize = 8 * 1024 * 1024 + 1; } diff --git a/crates/core/src/space.rs b/crates/core/src/space.rs index d932670..686bfc0 100644 --- a/crates/core/src/space.rs +++ b/crates/core/src/space.rs @@ -43,23 +43,27 @@ fn remote_in(all: &[mounts::Mount], folder: &Path) -> bool { all.iter().any(|m| complete::avoided_fs(&m.fs_type) && m.point != Path::new("/") && folder.starts_with(&m.point)) } -/// What a file of `len` bytes takes on a disk with 4 KiB blocks, which most use. -pub fn on_disk(len: u64) -> u64 { - len.div_ceil(4096).saturating_mul(4096) +/// Whether a check for room in `folder` would give a clear answer: not on a share or FUSE +/// (see [`is_remote`]), and not on btrfs, zfs or bcachefs, which can compress what's written, +/// share blocks between subvolumes of one pool, or dedupe, so the source's size says little +/// about what the copy will take. +pub fn worth_checking(folder: &Path) -> bool { + worth_checking_in(&mounts::read_mounts(), folder) +} + +fn worth_checking_in(all: &[mounts::Mount], folder: &Path) -> bool { + if remote_in(all, folder) { + return false; + } + let point = mounts::mount_point_of(all, folder); + let fs_type = all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).map(|m| m.fs_type.as_str()); + !matches!(fs_type, Some("btrfs" | "zfs" | "bcachefs")) } #[cfg(test)] mod tests { use super::*; - #[test] - fn a_file_takes_whole_blocks() { - assert_eq!(on_disk(0), 0); - assert_eq!(on_disk(1), 4096); - assert_eq!(on_disk(4096), 4096); - assert_eq!(on_disk(4097), 8192); - } - #[test] fn free_space_is_never_more_than_the_disk_has() { let s = crate::testutil::Scratch::new(); @@ -73,7 +77,7 @@ mod tests { // scripts/sandbox-run.sh mounts these, 4 MiB each. let free = free(Path::new(SMALL)).unwrap(); assert!(free <= 4 << 20 && free > 0, "{free}"); - assert!(!is_remote(Path::new(SMALL))); + assert!(!is_remote(Path::new(SMALL)) && worth_checking(Path::new(SMALL))); } #[test] @@ -88,5 +92,16 @@ mod tests { assert!(remote_in(&all, Path::new("/net/host"))); } + #[test] + fn copy_on_write_disks_are_never_checked() { + let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "ext4"), m("/home", "btrfs"), m("/tank", "zfs"), m("/pool", "bcachefs"), m("/tmp", "tmpfs"), m("/mnt/nas", "nfs4")]; + assert!(worth_checking_in(&all, Path::new("/srv"))); + assert!(worth_checking_in(&all, Path::new("/tmp/x"))); + for no in ["/home/me", "/tank/a", "/pool", "/mnt/nas/a"] { + assert!(!worth_checking_in(&all, Path::new(no)), "{no}"); + } + } + const SMALL: &str = "/run/gannet-small/space"; } diff --git a/scripts/sandbox-run.sh b/scripts/sandbox-run.sh index 9d075e4..bc09ce1 100755 --- a/scripts/sandbox-run.sh +++ b/scripts/sandbox-run.sh @@ -40,7 +40,7 @@ mapfile -d '' hide < "$SCRATCH/hide" # Tiny disks of their own, for tests of a destination that fills up. One for each such test, # as tests run side by side. They're under /run, which the covers leave alone. small=() -for name in space refuse fill merge move; do small+=(--size 4194304 --tmpfs "/run/gannet-small/$name"); done +for name in space refuse fill merge move mixed named sparse one; do small+=(--size 4194304 --tmpfs "/run/gannet-small/$name"); done bwrap --die-with-parent --unshare-pid --unshare-net --ro-bind / / --dev /dev --proc /proc --tmpfs /run --tmpfs /run/gannet-tree/mnt --tmpfs "$HOME" \ "${small[@]}" \ --bind "$SCRATCH/home" "$SCRATCH/home" --bind "$SCRATCH/tmp" /tmp \ From eacfd002413ea0e71b22deaeee55620ab6af9966 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 23:31:13 -0700 Subject: [PATCH 4/7] ALI-2600: Review round 2: moves off shares, same-disk merges, mounts inside a move - Removing the sources of a move: on a share or FUSE mount, where inode numbers can change between looks (mounts::inodes_may_change), a file is known by its size and time alone, so moving a folder off SMB or sshfs doesn't keep every original. - A stopped or full move takes back only what it copied. A merge on one disk that was stopped keeps what it renamed, removes the folders it emptied, and isn't "Nothing was moved". The count of what moved on the same drive is of items renamed, including inside merges, and the folders merged into stay selected. - The check for room asks space::worth_checking before looking for names in the destination, so nothing on a share is looked up. - space::is_remote and worth_checking follow the destination one part at a time against the mount table (complete::resolve), so a link to a share counts as the share and nothing on it is touched. - A move or delete doesn't count what's on a disk mounted inside the folder, which it leaves where it is. - A stop that comes once every copy has arrived and the originals are being removed finishes the move, which isn't reported as stopped. --- crates/core/src/ops.rs | 171 +++++++++++++++++++++++++++++++++------ crates/core/src/space.rs | 63 ++++++++++++--- scripts/sandbox-run.sh | 4 +- 3 files changed, 201 insertions(+), 37 deletions(-) diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index a4b9684..c6e6ee6 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -333,6 +333,10 @@ impl Engine { made: Vec::new(), inside_new: false, to_delete: Vec::new(), + renamed: 0, + loose_inodes: false, + mount_table: None, + finished_anyway: false, steps: Vec::new(), trashed: Vec::new(), mounts: MountCache::default(), @@ -353,7 +357,7 @@ impl Engine { let steps = std::mem::take(&mut run.steps); let outcome = Outcome { job: run.job.id, - cancelled: run.job.is_cancelled(), + cancelled: run.job.is_cancelled() && !run.finished_anyway, errors: run.errors, skipped: run.noted_leftovers, undo: (!steps.is_empty()).then_some(Undo(steps)), @@ -702,10 +706,38 @@ enum Made { Replaced(Trashed), } +/// What a source was when it was copied, to tell whether it has changed since. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Seen { + ino: u64, + len: u64, + mtime: (i64, i64), +} + +impl Seen { + fn of(m: &Metadata) -> Seen { + Seen { ino: m.ino(), len: m.len(), mtime: (m.mtime(), m.mtime_nsec()) } + } + + /// Whether `now` is still the file as it was. On a share or FUSE (`loose`) the inode number + /// can change between looks, so only the size and time say. + fn unchanged(&self, now: &Seen, loose: bool) -> bool { + (loose || self.ino == now.ino) && self.len == now.len && self.mtime == now.mtime + } +} + +/// Whether the filesystem `path` is on, as the mount table has it, can give a file another +/// inode number from one look to the next. +fn inodes_may_change_in(all: &[crate::mounts::Mount], path: &Path) -> bool { + let point = crate::mounts::mount_point_of(all, path); + all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).is_some_and(|m| crate::mounts::inodes_may_change(&m.fs_type)) +} + /// A source a move across disks has copied, removed once everything has been. enum Moved { - /// With what it was when it was copied, so a file changed since is kept. - File { src: PathBuf, ino: u64, len: u64, mtime: (i64, i64) }, + /// With what it was when it was copied, so a file changed since is kept. `loose` if it's + /// on a share or FUSE, whose inode numbers can change from one look to the next. + File { src: PathBuf, was: Seen, loose: bool }, /// Removed once empty. `clean` if nothing in it failed or was left on purpose. Folder { src: PathBuf, clean: bool }, } @@ -755,6 +787,14 @@ struct Run { inside_new: bool, /// What a move across disks has copied, for removing once it all has. to_delete: Vec, + /// Items this move renamed on their own disk, which a full disk or a stop doesn't take back. + renamed: usize, + /// Whether the top-level item being moved is on a share or FUSE. See [`Seen::unchanged`]. + loose_inodes: bool, + /// The mount table, read once a move needs it. + mount_table: Option>, + /// A stop came once every copy had arrived, so the move was finished. + finished_anyway: bool, skip_space_check: bool, /// What this job changed, for its undo. steps: Vec, @@ -775,7 +815,7 @@ impl Run { fn execute(&mut self, request: Request) { match request { Request::Copy { sources, dest } => { - let (need, away) = self.measure(&sources, &dest); + let (need, away) = self.measure(&sources, &dest, Mode::Copy); if self.room_for(&away, &dest, need) { self.place_all(&sources, &dest, Mode::Copy); } @@ -785,7 +825,7 @@ impl Run { // What goes to another disk is copied, so it's measured first, as a copy is. let dest_dev = fs::metadata(&dest).map(|m| m.dev()).ok(); let copied: Vec = sources.iter().filter(|s| self.force_exdev || fs::symlink_metadata(s).is_ok_and(|m| Some(m.dev()) != dest_dev)).cloned().collect(); - let (need, away) = self.measure(&copied, &dest); + let (need, away) = self.measure(&copied, &dest, Mode::Move); self.measured = copied.into_iter().collect(); if self.room_for(&away, &dest, need) { self.place_all(&sources, &dest, Mode::Move); @@ -797,7 +837,7 @@ impl Run { } Request::Trash { paths } => self.trash_all(paths), Request::Delete { paths } => { - self.scan(&paths); + self.scan(&paths, true); for p in &paths { if self.job.is_cancelled() { break; @@ -997,7 +1037,7 @@ impl Run { let Some(place) = zip_place(&items).map(|p| through_links(p, &items)) else { return }; self.touched.push(place.folder.clone()); let full: Vec = place.names.iter().map(|n| place.folder.join(n)).collect(); - self.scan(&full); + self.scan(&full, false); if self.job.is_cancelled() { return; } @@ -1464,13 +1504,14 @@ impl Run { /// only what it holds. Sources on the same device as `dest` aren't counted. A copy there /// shares blocks only on a filesystem with reflinks, but a disk that fills is caught as the /// copy goes, and the copy is taken back. - fn measure(&mut self, sources: &[PathBuf], dest: &Path) -> (u64, Vec) { + fn measure(&mut self, sources: &[PathBuf], dest: &Path, mode: Mode) -> (u64, Vec) { let dest_dev = fs::metadata(dest).map(|m| m.dev()).ok(); let mut need = 0; let mut away = Vec::new(); for src in sources { let before = self.need; - self.scan(std::slice::from_ref(src)); + // A move leaves a disk mounted inside a folder where it is, so it isn't counted. + self.scan(std::slice::from_ref(src), mode == Mode::Move); if fs::symlink_metadata(src).is_ok_and(|m| Some(m.dev()) != dest_dev) { need += self.need - before; away.push(src.clone()); @@ -1490,7 +1531,8 @@ impl Run { if need == 0 || self.skip_space_check || self.job.is_cancelled() { return true; } - if away.iter().any(|s| s.file_name().is_some_and(|n| fs::symlink_metadata(dest.join(n)).is_ok())) || !space::worth_checking(dest) { + // In this order, so nothing on a share is looked up. + if !space::worth_checking(dest) || away.iter().any(|s| s.file_name().is_some_and(|n| fs::symlink_metadata(dest.join(n)).is_ok())) { return true; } let Some(free) = space::free(dest) else { return true }; @@ -1506,22 +1548,29 @@ impl Run { } /// Adds up the bytes and items so progress has totals. - fn scan(&mut self, paths: &[PathBuf]) { + /// With `stop_at_mounts`, as for a move or a delete, which leave another disk mounted inside + /// a folder alone, what's on it isn't counted either. + fn scan(&mut self, paths: &[PathBuf], stop_at_mounts: bool) { let progress = self.job.progress.clone(); progress.scanning.store(true, Ordering::Relaxed); - let mut stack: Vec = paths.to_vec(); - while let Some(p) = stack.pop() { + // Each with the device of the item it's inside, given, or None for one given. + let mut stack: Vec<(PathBuf, Option)> = paths.iter().map(|p| (p.clone(), None)).collect(); + while let Some((p, top)) = stack.pop() { if self.job.is_cancelled() { break; } let Ok(m) = fs::symlink_metadata(&p) else { continue }; + let top = top.unwrap_or(m.dev()); + if stop_at_mounts && m.is_dir() && is_mount_boundary(&p, &m, top) { + continue; + } progress.total_items.fetch_add(1, Ordering::Relaxed); // A folder others can see into but not enter keeps what's in it from them too. let open_to_others = if m.is_dir() { 0o005 } else { 0o004 }; self.private_seen |= !m.is_symlink() && m.mode() & open_to_others != open_to_others; if m.is_dir() { if let Ok(rd) = fs::read_dir(&p) { - stack.extend(rd.flatten().map(|e| e.path())); + stack.extend(rd.flatten().map(|e| (e.path(), Some(top)))); } } else { progress.total_bytes.fetch_add(m.len(), Ordering::Relaxed); @@ -1626,6 +1675,14 @@ impl Run { self.settle(tops, sources, dest, mode); } + /// Whether `src` is on a share or FUSE, whose inode numbers can change. Its folder is + /// resolved for the mount table; the item itself isn't followed. + fn inodes_may_change_at(&mut self, src: &Path) -> bool { + let real = src.parent().and_then(|d| fs::canonicalize(d).ok()).map(|d| src.file_name().map_or(d.clone(), |n| d.join(n))); + let table = self.mount_table.get_or_insert_with(crate::mounts::read_mounts); + real.is_some_and(|r| inodes_may_change_in(table, &r)) + } + /// What `place` noted about the top-level item it just placed. fn top(&mut self, src: &Path) -> Top { Top { src: src.to_path_buf(), target: self.last_target.take(), merged: std::mem::take(&mut self.last_merged), replaced: self.last_replaced.take() } @@ -1638,10 +1695,17 @@ impl Run { let full = std::mem::take(&mut self.full); // A move stopped partway across disks is taken back too, so nothing is half moved: // no original goes until all of it has arrived. - let stopped = mode == Mode::Move && self.job.is_cancelled() && !(self.made.is_empty() && self.to_delete.is_empty()); + // Only copies are taken back: what was renamed on its own disk is where it was asked to go. + let copied = !self.made.is_empty() || self.to_delete.iter().any(|m| matches!(m, Moved::File { .. })); + let stopped = mode == Mode::Move && self.job.is_cancelled() && copied; if !full && !stopped { self.made.clear(); + let cancelled_before = self.job.is_cancelled(); self.delete_moved(); + // A stop that came while the originals were being removed is too late: every copy + // had arrived, so the move is finished rather than left half done. + self.finished_anyway = !cancelled_before && self.job.is_cancelled(); + self.renamed = 0; for top in tops { self.record_top_level(top, mode); } @@ -1649,14 +1713,13 @@ impl Run { } self.undo_made(); self.to_delete.clear(); - // Renamed on the same disk, so they took no room and have gone where they were asked to. - let mut moved = 0; + // Renamed on the same disk, so they took no room. They keep their undo and are selected. for top in tops { - if mode == Mode::Move && is_gone(&top.src) { + if mode == Mode::Move && (is_gone(&top.src) || top.merged) { self.record_top_level(top, mode); - moved += 1; } } + let moved = std::mem::take(&mut self.renamed); let what = match sources { [one] => quoted(one), many => format!("{} items", thousands(many.len())), @@ -1700,8 +1763,8 @@ impl Run { let mut kept: Vec = Vec::new(); for m in std::mem::take(&mut self.to_delete) { match m { - Moved::File { src, ino, len, mtime } => match fs::symlink_metadata(&src) { - Ok(now) if now.ino() == ino && now.len() == len && (now.mtime(), now.mtime_nsec()) == mtime => { + Moved::File { src, was, loose } => match fs::symlink_metadata(&src) { + Ok(now) if was.unchanged(&Seen::of(&now), loose) => { if let Err(e) = fs::remove_file(&src) { self.fail(&src, &e); kept.push(src); @@ -1772,6 +1835,9 @@ impl Run { }; if self.depth == 0 { self.top_dev = smeta.dev(); + if mode == Mode::Move { + self.loose_inodes = self.inodes_may_change_at(src); + } } else if mode == Mode::Move && smeta.is_dir() && is_mount_boundary(src, &smeta, self.top_dev) { self.report(src, "This is a mount point, so it was left where it is".into()); return Flow::Go; @@ -1836,6 +1902,7 @@ impl Run { if let Some(t) = old { self.kept_replaced(t); } + self.renamed += 1; self.job.progress.done_bytes.fetch_add(if smeta.is_dir() { 0 } else { smeta.len() }, Ordering::Relaxed); return Flow::Go; } @@ -1847,7 +1914,7 @@ impl Run { // Across disks: copy then remove, measuring what's about to move. The // top item's scan covers everything below it. if self.depth == 0 && !self.measured.contains(src) { - self.scan(&[src.to_path_buf()]); + self.scan(&[src.to_path_buf()], true); } } Err(e) => { @@ -1866,7 +1933,7 @@ impl Run { } } } else if mode == Mode::Move && !merge && self.depth == 0 && !self.measured.contains(src) { - self.scan(&[src.to_path_buf()]); + self.scan(&[src.to_path_buf()], true); } let ft = smeta.file_type(); if ft.is_dir() { @@ -2086,7 +2153,7 @@ impl Run { self.report(src, format!("Copied, but couldn't confirm it reached the disk, so the original stays: {}", describe(&e))); return Flow::Go; } - self.to_delete.push(Moved::File { src: src.to_path_buf(), ino: smeta.ino(), len: smeta.len(), mtime: (smeta.mtime(), smeta.mtime_nsec()) }); + self.to_delete.push(Moved::File { src: src.to_path_buf(), was: Seen::of(smeta), loose: self.loose_inodes }); } else { self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); } @@ -5134,5 +5201,61 @@ mod tests { assert_eq!(done.outcome.undo, None, "not moved, as the original is still there"); } + #[test] + fn a_file_on_a_share_is_known_by_its_size_and_time_not_its_inode() { + let was = Seen { ino: 10, len: 5, mtime: (100, 7) }; + let renumbered = Seen { ino: 99, ..was }; + assert!(!was.unchanged(&renumbered, false), "on a local disk a new inode is another file"); + assert!(was.unchanged(&renumbered, true), "on a share the number can change by itself"); + assert!(!was.unchanged(&Seen { len: 6, ..renumbered }, true)); + assert!(!was.unchanged(&Seen { mtime: (101, 7), ..was }, true)); + let m = |point: &str, fs_type: &str| crate::mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "ext4"), m("/mnt/nas", "cifs"), m("/home/me/remote", "fuse.sshfs"), m("/run/media/me/USB", "fuseblk"), m("/srv", "nfs4")]; + for loose in ["/mnt/nas/a", "/home/me/remote/b", "/run/media/me/USB/c", "/srv/d"] { + assert!(inodes_may_change_in(&all, Path::new(loose)), "{loose}"); + } + assert!(!inodes_may_change_in(&all, Path::new("/home/me/e"))); + } + + #[test] + fn stopping_a_merge_on_one_disk_keeps_what_it_renamed() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + // Made in this order, which the scratch disk lists them in, so sub is merged before c asks. + s.file("src/d/sub/b", b"b"); + s.file("src/d/c", b"new c"); + let names: Vec<_> = fs::read_dir(s.path().join("src/d")).unwrap().flatten().map(|e| e.file_name()).collect(); + assert_eq!(names, ["sub", "c"], "this test needs a disk that lists names in the order they were made"); + s.file("dest/d/sub/old", b"old"); + s.file("dest/d/c", b"old c"); + e.start(Request::Move { sources: vec![s.path().join("src/d")], dest: s.path().join("dest") }); + // Merge d, merge sub, then stop at c. + let done = finish(&rx, vec![answer(Choice::Replace), answer(Choice::Replace), answer(Choice::Cancel)]); + assert!(done.outcome.cancelled); + assert_eq!(done.outcome.stopped, None, "something was moved, so it isn't \"Nothing was moved\""); + assert_eq!(fs::read(s.path().join("dest/d/sub/b")).unwrap(), b"b"); + assert!(!s.path().join("src/d/sub").exists(), "the emptied folder went"); + assert_eq!(fs::read(s.path().join("src/d/c")).unwrap(), b"new c"); + assert_eq!(fs::read(s.path().join("dest/d/c")).unwrap(), b"old c"); + assert_eq!(done.outcome.created, [s.path().join("dest/d")], "the folder merged into is selected"); + } + + #[test] + fn a_move_doesnt_count_a_disk_mounted_inside_it() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + // scripts/sandbox-run.sh mounts an 8 MiB disk at tree/mnt, inside a 4 MiB one. + let tree = Path::new("/run/gannet-small/nest/tree"); + fs::write(tree.join("a.bin"), patterned(1 << 20)).unwrap(); + fs::write(tree.join("mnt/big.bin"), patterned(5 << 20)).unwrap(); + let dest = small_disk("nestdest"); + e.start(Request::Move { sources: vec![tree.to_path_buf()], dest: dest.clone() }); + let done = finish(&rx, vec![]); + // Counting the 5 MiB on the other disk would refuse it; that disk stays where it is. + assert_eq!(done.errors, [(tree.join("mnt"), "This is a mount point, so it was left where it is".to_string())]); + assert_eq!(fs::read(dest.join("tree/a.bin")).unwrap().len(), 1 << 20); + assert_eq!(fs::metadata(tree.join("mnt/big.bin")).unwrap().len(), 5 << 20); + } + const CHUNK_FOR_TESTS: usize = 8 * 1024 * 1024 + 1; } diff --git a/crates/core/src/space.rs b/crates/core/src/space.rs index 686bfc0..6de3263 100644 --- a/crates/core/src/space.rs +++ b/crates/core/src/space.rs @@ -2,7 +2,7 @@ use std::fs::File; use std::os::fd::AsRawFd; -use std::path::Path; +use std::path::{Path, PathBuf}; use crate::{complete, mounts}; @@ -34,9 +34,20 @@ fn quota_left(f: &File) -> Option { /// Whether `folder` is on, or inside, a network share, autofs or FUSE mount, where asking for /// free space is a round trip that can hang. The same mounts the path bar's completion keeps /// out of ([`complete::avoided_fs`]): a FUSE drive on a local disk (`fuseblk`, as ntfs-3g) is -/// asked, and so is `/`, even as a container's fuse-overlayfs root. +/// asked, and so is `/`, even as a container's fuse-overlayfs root. The path is followed one +/// part at a time against the mount table first ([`complete::resolve`]), so a link to a share +/// counts as the share, and nothing on a share is looked up to find out. A folder that can't be +/// followed there counts as remote: it's left alone. pub fn is_remote(folder: &Path) -> bool { - remote_in(&mounts::read_mounts(), folder) + real_place(&mounts::read_mounts(), folder, &complete::Disk).is_none() +} + +/// Where `folder` really is, if it's a folder that can be reached without going into a share. +fn real_place(all: &[mounts::Mount], folder: &Path, look: &impl complete::Look) -> Option { + match complete::resolve(folder, all, look)? { + (real, complete::Kind::Folder) if !remote_in(all, &real) => Some(real), + _ => None, + } } fn remote_in(all: &[mounts::Mount], folder: &Path) -> bool { @@ -48,14 +59,12 @@ fn remote_in(all: &[mounts::Mount], folder: &Path) -> bool { /// share blocks between subvolumes of one pool, or dedupe, so the source's size says little /// about what the copy will take. pub fn worth_checking(folder: &Path) -> bool { - worth_checking_in(&mounts::read_mounts(), folder) + worth_checking_in(&mounts::read_mounts(), folder, &complete::Disk) } -fn worth_checking_in(all: &[mounts::Mount], folder: &Path) -> bool { - if remote_in(all, folder) { - return false; - } - let point = mounts::mount_point_of(all, folder); +fn worth_checking_in(all: &[mounts::Mount], folder: &Path, look: &impl complete::Look) -> bool { + let Some(real) = real_place(all, folder, look) else { return false }; + let point = mounts::mount_point_of(all, &real); let fs_type = all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).map(|m| m.fs_type.as_str()); !matches!(fs_type, Some("btrfs" | "zfs" | "bcachefs")) } @@ -80,6 +89,34 @@ mod tests { assert!(!is_remote(Path::new(SMALL)) && worth_checking(Path::new(SMALL))); } + /// A disk of folders, with these links, that says if anything inside a share is looked up. + struct Fake(Vec<(&'static str, &'static str)>, &'static [&'static str]); + + impl complete::Look for Fake { + fn kind(&self, p: &Path) -> Option { + assert!(!self.1.iter().any(|s| p.starts_with(s)), "looked inside a share: {p:?}"); + Some(if self.0.iter().any(|(l, _)| p == Path::new(l)) { complete::Kind::Link } else { complete::Kind::Folder }) + } + fn read_link(&self, p: &Path) -> Option { + self.0.iter().find(|(l, _)| p == Path::new(l)).map(|(_, t)| PathBuf::from(t)) + } + fn entries(&self, _: &Path, _: &dyn Fn(&Path) -> bool) -> Option)>> { + None + } + } + + #[test] + fn a_link_to_a_share_counts_as_the_share() { + let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "ext4"), m("/mnt/nas", "cifs"), m("/home", "btrfs"), m("/srv", "ext4")]; + let look = Fake(vec![("/srv/nas", "/mnt/nas"), ("/srv/backups", "/mnt/nas/backups"), ("/srv/home", "/home/me")], &["/mnt/nas"]); + assert!(real_place(&all, Path::new("/srv/nas/photos"), &look).is_none()); + assert!(!worth_checking_in(&all, Path::new("/srv/backups"), &look)); + assert!(!worth_checking_in(&all, Path::new("/srv/home/x"), &look), "a link onto btrfs is btrfs"); + assert!(worth_checking_in(&all, Path::new("/srv/data"), &look)); + assert_eq!(real_place(&all, Path::new("/srv/data"), &look), Some(PathBuf::from("/srv/data"))); + } + #[test] fn shares_and_fuse_are_never_asked_but_local_disks_are() { let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; @@ -96,10 +133,12 @@ mod tests { fn copy_on_write_disks_are_never_checked() { let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; let all = [m("/", "ext4"), m("/home", "btrfs"), m("/tank", "zfs"), m("/pool", "bcachefs"), m("/tmp", "tmpfs"), m("/mnt/nas", "nfs4")]; - assert!(worth_checking_in(&all, Path::new("/srv"))); - assert!(worth_checking_in(&all, Path::new("/tmp/x"))); + let ok = Fake(vec![], &[]); + assert!(worth_checking_in(&all, Path::new("/srv"), &ok)); + assert!(worth_checking_in(&all, Path::new("/tmp/x"), &ok)); + let look = Fake(vec![], &["/mnt/nas"]); for no in ["/home/me", "/tank/a", "/pool", "/mnt/nas/a"] { - assert!(!worth_checking_in(&all, Path::new(no)), "{no}"); + assert!(!worth_checking_in(&all, Path::new(no), &look), "{no}"); } } diff --git a/scripts/sandbox-run.sh b/scripts/sandbox-run.sh index bc09ce1..b2e7ead 100755 --- a/scripts/sandbox-run.sh +++ b/scripts/sandbox-run.sh @@ -40,7 +40,9 @@ mapfile -d '' hide < "$SCRATCH/hide" # Tiny disks of their own, for tests of a destination that fills up. One for each such test, # as tests run side by side. They're under /run, which the covers leave alone. small=() -for name in space refuse fill merge move mixed named sparse one; do small+=(--size 4194304 --tmpfs "/run/gannet-small/$name"); done +for name in space refuse fill merge move mixed named sparse one nest nestdest; do small+=(--size 4194304 --tmpfs "/run/gannet-small/$name"); done +# And a bigger disk mounted inside one of them, for a move that must leave it alone. +small+=(--size 8388608 --tmpfs /run/gannet-small/nest/tree/mnt) bwrap --die-with-parent --unshare-pid --unshare-net --ro-bind / / --dev /dev --proc /proc --tmpfs /run --tmpfs /run/gannet-tree/mnt --tmpfs "$HOME" \ "${small[@]}" \ --bind "$SCRATCH/home" "$SCRATCH/home" --bind "$SCRATCH/tmp" /tmp \ From b51bfa6b4f0fb0186e640fc264657190b1b258d9 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 23:45:34 -0700 Subject: [PATCH 5/7] ALI-2600: Review round 3: safer checks on shares, top-level counts, progress while removing - A source on a share whose inode numbers change between looks is now told apart by its size, its modification time and, where the share keeps one, its change time. One changed within 2 s of being copied or of the job starting is kept, as a change that close can leave the times the same. - Which mounts count as such shares is mounts::inodes_renumbered: network filesystems and network FUSE (sshfs, gvfsd-fuse, rclone and the like), not fuseblk, exFAT or other local FUSE, whose inode numbers are stable. It's worked out only once a top-level item is copied, not for renames. - "N on the same drive were moved" counts top-level items only. - Removing a move's sources counts in its progress, so the bar doesn't sit at the end meanwhile. - A file counts toward the room it needs as the smaller of its allocated blocks and its size rounded up to 4 KiB, so neither a sparse file nor one with reserved space is over-counted. --- crates/core/src/mounts.rs | 9 +++ crates/core/src/ops.rs | 143 +++++++++++++++++++++++++++++--------- 2 files changed, 118 insertions(+), 34 deletions(-) diff --git a/crates/core/src/mounts.rs b/crates/core/src/mounts.rs index da16f85..419fdbd 100644 --- a/crates/core/src/mounts.rs +++ b/crates/core/src/mounts.rs @@ -59,6 +59,15 @@ pub fn inodes_may_change(fs_type: &str) -> bool { ["nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "glusterfs", "davfs"].contains(&fs_type) || fs_type.starts_with("fuse") } +/// Whether a filesystem of this kind really gives a file another inode number from one look to +/// the next: a network share, or FUSE over a network. Narrower than [`inodes_may_change`], +/// which is for telling a folder apart and so also takes in any FUSE: a local FUSE drive, as +/// ntfs-3g (`fuseblk`) or exFAT, keeps its numbers. +pub fn inodes_renumbered(fs_type: &str) -> bool { + const NETWORK: [&str; 15] = ["nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "glusterfs", "davfs", "sshfs", "fuse.sshfs", "fuse.gvfsd-fuse", "fuse.rclone", "fuse.s3fs", "fuse.curlftpfs"]; + NETWORK.contains(&fs_type) +} + /// The mount point holding `path`, which should already be canonical. pub fn mount_point_of(mounts: &[Mount], path: &Path) -> Option { mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).map(|m| m.point.clone()) diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index c6e6ee6..dd5d08f 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -334,7 +334,9 @@ impl Engine { inside_new: false, to_delete: Vec::new(), renamed: 0, - loose_inodes: false, + loose_inodes: None, + moving_top: None, + started: std::time::SystemTime::now(), mount_table: None, finished_anyway: false, steps: Vec::new(), @@ -712,32 +714,47 @@ struct Seen { ino: u64, len: u64, mtime: (i64, i64), + /// 0 where the filesystem doesn't say. + ctime: (i64, i64), } +/// How close to a moment a file's time can be and still be taken as from before it. Coarse +/// clocks on shares (FAT and SMB keep 2 s) can't tell apart changes nearer than that. +const TICK: i64 = 2; + impl Seen { fn of(m: &Metadata) -> Seen { - Seen { ino: m.ino(), len: m.len(), mtime: (m.mtime(), m.mtime_nsec()) } + Seen { ino: m.ino(), len: m.len(), mtime: (m.mtime(), m.mtime_nsec()), ctime: (m.ctime(), m.ctime_nsec()) } } - /// Whether `now` is still the file as it was. On a share or FUSE (`loose`) the inode number - /// can change between looks, so only the size and time say. - fn unchanged(&self, now: &Seen, loose: bool) -> bool { - (loose || self.ino == now.ino) && self.len == now.len && self.mtime == now.mtime + /// Whether `now` is still the file as it was when it was seen at `seen_at`, in a job that + /// started at `started` (seconds since the epoch). On a share whose inode numbers change + /// between looks (`loose`), the number can't say, so the size, the times, and the change + /// time where the filesystem keeps one have to. A change within one tick of the time could + /// leave them all the same, so a file changed that recently is taken as changed, which + /// keeps the original. + fn unchanged(&self, now: &Seen, loose: bool, seen_at: i64, started: i64) -> bool { + if !loose { + return self.ino == now.ino && self.len == now.len && self.mtime == now.mtime; + } + let near = |t: i64| (now.mtime.0 - t).abs() < TICK; + let ctime_same = self.ctime == (0, 0) || now.ctime == (0, 0) || self.ctime == now.ctime; + self.len == now.len && self.mtime == now.mtime && ctime_same && !near(seen_at) && !near(started) } } -/// Whether the filesystem `path` is on, as the mount table has it, can give a file another -/// inode number from one look to the next. +/// Whether the filesystem `path` is on, as the mount table has it, gives a file another inode +/// number from one look to the next. See [`crate::mounts::inodes_renumbered`]. fn inodes_may_change_in(all: &[crate::mounts::Mount], path: &Path) -> bool { let point = crate::mounts::mount_point_of(all, path); - all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).is_some_and(|m| crate::mounts::inodes_may_change(&m.fs_type)) + all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).is_some_and(|m| crate::mounts::inodes_renumbered(&m.fs_type)) } /// A source a move across disks has copied, removed once everything has been. enum Moved { - /// With what it was when it was copied, so a file changed since is kept. `loose` if it's - /// on a share or FUSE, whose inode numbers can change from one look to the next. - File { src: PathBuf, was: Seen, loose: bool }, + /// With what it was when it was copied, and when, so a file changed since is kept. `loose` + /// if it's on a share whose inode numbers can change from one look to the next. + File { src: PathBuf, was: Seen, seen_at: i64, loose: bool }, /// Removed once empty. `clean` if nothing in it failed or was left on purpose. Folder { src: PathBuf, clean: bool }, } @@ -787,10 +804,15 @@ struct Run { inside_new: bool, /// What a move across disks has copied, for removing once it all has. to_delete: Vec, - /// Items this move renamed on their own disk, which a full disk or a stop doesn't take back. + /// Top-level items this move renamed on their own disk, which a full disk or a stop doesn't + /// take back. renamed: usize, - /// Whether the top-level item being moved is on a share or FUSE. See [`Seen::unchanged`]. - loose_inodes: bool, + /// Whether the top-level item being moved, `moving_top`, is on a share whose inode numbers + /// can change. See [`Seen::unchanged`]. + loose_inodes: Option, + moving_top: Option, + /// When the job started, as the clock has it, for telling a source changed during it. + started: std::time::SystemTime, /// The mount table, read once a move needs it. mount_table: Option>, /// A stop came once every copy had arrived, so the move was finished. @@ -1574,7 +1596,9 @@ impl Run { } } else { progress.total_bytes.fetch_add(m.len(), Ordering::Relaxed); - self.need += m.blocks() * 512; + // Allocated blocks count only what a sparse file holds, and the size rounded up + // to whole blocks leaves out space a file has reserved but not used. + self.need += (m.blocks() * 512).min(m.len().div_ceil(4096) * 4096); } self.tick(); } @@ -1675,7 +1699,7 @@ impl Run { self.settle(tops, sources, dest, mode); } - /// Whether `src` is on a share or FUSE, whose inode numbers can change. Its folder is + /// Whether `src` is on a share whose inode numbers can change. Its folder is /// resolved for the mount table; the item itself isn't followed. fn inodes_may_change_at(&mut self, src: &Path) -> bool { let real = src.parent().and_then(|d| fs::canonicalize(d).ok()).map(|d| src.file_name().map_or(d.clone(), |n| d.join(n))); @@ -1697,10 +1721,10 @@ impl Run { // no original goes until all of it has arrived. // Only copies are taken back: what was renamed on its own disk is where it was asked to go. let copied = !self.made.is_empty() || self.to_delete.iter().any(|m| matches!(m, Moved::File { .. })); - let stopped = mode == Mode::Move && self.job.is_cancelled() && copied; + let cancelled_before = self.job.is_cancelled(); + let stopped = mode == Mode::Move && cancelled_before && copied; if !full && !stopped { self.made.clear(); - let cancelled_before = self.job.is_cancelled(); self.delete_moved(); // A stop that came while the originals were being removed is too late: every copy // had arrived, so the move is finished rather than left half done. @@ -1761,10 +1785,17 @@ impl Run { /// folders holding them. fn delete_moved(&mut self) { let mut kept: Vec = Vec::new(); - for m in std::mem::take(&mut self.to_delete) { + let started = epoch_secs(self.started); + let pending = std::mem::take(&mut self.to_delete); + // Removing them is part of the move, so the bar goes on until they're gone. + let progress = self.job.progress.clone(); + progress.total_items.fetch_add(pending.len() as u64, Ordering::Relaxed); + for m in pending { + progress.done_items.fetch_add(1, Ordering::Relaxed); + self.tick(); match m { - Moved::File { src, was, loose } => match fs::symlink_metadata(&src) { - Ok(now) if was.unchanged(&Seen::of(&now), loose) => { + Moved::File { src, was, seen_at, loose } => match fs::symlink_metadata(&src) { + Ok(now) if was.unchanged(&Seen::of(&now), loose, seen_at, started) => { if let Err(e) = fs::remove_file(&src) { self.fail(&src, &e); kept.push(src); @@ -1836,7 +1867,9 @@ impl Run { if self.depth == 0 { self.top_dev = smeta.dev(); if mode == Mode::Move { - self.loose_inodes = self.inodes_may_change_at(src); + // Worked out only once something of it is copied: a rename doesn't need it. + self.loose_inodes = None; + self.moving_top = Some(src.to_path_buf()); } } else if mode == Mode::Move && smeta.is_dir() && is_mount_boundary(src, &smeta, self.top_dev) { self.report(src, "This is a mount point, so it was left where it is".into()); @@ -1902,7 +1935,7 @@ impl Run { if let Some(t) = old { self.kept_replaced(t); } - self.renamed += 1; + self.renamed += usize::from(self.depth == 0); self.job.progress.done_bytes.fetch_add(if smeta.is_dir() { 0 } else { smeta.len() }, Ordering::Relaxed); return Flow::Go; } @@ -2153,7 +2186,15 @@ impl Run { self.report(src, format!("Copied, but couldn't confirm it reached the disk, so the original stays: {}", describe(&e))); return Flow::Go; } - self.to_delete.push(Moved::File { src: src.to_path_buf(), was: Seen::of(smeta), loose: self.loose_inodes }); + let loose = match self.loose_inodes { + Some(l) => l, + None => { + let l = self.moving_top.clone().is_some_and(|top| self.inodes_may_change_at(&top)); + self.loose_inodes = Some(l); + l + } + }; + self.to_delete.push(Moved::File { src: src.to_path_buf(), was: Seen::of(smeta), seen_at: epoch_secs(std::time::SystemTime::now()), loose }); } else { self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); } @@ -2334,6 +2375,11 @@ impl Run { } } +/// Seconds since the epoch, as file times are kept. +fn epoch_secs(t: std::time::SystemTime) -> i64 { + t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64) +} + /// Whether nothing is at `path` now. An error other than "not found", as from a folder that /// can't be read, doesn't say it's gone. fn is_gone(path: &Path) -> bool { @@ -5202,19 +5248,48 @@ mod tests { } #[test] - fn a_file_on_a_share_is_known_by_its_size_and_time_not_its_inode() { - let was = Seen { ino: 10, len: 5, mtime: (100, 7) }; + fn a_file_on_a_share_is_known_by_its_size_and_times_not_its_inode() { + let (start, seen) = (1_000_000, 1_000_100); + let was = Seen { ino: 10, len: 5, mtime: (900_000, 7), ctime: (900_000, 9) }; + let same = |now: Seen, loose| was.unchanged(&now, loose, seen, start); let renumbered = Seen { ino: 99, ..was }; - assert!(!was.unchanged(&renumbered, false), "on a local disk a new inode is another file"); - assert!(was.unchanged(&renumbered, true), "on a share the number can change by itself"); - assert!(!was.unchanged(&Seen { len: 6, ..renumbered }, true)); - assert!(!was.unchanged(&Seen { mtime: (101, 7), ..was }, true)); + assert!(!same(renumbered, false), "on a local disk a new inode is another file"); + assert!(same(renumbered, true), "on a share the number can change by itself"); + assert!(!same(Seen { len: 6, ..renumbered }, true)); + assert!(!same(Seen { mtime: (900_001, 7), ..was }, true)); + // A rewrite of the same size within one tick of the time shows in the change time. + assert!(!same(Seen { ctime: (1_000_050, 0), ..renumbered }, true)); + // Where the share doesn't keep a change time, it isn't compared. + assert!(Seen { ctime: (0, 0), ..was }.unchanged(&Seen { ctime: (5, 0), ..renumbered }, true, seen, start)); + // Changed within 2 s of being seen or of the job starting: it's kept, to be safe. + for recent in [seen - 1, seen + 1, start, start + 1] { + let w = Seen { mtime: (recent, 0), ..was }; + assert!(!w.unchanged(&Seen { ino: 99, ..w }, true, seen, start), "{recent}"); + assert!(w.unchanged(&w, false, seen, start), "a local disk has the inode to go by"); + } + } + + #[test] + fn only_shares_that_renumber_inodes_are_loose() { let m = |point: &str, fs_type: &str| crate::mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; - let all = [m("/", "ext4"), m("/mnt/nas", "cifs"), m("/home/me/remote", "fuse.sshfs"), m("/run/media/me/USB", "fuseblk"), m("/srv", "nfs4")]; - for loose in ["/mnt/nas/a", "/home/me/remote/b", "/run/media/me/USB/c", "/srv/d"] { + let all = [ + m("/", "ext4"), + m("/mnt/nas", "cifs"), + m("/mnt/smb", "smb3"), + m("/srv", "nfs4"), + m("/home/me/remote", "fuse.sshfs"), + m("/run/user/1000/gvfs", "fuse.gvfsd-fuse"), + m("/mnt/vm", "9p"), + m("/run/media/me/USB", "fuseblk"), + m("/mnt/exfat", "fuse.exfat"), + m("/home/me/vault", "fuse.gocryptfs"), + ]; + for loose in ["/mnt/nas/a", "/mnt/smb/a", "/srv/d", "/home/me/remote/b", "/run/user/1000/gvfs/x", "/mnt/vm/y"] { assert!(inodes_may_change_in(&all, Path::new(loose)), "{loose}"); } - assert!(!inodes_may_change_in(&all, Path::new("/home/me/e"))); + for stable in ["/home/me/e", "/run/media/me/USB/c", "/mnt/exfat/f", "/home/me/vault/g"] { + assert!(!inodes_may_change_in(&all, Path::new(stable)), "{stable}"); + } } #[test] From ea33bb1eff01d7af9314a6780b3a3cee659b9d21 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 23:58:29 -0700 Subject: [PATCH 6/7] ALI-2600: Review round 4: compare a moved file against the look before its copy - The reference time for telling whether a moved source changed is taken right before it's looked at, ahead of the copy, or the job's start if that's earlier (reference_time). - On a share, times come from the server's clock, so a file whose time is at or after 10 s before the reference is taken as changed and kept. That covers a server up to 10 s behind, and any amount ahead. Beyond 10 s behind, only the size and change time can tell, as the doc says. - Local disks with coarse times (vfat, exFAT and msdos at 2 s, ext3 at 1 s) compare the change time too, where it's kept, and use the same window. Care::{Strict, Coarse, Loose}, from the mount table the move reads once. - mounts::inodes_renumbered also takes in fuse.glusterfs, fuse.ceph-fuse, fuse.davfs, the MTP FUSE kinds, afs, lustre and vboxsf. Plain fuse stays out, and so is compared strictly. --- crates/core/src/mounts.rs | 5 +- crates/core/src/ops.rs | 172 ++++++++++++++++++++++++++------------ 2 files changed, 122 insertions(+), 55 deletions(-) diff --git a/crates/core/src/mounts.rs b/crates/core/src/mounts.rs index 419fdbd..75b1dc7 100644 --- a/crates/core/src/mounts.rs +++ b/crates/core/src/mounts.rs @@ -64,7 +64,10 @@ pub fn inodes_may_change(fs_type: &str) -> bool { /// which is for telling a folder apart and so also takes in any FUSE: a local FUSE drive, as /// ntfs-3g (`fuseblk`) or exFAT, keeps its numbers. pub fn inodes_renumbered(fs_type: &str) -> bool { - const NETWORK: [&str; 15] = ["nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "glusterfs", "davfs", "sshfs", "fuse.sshfs", "fuse.gvfsd-fuse", "fuse.rclone", "fuse.s3fs", "fuse.curlftpfs"]; + // Plain `fuse` says nothing about what's behind it, so it's left out, and taken as stable. + const NETWORK: [&str; 24] = [ + "nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "glusterfs", "davfs", "afs", "lustre", "vboxsf", "sshfs", "fuse.sshfs", "fuse.gvfsd-fuse", "fuse.rclone", "fuse.s3fs", "fuse.curlftpfs", "fuse.glusterfs", "fuse.ceph-fuse", "fuse.davfs", "fuse.mtpfs", "fuse.jmtpfs", "fuse.simple-mtpfs", + ]; NETWORK.contains(&fs_type) } diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index dd5d08f..a3a4cc8 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -334,7 +334,8 @@ impl Engine { inside_new: false, to_delete: Vec::new(), renamed: 0, - loose_inodes: None, + care: None, + looked_at: std::time::SystemTime::now(), moving_top: None, started: std::time::SystemTime::now(), mount_table: None, @@ -718,43 +719,68 @@ struct Seen { ctime: (i64, i64), } -/// How close to a moment a file's time can be and still be taken as from before it. Coarse -/// clocks on shares (FAT and SMB keep 2 s) can't tell apart changes nearer than that. -const TICK: i64 = 2; +/// How a filesystem's files can be told apart over time. See [`Seen::unchanged`]. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Care { + /// A local disk with fine times: the inode, size and time say. + Strict, + /// A local disk with coarse times (vfat, exFAT and msdos keep 2 s, ext3 1 s), where a + /// change soon after a look can leave the time the same. + Coarse, + /// A share whose inode numbers change between looks, and whose times come from another + /// machine's clock. + Loose, +} + +/// How far around the reference time a file's time is taken as too close to tell. Wide +/// enough for coarse clocks and for a server's clock a little off from this one's. +const WINDOW: i64 = 10; impl Seen { fn of(m: &Metadata) -> Seen { Seen { ino: m.ino(), len: m.len(), mtime: (m.mtime(), m.mtime_nsec()), ctime: (m.ctime(), m.ctime_nsec()) } } - /// Whether `now` is still the file as it was when it was seen at `seen_at`, in a job that - /// started at `started` (seconds since the epoch). On a share whose inode numbers change - /// between looks (`loose`), the number can't say, so the size, the times, and the change - /// time where the filesystem keeps one have to. A change within one tick of the time could - /// leave them all the same, so a file changed that recently is taken as changed, which - /// keeps the original. - fn unchanged(&self, now: &Seen, loose: bool, seen_at: i64, started: i64) -> bool { - if !loose { - return self.ino == now.ino && self.len == now.len && self.mtime == now.mtime; + /// Whether `now` is still the file as it was. `reference` is when it was looked at before + /// copying, or the job's start if earlier, in seconds since the epoch. + /// + /// On a local disk with fine times the inode, size and time say. Where the times are coarse, + /// or on a share, a change soon after the look can leave the times as they were, so the + /// change time is compared too where the filesystem keeps one, and a file whose time is + /// at or after 10 s before the reference is taken as changed, which keeps the original. + /// That also covers a server whose clock runs ahead of this one. A share's inode numbers + /// can change between looks, so there they aren't compared. + /// + /// The limit: a server whose clock is more than 10 s behind can stamp a change made during + /// the job with a time before the window, and then only the size and change time can tell. + fn unchanged(&self, now: &Seen, care: Care, reference: i64) -> bool { + let same_times = self.len == now.len && self.mtime == now.mtime; + if care == Care::Strict { + return self.ino == now.ino && same_times; } - let near = |t: i64| (now.mtime.0 - t).abs() < TICK; let ctime_same = self.ctime == (0, 0) || now.ctime == (0, 0) || self.ctime == now.ctime; - self.len == now.len && self.mtime == now.mtime && ctime_same && !near(seen_at) && !near(started) + let recent = now.mtime.0 >= reference - WINDOW; + let ino_same = care == Care::Loose || self.ino == now.ino; + ino_same && same_times && ctime_same && !recent } } -/// Whether the filesystem `path` is on, as the mount table has it, gives a file another inode -/// number from one look to the next. See [`crate::mounts::inodes_renumbered`]. -fn inodes_may_change_in(all: &[crate::mounts::Mount], path: &Path) -> bool { +/// How the files on the filesystem `path` is on, as the mount table has it, can be told apart. +/// See [`crate::mounts::inodes_renumbered`]. +fn care_in(all: &[crate::mounts::Mount], path: &Path) -> Care { let point = crate::mounts::mount_point_of(all, path); - all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).is_some_and(|m| crate::mounts::inodes_renumbered(&m.fs_type)) + match all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).map(|m| m.fs_type.as_str()) { + Some(t) if crate::mounts::inodes_renumbered(t) => Care::Loose, + Some("vfat" | "exfat" | "msdos" | "ext3") => Care::Coarse, + _ => Care::Strict, + } } /// A source a move across disks has copied, removed once everything has been. enum Moved { - /// With what it was when it was copied, and when, so a file changed since is kept. `loose` - /// if it's on a share whose inode numbers can change from one look to the next. - File { src: PathBuf, was: Seen, seen_at: i64, loose: bool }, + /// With what it was before it was copied, and the reference time for that (see + /// [`Seen::unchanged`]), so a file changed since is kept. + File { src: PathBuf, was: Seen, reference: i64, care: Care }, /// Removed once empty. `clean` if nothing in it failed or was left on purpose. Folder { src: PathBuf, clean: bool }, } @@ -809,7 +835,9 @@ struct Run { renamed: usize, /// Whether the top-level item being moved, `moving_top`, is on a share whose inode numbers /// can change. See [`Seen::unchanged`]. - loose_inodes: Option, + care: Option, + /// When the item being placed was last looked at, before it's copied. + looked_at: std::time::SystemTime, moving_top: Option, /// When the job started, as the clock has it, for telling a source changed during it. started: std::time::SystemTime, @@ -1699,12 +1727,12 @@ impl Run { self.settle(tops, sources, dest, mode); } - /// Whether `src` is on a share whose inode numbers can change. Its folder is - /// resolved for the mount table; the item itself isn't followed. - fn inodes_may_change_at(&mut self, src: &Path) -> bool { + /// How files where `src` is can be told apart. Its folder is resolved for the mount table; + /// the item itself isn't followed. + fn care_at(&mut self, src: &Path) -> Care { let real = src.parent().and_then(|d| fs::canonicalize(d).ok()).map(|d| src.file_name().map_or(d.clone(), |n| d.join(n))); let table = self.mount_table.get_or_insert_with(crate::mounts::read_mounts); - real.is_some_and(|r| inodes_may_change_in(table, &r)) + real.map_or(Care::Strict, |r| care_in(table, &r)) } /// What `place` noted about the top-level item it just placed. @@ -1785,7 +1813,6 @@ impl Run { /// folders holding them. fn delete_moved(&mut self) { let mut kept: Vec = Vec::new(); - let started = epoch_secs(self.started); let pending = std::mem::take(&mut self.to_delete); // Removing them is part of the move, so the bar goes on until they're gone. let progress = self.job.progress.clone(); @@ -1794,8 +1821,8 @@ impl Run { progress.done_items.fetch_add(1, Ordering::Relaxed); self.tick(); match m { - Moved::File { src, was, seen_at, loose } => match fs::symlink_metadata(&src) { - Ok(now) if was.unchanged(&Seen::of(&now), loose, seen_at, started) => { + Moved::File { src, was, reference, care } => match fs::symlink_metadata(&src) { + Ok(now) if was.unchanged(&Seen::of(&now), care, reference) => { if let Err(e) = fs::remove_file(&src) { self.fail(&src, &e); kept.push(src); @@ -1857,6 +1884,8 @@ impl Run { return Flow::Stop; } self.set_current(src); + // Taken before the look, so a change right after it falls inside the window. + self.looked_at = std::time::SystemTime::now(); let smeta = match fs::symlink_metadata(src) { Ok(m) => m, Err(e) => { @@ -1868,7 +1897,7 @@ impl Run { self.top_dev = smeta.dev(); if mode == Mode::Move { // Worked out only once something of it is copied: a rename doesn't need it. - self.loose_inodes = None; + self.care = None; self.moving_top = Some(src.to_path_buf()); } } else if mode == Mode::Move && smeta.is_dir() && is_mount_boundary(src, &smeta, self.top_dev) { @@ -2186,15 +2215,16 @@ impl Run { self.report(src, format!("Copied, but couldn't confirm it reached the disk, so the original stays: {}", describe(&e))); return Flow::Go; } - let loose = match self.loose_inodes { - Some(l) => l, + let care = match self.care { + Some(c) => c, None => { - let l = self.moving_top.clone().is_some_and(|top| self.inodes_may_change_at(&top)); - self.loose_inodes = Some(l); - l + let c = self.moving_top.clone().map_or(Care::Strict, |top| self.care_at(&top)); + self.care = Some(c); + c } }; - self.to_delete.push(Moved::File { src: src.to_path_buf(), was: Seen::of(smeta), seen_at: epoch_secs(std::time::SystemTime::now()), loose }); + let reference = reference_time(self.looked_at, self.started); + self.to_delete.push(Moved::File { src: src.to_path_buf(), was: Seen::of(smeta), reference, care }); } else { self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); } @@ -2375,6 +2405,12 @@ impl Run { } } +/// The time a source's later look is compared against: when it was looked at before being +/// copied, or the job's start if that's earlier. See [`Seen::unchanged`]. +fn reference_time(looked_at: std::time::SystemTime, started: std::time::SystemTime) -> i64 { + epoch_secs(looked_at.min(started)) +} + /// Seconds since the epoch, as file times are kept. fn epoch_secs(t: std::time::SystemTime) -> i64 { t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64) @@ -5249,24 +5285,48 @@ mod tests { #[test] fn a_file_on_a_share_is_known_by_its_size_and_times_not_its_inode() { - let (start, seen) = (1_000_000, 1_000_100); + let reference = 1_000_000; let was = Seen { ino: 10, len: 5, mtime: (900_000, 7), ctime: (900_000, 9) }; - let same = |now: Seen, loose| was.unchanged(&now, loose, seen, start); + let same = |now: Seen, care| was.unchanged(&now, care, reference); let renumbered = Seen { ino: 99, ..was }; - assert!(!same(renumbered, false), "on a local disk a new inode is another file"); - assert!(same(renumbered, true), "on a share the number can change by itself"); - assert!(!same(Seen { len: 6, ..renumbered }, true)); - assert!(!same(Seen { mtime: (900_001, 7), ..was }, true)); - // A rewrite of the same size within one tick of the time shows in the change time. - assert!(!same(Seen { ctime: (1_000_050, 0), ..renumbered }, true)); - // Where the share doesn't keep a change time, it isn't compared. - assert!(Seen { ctime: (0, 0), ..was }.unchanged(&Seen { ctime: (5, 0), ..renumbered }, true, seen, start)); - // Changed within 2 s of being seen or of the job starting: it's kept, to be safe. - for recent in [seen - 1, seen + 1, start, start + 1] { - let w = Seen { mtime: (recent, 0), ..was }; - assert!(!w.unchanged(&Seen { ino: 99, ..w }, true, seen, start), "{recent}"); - assert!(w.unchanged(&w, false, seen, start), "a local disk has the inode to go by"); + assert!(!same(renumbered, Care::Strict), "on a local disk a new inode is another file"); + assert!(!same(renumbered, Care::Coarse)); + assert!(same(renumbered, Care::Loose), "on a share the number can change by itself"); + assert!(!same(Seen { len: 6, ..renumbered }, Care::Loose)); + assert!(!same(Seen { mtime: (900_001, 7), ..was }, Care::Loose)); + // A rewrite of the same size that kept the time shows in the change time. + assert!(!same(Seen { ctime: (900_050, 0), ..renumbered }, Care::Loose)); + assert!(!same(Seen { ctime: (900_050, 0), ..was }, Care::Coarse)); + assert!(same(Seen { ctime: (900_050, 0), ..was }, Care::Strict), "fine times need no change time"); + // Where the filesystem doesn't keep a change time, it isn't compared. + assert!(Seen { ctime: (0, 0), ..was }.unchanged(&Seen { ctime: (5, 0), ..renumbered }, Care::Loose, reference)); + } + + #[test] + fn a_file_with_a_time_near_the_copy_is_kept_where_times_are_coarse_or_from_a_server() { + let reference = 1_000_000; + // Within 10 s either side of the reference, or after it, as a server running ahead stamps. + for t in [reference - 10, reference - 3, reference, reference + 3, reference + 10, reference + 3600] { + let w = Seen { ino: 1, len: 5, mtime: (t, 0), ctime: (t, 0) }; + assert!(!w.unchanged(&w, Care::Loose, reference), "{t}"); + assert!(!w.unchanged(&w, Care::Coarse, reference), "{t}"); + assert!(w.unchanged(&w, Care::Strict, reference), "a disk with fine times needs no window: {t}"); } + let old = Seen { ino: 1, len: 5, mtime: (reference - 11, 0), ctime: (reference - 11, 0) }; + assert!(old.unchanged(&old, Care::Loose, reference)); + assert!(old.unchanged(&old, Care::Coarse, reference)); + } + + #[test] + fn the_reference_is_the_look_before_the_copy_or_the_job_start_if_earlier() { + let t = |secs| std::time::UNIX_EPOCH + Duration::from_secs(secs); + assert_eq!(reference_time(t(1_000_100), t(1_000_000)), 1_000_000, "the job started first"); + assert_eq!(reference_time(t(999_000), t(1_000_000)), 999_000, "the clock went back since the start"); + // A file changed just after its look, but stamped before the copy ended, is still kept. + let looked: i64 = 1_000_100; + let r = reference_time(t(looked as u64), t(1_000_090)); + let w = Seen { ino: 1, len: 5, mtime: (looked + 1, 0), ctime: (looked + 1, 0) }; + assert!(!w.unchanged(&w, Care::Loose, r)); } #[test] @@ -5285,10 +5345,14 @@ mod tests { m("/home/me/vault", "fuse.gocryptfs"), ]; for loose in ["/mnt/nas/a", "/mnt/smb/a", "/srv/d", "/home/me/remote/b", "/run/user/1000/gvfs/x", "/mnt/vm/y"] { - assert!(inodes_may_change_in(&all, Path::new(loose)), "{loose}"); + assert_eq!(care_in(&all, Path::new(loose)), Care::Loose, "{loose}"); } for stable in ["/home/me/e", "/run/media/me/USB/c", "/mnt/exfat/f", "/home/me/vault/g"] { - assert!(!inodes_may_change_in(&all, Path::new(stable)), "{stable}"); + assert_eq!(care_in(&all, Path::new(stable)), Care::Strict, "{stable}"); + } + let coarse = [m("/", "ext4"), m("/a", "vfat"), m("/b", "exfat"), m("/c", "msdos"), m("/d", "ext3")]; + for c in ["/a/x", "/b/x", "/c/x", "/d/x"] { + assert_eq!(care_in(&coarse, Path::new(c)), Care::Coarse, "{c}"); } } From 7be03ad54c612c51c0fc7e13292ea8865ba86dbd Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 00:11:16 -0700 Subject: [PATCH 7/7] ALI-2600: Make two merge tests independent of the order a folder lists its names in CI lists names in another order than the btrfs scratch disk here, and both failed there. - a_full_merge_takes_away_only_what_it_added answers every clash with Replace for all, however many come up before the disk fills, instead of expecting three questions. - stopping_a_merge_on_one_disk_keeps_what_it_renamed gives each merged folder one thing and stops at a second source, which place_all reaches after the first, so the questions come in one order on any disk. --- crates/core/src/ops.rs | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index a3a4cc8..b6a5184 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -2761,6 +2761,20 @@ mod tests { } } + /// Waits for the job, answering every conflict, if any come, with Replace for all. + fn finish_replacing(rx: &Receiver) -> Done { + let mut errors = Vec::new(); + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("job should finish") { + Event::Error { path, message, .. } => errors.push((path, message)), + Event::Conflict(c) => c.reply.send(all(Choice::Replace)).unwrap(), + Event::Expands(q) => panic!("unexpected question about {:?}", q.archive), + Event::Progress(_) => {} + Event::Finished(outcome) => return Done { outcome, errors }, + } + } + } + fn answer(choice: Choice) -> Answer { Answer { choice, apply_to_all: false } } @@ -5116,8 +5130,10 @@ mod tests { megabytes(&s, "data/kept", 1); megabytes(&s, "data/new folder", 2); e.start(Request::Copy { sources: vec![s.path().join("data")], dest: disk.clone() }); - // Replace merges the folders, and applies to the files as well. - let done = finish(&rx, vec![answer(Choice::Replace), answer(Choice::Replace), all(Choice::Replace)]); + // Replace merges the folders, and applies to the files as well. Which clashes come up + // before the disk fills depends on the order the folder lists its names in, so every + // one is answered, however many there are. + let done = finish_replacing(&rx); assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “data”: there isn't enough space in “merge”. Nothing was copied".to_string())]); assert_eq!(contents(&disk.join("data")), ["a.bin", "kept", "old.txt"]); assert_eq!(contents(&disk.join("data/kept")), ["inside"]); @@ -5360,22 +5376,21 @@ mod tests { fn stopping_a_merge_on_one_disk_keeps_what_it_renamed() { let s = Scratch::new(); let (e, rx) = engine(&s); - // Made in this order, which the scratch disk lists them in, so sub is merged before c asks. + // Each folder holds one thing, and the sources go in the order given, so the questions + // come in this order on any disk: d, d/sub, then e, where the move is stopped. s.file("src/d/sub/b", b"b"); - s.file("src/d/c", b"new c"); - let names: Vec<_> = fs::read_dir(s.path().join("src/d")).unwrap().flatten().map(|e| e.file_name()).collect(); - assert_eq!(names, ["sub", "c"], "this test needs a disk that lists names in the order they were made"); + s.file("src/e", b"new e"); s.file("dest/d/sub/old", b"old"); - s.file("dest/d/c", b"old c"); - e.start(Request::Move { sources: vec![s.path().join("src/d")], dest: s.path().join("dest") }); - // Merge d, merge sub, then stop at c. + s.file("dest/e", b"old e"); + e.start(Request::Move { sources: vec![s.path().join("src/d"), s.path().join("src/e")], dest: s.path().join("dest") }); let done = finish(&rx, vec![answer(Choice::Replace), answer(Choice::Replace), answer(Choice::Cancel)]); assert!(done.outcome.cancelled); assert_eq!(done.outcome.stopped, None, "something was moved, so it isn't \"Nothing was moved\""); assert_eq!(fs::read(s.path().join("dest/d/sub/b")).unwrap(), b"b"); - assert!(!s.path().join("src/d/sub").exists(), "the emptied folder went"); - assert_eq!(fs::read(s.path().join("src/d/c")).unwrap(), b"new c"); - assert_eq!(fs::read(s.path().join("dest/d/c")).unwrap(), b"old c"); + assert_eq!(fs::read(s.path().join("dest/d/sub/old")).unwrap(), b"old"); + assert!(!s.path().join("src/d").exists(), "the folders it emptied went"); + assert_eq!(fs::read(s.path().join("src/e")).unwrap(), b"new e"); + assert_eq!(fs::read(s.path().join("dest/e")).unwrap(), b"old e"); assert_eq!(done.outcome.created, [s.path().join("dest/d")], "the folder merged into is selected"); }