Skip to content

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

Rust

fix: full-matrix platform failures in migration backup and serve lock

AkitaOnRails8b8647c28602
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index ec4daa31..c04ceade 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1,7 +1,6 @@
//! `ai-memory serve` — MCP server with optional filesystem watcher.
use std::future::Future;
-use std::io::Write as _;
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
@@ -80,6 +79,13 @@ struct ServeLock {
_file: std::fs::File,
}
+/// Unlocked sidecar naming the lock holder (`pid=<n>`). Separate from the
+/// lock file because Windows' exclusive lock blocks reads of the locked
+/// file from other handles; informational only, rewritten by each holder.
+fn holder_info_path(data_dir: &Path) -> std::path::PathBuf {
+ data_dir.join(".serve.lock.holder")
+}
+
/// Take the single-instance serve lock for `data_dir`.
///
/// A contended lock refuses startup naming the holder, unless `force` is set:
@@ -91,7 +97,7 @@ fn acquire_serve_lock(data_dir: &Path, force: bool) -> Result<Option<ServeLock>>
std::fs::create_dir_all(data_dir)
.with_context(|| format!("creating data directory {}", data_dir.display()))?;
let path = data_dir.join(SERVE_LOCK_FILE);
- let mut file = std::fs::OpenOptions::new()
+ let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
@@ -101,16 +107,20 @@ fn acquire_serve_lock(data_dir: &Path, force: bool) -> Result<Option<ServeLock>>
use fs2::FileExt as _;
match file.try_lock_exclusive() {
Ok(()) => {
- // Informational only: the flock is the guard, and this line names
- // the holder in a later refusal message. Best-effort.
- let _ = file
- .set_len(0)
- .and_then(|()| file.write_all(format!("pid={}\n", std::process::id()).as_bytes()));
+ // Informational only: the flock is the guard, and this names the
+ // holder in a later refusal message. Best-effort, and written to
+ // an UNLOCKED sidecar — on Windows the exclusive lock blocks
+ // other handles from reading the locked file itself, which made
+ // every refusal report "holder unknown".
+ let _ = std::fs::write(
+ holder_info_path(data_dir),
+ format!("pid={}\n", std::process::id()),
+ );
tracing::info!(lock = %path.display(), "single-instance serve lock held");
Ok(Some(ServeLock { _file: file }))
}
Err(err) if crate::commands::hook_spool::is_drain_lock_busy_error(&err) => {
- let holder = std::fs::read_to_string(&path)
+ let holder = std::fs::read_to_string(holder_info_path(data_dir))
.map(|text| text.trim().to_string())
.unwrap_or_default();
if force {
diff --git a/crates/ai-memory-wiki/src/backup.rs b/crates/ai-memory-wiki/src/backup.rs
index e90b171a..9a07ba1e 100644
--- a/crates/ai-memory-wiki/src/backup.rs
+++ b/crates/ai-memory-wiki/src/backup.rs
@@ -93,14 +93,14 @@ fn destination_dir(
// Canonicalize both sides before comparing: `<data_dir>/.` or a
// symlinked spelling must not defeat the root guard (or the walk's
// self-exclusion, which compares against the path returned here).
+ // The dest is created first so it ALWAYS canonicalizes — an
+ // uncanonical spelling of a not-yet-existing dest defeated the
+ // self-exclusion on the very first backup.
+ std::fs::create_dir_all(&dest)?;
let canonical_data = data_dir
.canonicalize()
.unwrap_or_else(|_| data_dir.to_path_buf());
- let canonical_dest = if dest.exists() {
- dest.canonicalize().unwrap_or_else(|_| dest.clone())
- } else {
- dest.clone()
- };
+ let canonical_dest = dest.canonicalize().unwrap_or_else(|_| dest.clone());
if canonical_dest == canonical_data {
return Err(WikiError::Io(std::io::Error::other(
"the backup destination must not be the data dir root itself; \
@@ -127,8 +127,15 @@ fn create_pre_migration_backup_inner(
dest_override: Option<&Path>,
in_container: bool,
) -> WikiResult<BackupReceipt> {
+ // One spelling for every comparison below: `destination_dir` returns a
+ // canonical path, so the walk must produce canonical paths too or the
+ // self-exclusion guards (`path == dest_dir`, `path == archive_path`)
+ // silently miss under a symlinked data-dir spelling (macOS /var ->
+ // /private/var; observed tarring the half-written archive itself).
+ let data_dir = &data_dir
+ .canonicalize()
+ .unwrap_or_else(|_| data_dir.to_path_buf());
let dest_dir = destination_dir(dest_override, data_dir, in_container)?;
- std::fs::create_dir_all(&dest_dir)?;
let stamp = jiff::Timestamp::now().strftime("%Y%m%d-%H%M%S").to_string();
let archive_path = dest_dir.join(format!("ai-memory-backup-{label}-{stamp}.tar.gz"));
@@ -230,7 +237,13 @@ mod tests {
let data = data_dir_with_content();
let dest = TempDir::new().unwrap();
let receipt = create_pre_migration_backup(data.path(), "test", Some(dest.path())).unwrap();
- assert!(receipt.archive_path.starts_with(dest.path()));
+ // TempDir spellings differ from canonical on macOS (/var vs
+ // /private/var); the backup works in canonical space.
+ assert!(
+ receipt
+ .archive_path
+ .starts_with(dest.path().canonicalize().unwrap())
+ );
assert_eq!(receipt.entries, 2);
assert!(receipt.size_bytes > 0);
assert!(receipt.archive_present());
@@ -262,7 +275,7 @@ mod tests {
assert!(
receipt
.archive_path
- .starts_with(data.path().join("backups"))
+ .starts_with(data.path().canonicalize().unwrap().join("backups"))
);
// The two data files, not the archive or receipt.
assert_eq!(receipt.entries, 2);
@@ -284,6 +297,27 @@ mod tests {
assert_eq!(second.entries, 3, "data files + first receipt");
}
+ /// Reproduces the macOS matrix failure on any Unix: hand the backup a
+ /// symlinked spelling of the data dir (as macOS's /var -> /private/var
+ /// does implicitly) and prove the self-exclusion still holds — a second
+ /// run must not descend into backups/ or tar the first archive.
+ #[cfg(unix)]
+ #[test]
+ fn self_exclusion_survives_a_symlinked_data_dir_spelling() {
+ let real = data_dir_with_content();
+ let outer = TempDir::new().unwrap();
+ let alias = outer.path().join("alias");
+ std::os::unix::fs::symlink(real.path(), &alias).unwrap();
+ let dest = alias.join("backups");
+ let first = create_pre_migration_backup(&alias, "test", Some(&dest)).unwrap();
+ assert_eq!(first.entries, 2);
+ let second = create_pre_migration_backup(&alias, "test", Some(&dest)).unwrap();
+ assert_eq!(
+ second.entries, 3,
+ "data files + first receipt, never the archive"
+ );
+ }
+
#[test]
fn the_data_dir_root_is_refused_as_a_destination() {
let data = data_dir_with_content();