From 2b76b71db835015a8ea266e1fc69c9ddbb6142c0 Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Wed, 3 Sep 2025 11:15:07 +0530 Subject: [PATCH] atomic save of index file --- .../apps/photos/rust/src/api/usearch_api.rs | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/mobile/apps/photos/rust/src/api/usearch_api.rs b/mobile/apps/photos/rust/src/api/usearch_api.rs index b2c77f0fd3..01823cb0f0 100644 --- a/mobile/apps/photos/rust/src/api/usearch_api.rs +++ b/mobile/apps/photos/rust/src/api/usearch_api.rs @@ -49,9 +49,37 @@ impl VectorDB { if let Some(parent) = self.path.parent() { std::fs::create_dir_all(parent).expect("Failed to create directory"); } - self.index - .save(self.path.to_str().expect("Invalid path")) - .expect("Failed to save index"); + + // Use atomic write: save to temp file first, then rename + let temp_path = self.path.with_extension("tmp"); + let temp_path_str = temp_path.to_str().expect("Invalid temp path"); + + // Save to temporary file + match self.index.save(temp_path_str) { + Ok(_) => { + // Atomic rename - guaranteed atomic on iOS/Android + // This will atomically replace the existing file + // The rename ensures we never have a partially written file, + // even if the app is suspended or crashes + match std::fs::rename(&temp_path, &self.path) { + Ok(_) => { + println!("Successfully saved index atomically"); + } + Err(e) => { + println!("Failed to rename temp index file: {:?}", e); + // Try to clean up temp file + let _ = std::fs::remove_file(&temp_path); + panic!("Failed to atomically save index: {:?}", e); + } + } + } + Err(e) => { + println!("Failed to save index to temp file: {:?}", e); + // Try to clean up temp file if it exists + let _ = std::fs::remove_file(&temp_path); + panic!("Failed to save index: {:?}", e); + } + } } fn ensure_capacity(&self, margin: usize) {