From 10b8faeba3a3f933d8ecd3587ac22457e8517af9 Mon Sep 17 00:00:00 2001 From: PaddleStroke Date: Wed, 28 Oct 2026 14:32:20 +0000 Subject: [PATCH] Windows: an export over a file another program holds briefly waits for it, up to 2 s (#8104) (#8125) * claim: #8104 Co-Authored-By: Claude Opus 5.5 * Windows: an export over a file another program holds briefly waits for it, up to 2 s (#8104) write_atomic replaces the target with one rename. Windows refuses that rename (os error 5 or 32) while another program, such as an antivirus or indexer scanning a file written a moment earlier, has the file open without delete sharing. The retry gave up after 127 ms of waiting, which a scan under load outlasts, so render.export and library.export over an existing file failed with "Access is denied". The retry now keeps doubling its wait up to 250 ms, about 2 s in all. If the file is still held after that, the error says the file is in use by another program, followed by the system's own message. The old file stays whole throughout, as before. Co-Authored-By: Claude Opus 5.5 * Saving over a read-only file fails at once, and says why Windows refused Access denied (os error 5) is also what Windows gives for a read-only or ACL-denied target, which waiting does not fix. A read-only target is now refused without the 2 s wait, with "the file is read-only". Any other refusal that outlasts the wait says another program may have the file open or it is read-only, followed by the system's own message. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/io/src/safe_write.rs | 101 ++++++++++++++++++++++++++++++++---- 1 file changed, 90 insertions(+), 11 deletions(-) diff --git a/crates/io/src/safe_write.rs b/crates/io/src/safe_write.rs index 4ee047f75..71f890fb1 100644 --- a/crates/io/src/safe_write.rs +++ b/crates/io/src/safe_write.rs @@ -93,7 +93,33 @@ fn keep_permissions(old: &Option, new: &Path) { // or deleting/truncating its existing target. ACL/read-only/other permanent // refusals still fail. No file lock is broken and no security setting is changed. fn replace_synced(source: &Path, destination: &Path) -> std::io::Result<()> { - rename_with_retry(|| fs::rename(source, destination), cfg!(windows), std::thread::sleep) + // A read-only target is refused for good: fail at once rather than wait for it. + let read_only = fs::metadata(destination).is_ok_and(|m| m.permissions().readonly()); + let windows = cfg!(windows); + rename_with_retry(|| fs::rename(source, destination), windows && !read_only, std::thread::sleep) + .map_err(|error| explain_refusal(error, windows, read_only)) +} + +/// The waits between attempts at a rename Windows refuses: doubling from 1 ms, then 250 ms at a +/// time, about 2 s in all. An antivirus or indexer scanning a file written a moment earlier can +/// hold it for several hundred milliseconds when the machine is busy (#8104); 127 ms was too short. +const RENAME_WAITS_MS: [u64; 15] = [1, 2, 4, 8, 16, 32, 64, 128, 250, 250, 250, 250, 250, 250, 250]; + +/// Whether `error` is Windows refusing a rename (access denied, os error 5, or a sharing +/// violation, os error 32): another program has the file open, or it is read-only or denied. +fn refused_by_windows(error: &std::io::Error) -> bool { + matches!(error.raw_os_error(), Some(5 | 32)) +} + +/// Say why Windows would not replace the file rather than only the bare "Access is denied", and +/// keep the system's own words. +fn explain_refusal(error: std::io::Error, windows: bool, read_only: bool) -> std::io::Error { + if !windows || !refused_by_windows(&error) { + return error; + } + let why = + if read_only { "the file is read-only" } else { "Windows would not replace the file: another program may have it open, or it is read-only" }; + std::io::Error::new(error.kind(), format!("{why} ({error})")) } fn rename_with_retry( @@ -102,12 +128,15 @@ fn rename_with_retry( mut wait: impl FnMut(std::time::Duration), ) -> std::io::Result<()> { // Windows can refuse rename while an independently opened handle withholds - // FILE_SHARE_DELETE. Access denied may also be permanent, so keep both an - // attempt bound and the original last error. Requested sleeps total 127 ms; - // scheduling/OS operation time is not a wall-clock latency guarantee. + // FILE_SHARE_DELETE. Access denied may also be permanent, so keep an attempt + // bound and the last error. Requested sleeps total 2005 ms; scheduling/OS + // operation time is not a wall-clock latency guarantee. let mut result = rename(); - for milliseconds in [1, 2, 4, 8, 16, 32, 64] { - if !windows || !result.as_ref().is_err_and(|error| matches!(error.raw_os_error(), Some(5 | 32))) { + if !windows { + return result; + } + for milliseconds in RENAME_WAITS_MS { + if !result.as_ref().is_err_and(refused_by_windows) { return result; } wait(std::time::Duration::from_millis(milliseconds)); @@ -489,9 +518,9 @@ mod rename_retry_tests { ) .unwrap_err(); assert_eq!(error.raw_os_error(), Some(code)); - assert_eq!(calls.get(), 8); - assert_eq!(waits, [1, 2, 4, 8, 16, 32, 64]); - assert_eq!(waits.iter().sum::(), 127); + assert_eq!(calls.get(), 16); + assert_eq!(waits, [1, 2, 4, 8, 16, 32, 64, 128, 250, 250, 250, 250, 250, 250, 250]); + assert_eq!(waits.iter().sum::(), 2005); } for (windows, code) in [(false, 5), (false, 32), (true, 2), (true, 3), (true, 87), (true, 183)] { let calls = Cell::new(0); @@ -547,12 +576,61 @@ mod rename_retry_tests { }, ) .unwrap(); - assert!(calls.get() >= 2 && calls.get() <= 8); + assert!(calls.get() >= 2 && calls.get() <= 16); assert_eq!(fs::read(&old).unwrap(), b"new complete image"); assert!(!pending.exists()); fs::remove_dir_all(directory).unwrap(); } + /// #8104: a scanner (antivirus, indexer, thumbnailer) that opens the target without delete + /// sharing and keeps it for a few hundred milliseconds under load delays the replace; it does + /// not fail it, and the old file stays whole until the new one takes its place. + #[cfg(windows)] + #[test] + fn a_reader_holding_the_target_for_a_while_delays_the_replace_without_failing_it() { + use std::os::windows::fs::OpenOptionsExt; + let directory = std::env::temp_dir().join(format!("solidcraft-rename-slow-reader-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let path = directory.join("library.json"); + fs::write(&path, b"old whole library").unwrap(); + let reader = OpenOptions::new().read(true).share_mode(1).open(&path).unwrap(); + let scanner = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(400)); + drop(reader); + }); + write_atomic(&path, b"new whole library", false).unwrap(); + scanner.join().unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"new whole library"); + assert!(stale_temps(&path).is_empty()); + fs::remove_dir_all(directory).unwrap(); + } + + /// A read-only target is refused for good: the export fails at once with that reason, rather + /// than after the wait for a program holding the file, and the old file is kept. + #[cfg(windows)] + #[test] + fn a_read_only_target_fails_at_once_and_says_so() { + let directory = std::env::temp_dir().join(format!("solidcraft-rename-read-only-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let path = directory.join("render.png"); + fs::write(&path, b"old image").unwrap(); + let writable = fs::metadata(&path).unwrap().permissions(); + let mut read_only = writable.clone(); + read_only.set_readonly(true); + fs::set_permissions(&path, read_only).unwrap(); + let started = std::time::Instant::now(); + let error = write_atomic(&path, b"new image", false).unwrap_err(); + assert!(started.elapsed() < std::time::Duration::from_millis(1000), "{:?}", started.elapsed()); + assert!(error.to_string().contains("the file is read-only"), "{error}"); + assert!(error.to_string().contains(&std::io::Error::from_raw_os_error(5).to_string()), "{error}"); + assert_eq!(fs::read(&path).unwrap(), b"old image"); + assert!(stale_temps(&path).is_empty()); + fs::set_permissions(&path, writable).unwrap(); + fs::remove_dir_all(directory).unwrap(); + } + #[cfg(windows)] #[test] fn persistent_native_lock_is_an_error_without_destroying_or_bypassing_the_target() { @@ -563,7 +641,8 @@ mod rename_retry_tests { fs::write(&path, b"old whole raw master").unwrap(); let reader = OpenOptions::new().read(true).share_mode(1).open(&path).unwrap(); let error = write_atomic(&path, b"new whole raw master", false).unwrap_err(); - assert!(matches!(error.raw_os_error(), Some(5 | 32)), "{error}"); + assert!(error.to_string().contains("another program may have it open, or it is read-only"), "{error}"); + assert_eq!(error.kind(), std::io::Error::from_raw_os_error(5).kind()); assert_eq!(fs::read(&path).unwrap(), b"old whole raw master"); assert!(stale_temps(&path).is_empty()); drop(reader);