Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(upgrade): retry the Windows binary swap through a sharing violation

gbb27c0c0a8523
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12202b0f..6a0da7ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,11 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- `ai-memory upgrade` on Windows now waits for a scanner to release the
+ running or the freshly written binary before swapping them, instead of
+ failing with "being used by another process". The swap retries that
+ sharing violation for about eight seconds, as the wiki's atomic writes
+ already did (#1895).
- Project search links now use the project's current stored name after
resolving a canonical or legacy key. Results, breadcrumbs, and the scope
selector stay on that project without renaming it (#1875).
diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rs
index 24cf103d..dc54bbd5 100644
--- a/crates/ai-memory-cli/src/commands/upgrade.rs
+++ b/crates/ai-memory-cli/src/commands/upgrade.rs
@@ -689,18 +689,31 @@ fn replace_file_atomic(src: &Path, dest: &Path) -> Result<()> {
}
}
+/// Linear backoff, 100 ms + 200 ms + … + 1.2 s: a scanner holds a fresh
+/// 100 MB binary for a few seconds.
+#[cfg(windows)]
+const SWAP_RETRY_ATTEMPTS: u32 = 12;
+#[cfg(windows)]
+const SWAP_RETRY_BASE_DELAY: Duration = Duration::from_millis(100);
+
/// Windows allows renaming a running image aside, but not overwriting it.
/// Stage to `.new`, move live `dest` → `.old`, promote `.new` → `dest`, then
/// best-effort delete `.old` (often fails while this process still maps it).
+///
+/// Both renames retry a sharing violation: a scanner holding the running
+/// binary or the fresh `.new` used to fail the upgrade.
#[cfg(windows)]
fn replace_file_windows_rename_aside(tmp: &Path, dest: &Path) -> Result<()> {
+ let rename = |from: &Path, to: &Path| {
+ ai_memory_wiki::rename_with_retry(from, to, SWAP_RETRY_ATTEMPTS, SWAP_RETRY_BASE_DELAY)
+ };
let old = dest.with_extension("old");
if old.exists() {
let _ = fs::remove_file(&old);
}
let had_dest = dest.exists();
if had_dest {
- fs::rename(dest, &old).with_context(|| {
+ rename(dest, &old).with_context(|| {
format!(
"moving running binary aside {} -> {}",
dest.display(),
@@ -708,9 +721,9 @@ fn replace_file_windows_rename_aside(tmp: &Path, dest: &Path) -> Result<()> {
)
})?;
}
- if let Err(err) = fs::rename(tmp, dest) {
+ if let Err(err) = rename(tmp, dest) {
if had_dest {
- let _ = fs::rename(&old, dest);
+ let _ = rename(&old, dest);
}
return Err(err).with_context(|| {
format!(
@@ -1722,6 +1735,43 @@ mod tests {
Ok(())
}
+ /// A scanner holds the running binary when the swap moves it aside; the
+ /// swap waits it out. Fails without the retry.
+ #[cfg(windows)]
+ #[test]
+ fn replace_file_atomic_waits_out_a_transient_hold_on_the_running_binary() -> Result<()> {
+ use std::os::windows::fs::OpenOptionsExt as _;
+ const FILE_SHARE_READ: u32 = 1;
+
+ let dir = tempfile::tempdir()?;
+ let dest = dir.path().join(shipped_binary_name());
+ let src = dir.path().join("fresh");
+ fs::write(&dest, b"old")?;
+ fs::write(&src, b"new")?;
+ let holder = fs::OpenOptions::new()
+ .read(true)
+ .share_mode(FILE_SHARE_READ)
+ .open(&dest)?;
+ assert_eq!(
+ fs::rename(&dest, dest.with_extension("probe"))
+ .unwrap_err()
+ .raw_os_error(),
+ Some(32),
+ "the hold must be a real sharing violation"
+ );
+ let release = std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(400));
+ drop(holder);
+ });
+
+ replace_file_atomic(&src, &dest)?;
+
+ release.join().expect("release thread");
+ assert_eq!(fs::read(&dest)?, b"new");
+ assert!(!dest.with_extension("new").exists());
+ Ok(())
+ }
+
#[test]
fn replace_file_atomic_cleans_stale_old_before_swap() -> Result<()> {
let dir = tempfile::tempdir()?;
diff --git a/crates/ai-memory-wiki/src/atomic.rs b/crates/ai-memory-wiki/src/atomic.rs
index 07fe2428..0ff7bbf5 100644
--- a/crates/ai-memory-wiki/src/atomic.rs
+++ b/crates/ai-memory-wiki/src/atomic.rs
@@ -75,6 +75,46 @@ where
}
}
+/// `fs::rename`, retrying a transient sharing violation `attempts` times
+/// with a linear backoff from `base_delay`. Off Windows nothing is transient.
+///
+/// # Errors
+/// The final `fs::rename` error.
+pub fn rename_with_retry(
+ from: &Path,
+ to: &Path,
+ attempts: u32,
+ base_delay: Duration,
+) -> std::io::Result<()> {
+ retry_transient(attempts, base_delay, is_transient_sharing_violation, || {
+ std::fs::rename(from, to)
+ })
+}
+
+/// Retry `attempt_fn` while `transient` says so, at most `attempts` times.
+fn retry_transient<T, F, P>(
+ attempts: u32,
+ base_delay: Duration,
+ transient: P,
+ mut attempt_fn: F,
+) -> std::io::Result<T>
+where
+ F: FnMut() -> std::io::Result<T>,
+ P: Fn(&std::io::Error) -> bool,
+{
+ let mut attempt = 0u32;
+ loop {
+ match attempt_fn() {
+ Ok(value) => return Ok(value),
+ Err(err) if attempt < attempts && transient(&err) => {
+ attempt += 1;
+ std::thread::sleep(base_delay * attempt);
+ }
+ Err(err) => return Err(err),
+ }
+ }
+}
+
/// Windows: sharing (32) and lock (33) violations are transient third-party
/// holds. Everything else — including `ACCESS_DENIED`, which is usually a
/// real permissions problem — propagates immediately. Elsewhere: nothing is
@@ -236,6 +276,97 @@ mod tests {
assert_eq!(calls, 1, "no retry when the predicate says non-transient");
}
+ /// Absorbs a transient hold, stops at the budget, never retries a real
+ /// error.
+ #[test]
+ fn rename_retry_absorbs_transient_holds_within_its_budget() {
+ let mut failures_left = 3;
+ let mut calls = 0u32;
+ let result = retry_transient(
+ 5,
+ Duration::ZERO,
+ |_| true,
+ || {
+ calls += 1;
+ if failures_left > 0 {
+ failures_left -= 1;
+ Err(std::io::Error::from_raw_os_error(32))
+ } else {
+ Ok(())
+ }
+ },
+ );
+ assert!(result.is_ok());
+ assert_eq!(calls, 4, "three transient failures, then success");
+
+ let mut calls = 0u32;
+ let result: std::io::Result<()> = retry_transient(
+ 5,
+ Duration::ZERO,
+ |_| true,
+ || {
+ calls += 1;
+ Err(std::io::Error::from_raw_os_error(32))
+ },
+ );
+ assert!(result.is_err());
+ assert_eq!(calls, 6, "initial attempt plus five retries, then stop");
+
+ let mut calls = 0u32;
+ let result: std::io::Result<()> = retry_transient(
+ 5,
+ Duration::ZERO,
+ |_| false,
+ || {
+ calls += 1;
+ Err(std::io::Error::from_raw_os_error(32))
+ },
+ );
+ assert!(result.is_err());
+ assert_eq!(calls, 1, "no retry when the predicate says non-transient");
+ }
+
+ #[test]
+ fn rename_with_retry_moves_the_file_and_reports_a_missing_source() {
+ let dir = TempDir::new().unwrap();
+ let from = dir.path().join("from");
+ let to = dir.path().join("to");
+ std::fs::write(&from, b"bytes").unwrap();
+ rename_with_retry(&from, &to, 5, Duration::ZERO).unwrap();
+ assert_eq!(std::fs::read(&to).unwrap(), b"bytes");
+ let err = rename_with_retry(&from, &to, 5, Duration::ZERO).unwrap_err();
+ assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
+ }
+
+ /// A real sharing hold: a handle without `FILE_SHARE_DELETE`, as a
+ /// scanner holds a file.
+ #[cfg(windows)]
+ #[test]
+ fn rename_with_retry_outlasts_a_real_sharing_hold() {
+ use std::os::windows::fs::OpenOptionsExt as _;
+ const FILE_SHARE_READ: u32 = 1;
+
+ let dir = TempDir::new().unwrap();
+ let from = dir.path().join("held.exe");
+ let to = dir.path().join("held.old");
+ std::fs::write(&from, b"image").unwrap();
+ let holder = std::fs::OpenOptions::new()
+ .read(true)
+ .share_mode(FILE_SHARE_READ)
+ .open(&from)
+ .unwrap();
+ let err = std::fs::rename(&from, &to).unwrap_err();
+ assert_eq!(err.raw_os_error(), Some(32), "the hold must be real: {err}");
+
+ let release = std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(300));
+ drop(holder);
+ });
+ rename_with_retry(&from, &to, 20, Duration::from_millis(50)).unwrap();
+ release.join().unwrap();
+ assert_eq!(std::fs::read(&to).unwrap(), b"image");
+ }
+
/// Pins the production classifier per platform: on Unix nothing is
/// transient (raw 32 is EPIPE there), so Unix persist behaviour is
/// byte-for-byte unchanged by this fix. On Windows, 32 and 33 retry.
diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rs
index cfaa1c5c..8d6431d9 100644
--- a/crates/ai-memory-wiki/src/lib.rs
+++ b/crates/ai-memory-wiki/src/lib.rs
@@ -23,7 +23,7 @@ pub use admission::{
AdmissionChain, AdmissionContext, AdmissionOp, FailurePolicy, MAX_ADMISSION_WEBHOOKS,
MAX_RESPONSE_BYTES, WebhookConfig,
};
-pub use atomic::write_atomic;
+pub use atomic::{rename_with_retry, write_atomic};
pub use confinement::validate_wiki_tree;
pub use error::{WikiError, WikiResult};
pub use git::{COMMIT_AUTHOR_EMAIL, COMMIT_AUTHOR_NAME, GitAdapter};