Skip to content

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

Rust

fix(backup): test the archive's final flush and fsync its directory

AkitaOnRails1a17deaac315
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 799c6f29..1293aac2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -223,13 +223,6 @@ version in [`docs/changelog/`](docs/changelog/):
relay and wiki sync companions take the same `rustls-webpki` bump.
### Fixed
-- The pre-migration backup archive is now flushed and fsynced before it is
- verified. `finish` returned the buffered writer and it was dropped, so the
- archive's tail was written by `Drop` — discarding any error — and never put
- on stable storage, while the verify pass re-read it from the page cache and
- cleared a destructive in-place migration to run.
- ([#1525](https://github.com/akitaonrails/ai-memory/pull/1525))
-
- Reserved local-embedding capacity for interactive search queries instead of
allowing concurrent page writes and backfill work to occupy every inference
slot. Excess queries fall back immediately to non-vector retrieval, and a
@@ -243,7 +236,12 @@ version in [`docs/changelog/`](docs/changelog/):
session-start fetch whenever any handoff was open, so the session started
with no profile digest, brief or inbox notice at all. The refusal now costs
only the claim, and the handoff stays open.
-
+- The pre-migration backup archive is now flushed and fsynced, along with its
+ directory entry, before it is verified. The buffered tail of the archive was
+ written when the writer was dropped, which discarded any error such as a full
+ disk, and the file was never put on stable storage, while the verify pass
+ re-read it from the page cache and cleared a destructive in-place migration
+ to run. ([#1525](https://github.com/akitaonrails/ai-memory/pull/1525))
- `mcp-bridge` and the `setup` self-check no longer send requests to the
server through `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, as the hooks
already did. A sandbox such as ai-jail exports a proxy with an empty
diff --git a/crates/ai-memory-wiki/src/backup.rs b/crates/ai-memory-wiki/src/backup.rs
index 3b218fc8..e49f5a13 100644
--- a/crates/ai-memory-wiki/src/backup.rs
+++ b/crates/ai-memory-wiki/src/backup.rs
@@ -202,15 +202,21 @@ fn create_pre_migration_backup_inner(
}
}
}
- // `finish` hands back the `BufWriter`. Dropping it would flush on
- // `Drop`, which discards the error, and nothing would fsync — so the
- // verify pass below re-reads the page cache and calls an archive good
- // that is not yet on stable storage. This archive is the gate for a
- // destructive in-place migration, so it has to survive a crash; the
- // admin backup endpoints sync after `finish` for the same reason.
- let mut out = tar.into_inner()?.finish()?;
- out.flush()?;
- out.get_ref().sync_all()?;
+ // The verify pass below re-reads the page cache, so it cannot tell an
+ // archive on stable storage from one that is not. This archive is the
+ // gate for a destructive in-place migration, so it has to survive a
+ // crash: fsync the file, then its directory entry. The admin backup
+ // endpoints sync after `finish` for the same reason.
+ finish_archive(tar)?.sync_all()?;
+ File::open(&dest_dir)
+ .and_then(|dir| dir.sync_all())
+ .unwrap_or_else(|e| {
+ tracing::debug!(
+ dest = %dest_dir.display(),
+ error = %e,
+ "could not fsync the backup destination directory"
+ );
+ });
}
// Verify: re-open and count entries; a torn or unreadable archive
@@ -265,11 +271,57 @@ fn create_pre_migration_backup_inner(
Ok(receipt)
}
+/// End the gzip stream and flush the buffer, returning the underlying writer.
+///
+/// `GzEncoder::finish` hands back the `BufWriter`; dropping it would write the
+/// buffered tail from `Drop`, which discards the error, and a backup on a full
+/// disk would then reach the verify pass as if it had been written.
+fn finish_archive<W: Write>(
+ tar: tar::Builder<flate2::write::GzEncoder<BufWriter<W>>>,
+) -> std::io::Result<W> {
+ tar.into_inner()?
+ .finish()?
+ .into_inner()
+ .map_err(std::io::IntoInnerError::into_error)
+}
+
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
+ /// A destination that takes no bytes, like a full disk.
+ struct FullDisk;
+
+ impl Write for FullDisk {
+ fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
+ Err(std::io::ErrorKind::StorageFull.into())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ /// The whole small archive sits in the `BufWriter` until `finish`, so the
+ /// write that fails is the one flushing that tail; it must reach the
+ /// caller instead of being dropped with the buffer.
+ #[test]
+ fn a_failed_final_flush_fails_the_archive() {
+ let enc =
+ flate2::write::GzEncoder::new(BufWriter::new(FullDisk), flate2::Compression::default());
+ let mut tar = tar::Builder::new(enc);
+ let body = b"page body";
+ let mut header = tar::Header::new_gnu();
+ header.set_size(body.len() as u64);
+ header.set_cksum();
+ tar.append_data(&mut header, "wiki/page.md", &body[..])
+ .unwrap();
+
+ let error = finish_archive(tar).err().expect("a full disk must fail");
+ assert_eq!(error.kind(), std::io::ErrorKind::StorageFull);
+ }
+
fn data_dir_with_content() -> TempDir {
let tmp = TempDir::new().unwrap();
std::fs::create_dir_all(tmp.path().join("wiki/ws/proj/notes")).unwrap();
diff --git a/docs/MIGRATION-2.0.md b/docs/MIGRATION-2.0.md
index 09bdccaf..a6d6a00f 100644
--- a/docs/MIGRATION-2.0.md
+++ b/docs/MIGRATION-2.0.md
@@ -27,7 +27,7 @@ one-shot wiki migration runs before the server accepts any traffic:
Set `AI_MEMORY_BACKUP_DIR=/somewhere/else` before starting if your
home is small; the destination must be outside the data directory.
-The archive is re-opened and verified after writing. **If the backup
+The archive is flushed and fsynced, then re-opened and verified. **If the backup
cannot be written or verified, the migration aborts and the server
refuses to start**. Your data is untouched and the error says why.
diff --git a/docs/okf.md b/docs/okf.md
index 87121864..62541e93 100644
--- a/docs/okf.md
+++ b/docs/okf.md
@@ -116,7 +116,7 @@ Order is fixed; each step gates the next:
1. **Proactive backup, first, always.** The migration compresses the
entire data dir (wiki, SQLite DB, manifests) to
`~/ai-memory-backup-pre-2.0-<date>.tar.gz` (outside the data dir),
- verifies the archive is listable and size-sane, and **aborts if the
+ fsyncs it, verifies the archive is listable and size-sane, and **aborts if the
backup cannot be written or verified**. The archive path is recorded
in the wiki meta manifest.
2. **In-place frontmatter rewrite.** Same page id, same version row,