From 070c1a6017496f172fd0dafa7bb75a71d6fe97d4 Mon Sep 17 00:00:00 2001 From: Stalin Solomon <4509346+stalingino@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:37:05 +0530 Subject: [PATCH 1/3] fix(localfs): make local-store writes atomic and durable put_object wrote objects straight to their final path with fs::write and upload_file copied staged parquet onto the final path with fs_extra, neither with an fsync. A crash, OOM kill or full disk mid-write left a truncated .stream.json, manifest or parquet file at the real path, which later reads treat as a valid object, and a power loss could drop writes already treated as uploaded. Both now write to a uniquely named .partial sibling, fsync it, rename it over the destination (atomic within a filesystem) and fsync the parent directory on Unix, so readers and crashes only ever see the old or the complete new object, the guarantee object stores give a PUT. The temporary file is removed on failure; its .partial suffix keeps it out of every listing filter. This is the pattern the hot tier already uses for its index. --- src/storage/localfs.rs | 140 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 132 insertions(+), 8 deletions(-) diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index 0699d946d..b6d39b36e 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -26,7 +26,6 @@ use async_trait::async_trait; use bytes::Bytes; use chrono::Utc; use datafusion::{datasource::listing::ListingTableUrl, execution::runtime_env::RuntimeEnvBuilder}; -use fs_extra::file::CopyOptions; use futures::{TryStreamExt, stream::FuturesUnordered}; use object_store::{ListResult, ObjectMeta, buffered::BufReader}; use relative_path::{RelativePath, RelativePathBuf}; @@ -384,7 +383,7 @@ impl ObjectStorage for LocalFS { fs::create_dir_all(parent).await?; } - let res = fs::write(path, resource).await; + let res = write_atomically(path, resource).await; if res.is_ok() { // Record single file written successfully increment_files_scanned_in_object_store_calls_by_date( @@ -668,11 +667,6 @@ impl ObjectStorage for LocalFS { path: &Path, tenant_id: &Option, ) -> Result<(), ObjectStorageError> { - let op = CopyOptions { - overwrite: true, - skip_exist: true, - ..CopyOptions::default() - }; let to_path = self.root.join(key); let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); @@ -680,7 +674,7 @@ impl ObjectStorage for LocalFS { fs::create_dir_all(path).await?; } - let result = fs_extra::file::copy(path, to_path, &op); + let result = copy_atomically(path.to_path_buf(), to_path).await; match result { Ok(_) => { increment_object_store_calls_by_date( @@ -845,6 +839,69 @@ async fn dir_name(entry: DirEntry) -> Result, ObjectStorageError> } } +/// Object stores give a PUT all-or-nothing semantics: readers see the previous object or the complete new one. +/// A plain write to the final path does not: a crash, a full disk or a concurrent reader can observe a truncated +/// file there, and LocalFS readers then treat that truncated metadata or parquet file as a valid object. +/// +/// The writers below give LocalFS the same guarantee. Bytes go to a uniquely named `.partial` sibling (so concurrent +/// writers to the same key never share a temporary file, and the `.partial` suffix keeps it out of every listing +/// filter), the file is fsynced, renamed over the destination (atomic within one filesystem), and on Unix the +/// parent directory is fsynced so the rename itself survives a power loss. On failure the temporary file is removed. +async fn write_atomically(dest: PathBuf, contents: Bytes) -> std::io::Result<()> { + tokio::task::spawn_blocking(move || { + commit_via_partial(&dest, |partial| { + let mut file = std::fs::File::create(partial)?; + std::io::Write::write_all(&mut file, &contents)?; + file.sync_all() + }) + }) + .await + .map_err(std::io::Error::other)? +} + +/// Copies `src` to `dest` with the same all-or-nothing guarantee as [`write_atomically`]. `src` is left in place. +async fn copy_atomically(src: PathBuf, dest: PathBuf) -> std::io::Result<()> { + tokio::task::spawn_blocking(move || { + commit_via_partial(&dest, |partial| { + std::fs::copy(&src, partial)?; + std::fs::File::open(partial)?.sync_all() + }) + }) + .await + .map_err(std::io::Error::other)? +} + +fn commit_via_partial( + dest: &Path, + fill: impl FnOnce(&Path) -> std::io::Result<()>, +) -> std::io::Result<()> { + let mut name = dest + .file_name() + .ok_or_else(|| std::io::Error::other(format!("{} has no file name", dest.display())))? + .to_os_string(); + name.push(format!(".{}.partial", ulid::Ulid::new())); + let partial = dest.with_file_name(name); + + let result = fill(&partial) + .and_then(|()| std::fs::rename(&partial, dest)) + .and_then(|()| sync_parent_dir(dest)); + if result.is_err() { + let _ = std::fs::remove_file(&partial); + } + result +} + +/// Persists the directory entry created by a rename. Windows has no equivalent call for directories. +fn sync_parent_dir(path: &Path) -> std::io::Result<()> { + #[cfg(unix)] + if let Some(parent) = path.parent() { + std::fs::File::open(parent)?.sync_all()?; + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + impl From for ObjectStorageError { fn from(e: fs_extra::error::Error) -> Self { ObjectStorageError::UnhandledError(Box::new(e)) @@ -855,6 +912,73 @@ impl From for ObjectStorageError { mod tests { use super::*; + fn partial_files(dir: &Path) -> Vec { + std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".partial")) + .collect() + } + + #[tokio::test] + async fn put_object_replaces_content_and_leaves_no_partial_file() { + let root = tempfile::tempdir().unwrap(); + let store = LocalFS::new(root.path().to_path_buf()); + let key = RelativePath::new("stream/.stream/.stream.json"); + + store + .put_object(key, Bytes::from_static(b"first version"), &None) + .await + .unwrap(); + store + .put_object(key, Bytes::from_static(b"second"), &None) + .await + .unwrap(); + + let written = store.path_in_root(key); + assert_eq!(std::fs::read(&written).unwrap(), b"second"); + assert!(partial_files(written.parent().unwrap()).is_empty()); + } + + #[tokio::test] + async fn upload_file_copies_atomically_and_keeps_the_source() { + let root = tempfile::tempdir().unwrap(); + let staging = tempfile::tempdir().unwrap(); + let store = LocalFS::new(root.path().to_path_buf()); + let staged = staging.path().join("data.parquet"); + std::fs::write(&staged, b"parquet bytes").unwrap(); + + store + .upload_file("stream/date=2026-01-01/data.parquet", &staged, &None) + .await + .unwrap(); + + let uploaded = root.path().join("stream/date=2026-01-01/data.parquet"); + assert_eq!(std::fs::read(&uploaded).unwrap(), b"parquet bytes"); + assert!( + staged.exists(), + "the caller removes the staged file after a successful upload" + ); + assert!(partial_files(uploaded.parent().unwrap()).is_empty()); + } + + #[tokio::test] + async fn failed_atomic_write_keeps_the_old_object_and_cleans_up() { + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("object.json"); + std::fs::write(&dest, b"old").unwrap(); + + let err = commit_via_partial(&dest, |partial| { + std::fs::write(partial, b"half writ")?; + Err(std::io::Error::other("disk full")) + }) + .unwrap_err(); + + assert_eq!(err.to_string(), "disk full"); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + assert!(partial_files(dir.path()).is_empty()); + } + #[tokio::test] async fn directory_listing_keeps_metadata_layouts_and_missing_path_rules() { let root = tempfile::tempdir().unwrap(); From 97790b1ebd42ecac087334bc93a98a05c755a86f Mon Sep 17 00:00:00 2001 From: Stalin Solomon <4509346+stalingino@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:33:16 +0530 Subject: [PATCH 2/3] fix(localfs): skip .partial files in listings, persist new directories - A temporary file left by an interrupted write is named ..partial, which still matches contains-style filters such as ".schema" and "ingestor". get_objects and get_ingestor_meta_file_paths now skip it, so it is never parsed as an object on restart. - Missing parent directories are created by the atomic writer, which fsyncs the parent of every directory it creates; fsyncing only the file's own directory did not persist the entries linking new directories. - The copied file is reopened with write access before sync_all: Windows' FlushFileBuffers needs it. --- src/storage/localfs.rs | 117 +++++++++++++++++++++++++++++++++++------ 1 file changed, 101 insertions(+), 16 deletions(-) diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index b6d39b36e..46fd227d6 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -266,13 +266,13 @@ impl ObjectStorage for LocalFS { while let Some(entry) = entries.next_entry().await? { files_scanned += 1; - let flag = entry - .path() + let entry_path = entry.path(); + let name = entry_path .file_name() .unwrap_or_default() .to_str() - .unwrap_or_default() - .contains("ingestor"); + .unwrap_or_default(); + let flag = name.contains("ingestor") && !is_partial(name); if flag { path_arr.push( @@ -327,6 +327,11 @@ impl ObjectStorage for LocalFS { .to_owned(); files_scanned += 1; + // An interrupted atomic write leaves `..partial` behind; its name still matches + // `contains`-style filters such as ".schema", so it must never be read as an object. + if is_partial(&path) { + continue; + } let ingestor_file = filter_func(path); if !ingestor_file { @@ -379,9 +384,6 @@ impl ObjectStorage for LocalFS { ) -> Result<(), ObjectStorageError> { let path = self.path_in_root(path); let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).await?; - } let res = write_atomically(path, resource).await; if res.is_ok() { @@ -670,9 +672,6 @@ impl ObjectStorage for LocalFS { let to_path = self.root.join(key); let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - if let Some(path) = to_path.parent() { - fs::create_dir_all(path).await?; - } let result = copy_atomically(path.to_path_buf(), to_path).await; match result { @@ -843,10 +842,11 @@ async fn dir_name(entry: DirEntry) -> Result, ObjectStorageError> /// A plain write to the final path does not: a crash, a full disk or a concurrent reader can observe a truncated /// file there, and LocalFS readers then treat that truncated metadata or parquet file as a valid object. /// -/// The writers below give LocalFS the same guarantee. Bytes go to a uniquely named `.partial` sibling (so concurrent -/// writers to the same key never share a temporary file, and the `.partial` suffix keeps it out of every listing -/// filter), the file is fsynced, renamed over the destination (atomic within one filesystem), and on Unix the -/// parent directory is fsynced so the rename itself survives a power loss. On failure the temporary file is removed. +/// The writers below give LocalFS the same guarantee. Missing parent directories are created and made durable, bytes +/// go to a uniquely named `.partial` sibling (so concurrent writers to the same key never share a temporary file), +/// the file is fsynced, renamed over the destination (atomic within one filesystem), and on Unix the parent directory +/// is fsynced so the rename itself survives a power loss. On failure the temporary file is removed; one left behind +/// by a crash is skipped by every LocalFS listing (see [`is_partial`]). async fn write_atomically(dest: PathBuf, contents: Bytes) -> std::io::Result<()> { tokio::task::spawn_blocking(move || { commit_via_partial(&dest, |partial| { @@ -864,7 +864,11 @@ async fn copy_atomically(src: PathBuf, dest: PathBuf) -> std::io::Result<()> { tokio::task::spawn_blocking(move || { commit_via_partial(&dest, |partial| { std::fs::copy(&src, partial)?; - std::fs::File::open(partial)?.sync_all() + // Windows' FlushFileBuffers (behind sync_all) needs a handle with write access. + std::fs::OpenOptions::new() + .write(true) + .open(partial)? + .sync_all() }) }) .await @@ -879,8 +883,11 @@ fn commit_via_partial( .file_name() .ok_or_else(|| std::io::Error::other(format!("{} has no file name", dest.display())))? .to_os_string(); - name.push(format!(".{}.partial", ulid::Ulid::new())); + name.push(format!(".{}{PARTIAL_SUFFIX}", ulid::Ulid::new())); let partial = dest.with_file_name(name); + if let Some(parent) = dest.parent() { + create_dirs_durably(parent)?; + } let result = fill(&partial) .and_then(|()| std::fs::rename(&partial, dest)) @@ -891,6 +898,35 @@ fn commit_via_partial( result } +const PARTIAL_SUFFIX: &str = ".partial"; + +/// Temporary file of an atomic write that has not been renamed into place (possibly left by a crash). +fn is_partial(file_name: &str) -> bool { + file_name.ends_with(PARTIAL_SUFFIX) +} + +/// Creates `dir` and any missing ancestors, then fsyncs the parent of each directory it created, so that after a +/// power loss a file written below them is still reachable. fsyncing only the file's own directory would persist +/// the file's entry but not the entries linking the new directories to their parents. +fn create_dirs_durably(dir: &Path) -> std::io::Result<()> { + let mut missing = Vec::new(); + let mut current = Some(dir); + while let Some(path) = current + && !path.exists() + { + missing.push(path.to_path_buf()); + current = path.parent(); + } + if missing.is_empty() { + return Ok(()); + } + std::fs::create_dir_all(dir)?; + for created in &missing { + sync_parent_dir(created)?; + } + Ok(()) +} + /// Persists the directory entry created by a rename. Windows has no equivalent call for directories. fn sync_parent_dir(path: &Path) -> std::io::Result<()> { #[cfg(unix)] @@ -962,6 +998,55 @@ mod tests { assert!(partial_files(uploaded.parent().unwrap()).is_empty()); } + #[tokio::test] + async fn listings_skip_partial_files_left_by_a_crash() { + let root = tempfile::tempdir().unwrap(); + let store = LocalFS::new(root.path().to_path_buf()); + let dir = root.path().join("stream").join(STREAM_ROOT_DIRECTORY); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("host.schema"), b"{}").unwrap(); + std::fs::write( + dir.join("host.schema.01J0000000000000000000000.partial"), + b"{trunc", + ) + .unwrap(); + std::fs::write( + root.path() + .join("ingestor.abc.json.01J0000000000000000000000.partial"), + b"{trunc", + ) + .unwrap(); + + let schemas = store + .get_objects( + Some(&RelativePathBuf::from(format!( + "stream/{STREAM_ROOT_DIRECTORY}" + ))), + Box::new(|name: String| name.contains(".schema")), + &None, + ) + .await + .unwrap(); + assert_eq!(schemas, vec![Bytes::from_static(b"{}")]); + assert!( + store + .get_ingestor_meta_file_paths(&None) + .await + .unwrap() + .is_empty() + ); + } + + #[test] + fn atomic_write_creates_missing_directories() { + let root = tempfile::tempdir().unwrap(); + let dest = root.path().join("a/b/c/object.json"); + + commit_via_partial(&dest, |partial| std::fs::write(partial, b"ok")).unwrap(); + + assert_eq!(std::fs::read(&dest).unwrap(), b"ok"); + } + #[tokio::test] async fn failed_atomic_write_keeps_the_old_object_and_cleans_up() { let dir = tempfile::tempdir().unwrap(); From 7083e4312c513fba6e65ccf93177277cd5fef7d7 Mon Sep 17 00:00:00 2001 From: Stalin Solomon <4509346+stalingino@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:46:11 +0530 Subject: [PATCH 3/3] fix(localfs): fsync the directory chain up to the store root on commit Syncing only the directories a write created left a gap: a directory created moments earlier by a concurrent writer, or by code that never synced it, was skipped, and could be lost on power loss together with a file this write had already reported as committed. After the rename, every directory from the file's own up to the store root is now fsynced. Syncing a directory with no pending changes is close to free. --- src/storage/localfs.rs | 81 +++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 44 deletions(-) diff --git a/src/storage/localfs.rs b/src/storage/localfs.rs index 46fd227d6..02dc5b92d 100644 --- a/src/storage/localfs.rs +++ b/src/storage/localfs.rs @@ -385,7 +385,7 @@ impl ObjectStorage for LocalFS { let path = self.path_in_root(path); let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - let res = write_atomically(path, resource).await; + let res = write_atomically(self.root.clone(), path, resource).await; if res.is_ok() { // Record single file written successfully increment_files_scanned_in_object_store_calls_by_date( @@ -673,7 +673,7 @@ impl ObjectStorage for LocalFS { let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - let result = copy_atomically(path.to_path_buf(), to_path).await; + let result = copy_atomically(self.root.clone(), path.to_path_buf(), to_path).await; match result { Ok(_) => { increment_object_store_calls_by_date( @@ -842,14 +842,14 @@ async fn dir_name(entry: DirEntry) -> Result, ObjectStorageError> /// A plain write to the final path does not: a crash, a full disk or a concurrent reader can observe a truncated /// file there, and LocalFS readers then treat that truncated metadata or parquet file as a valid object. /// -/// The writers below give LocalFS the same guarantee. Missing parent directories are created and made durable, bytes -/// go to a uniquely named `.partial` sibling (so concurrent writers to the same key never share a temporary file), -/// the file is fsynced, renamed over the destination (atomic within one filesystem), and on Unix the parent directory -/// is fsynced so the rename itself survives a power loss. On failure the temporary file is removed; one left behind -/// by a crash is skipped by every LocalFS listing (see [`is_partial`]). -async fn write_atomically(dest: PathBuf, contents: Bytes) -> std::io::Result<()> { +/// The writers below give LocalFS the same guarantee. Bytes go to a uniquely named `.partial` sibling (so concurrent +/// writers to the same key never share a temporary file), the file is fsynced, renamed over the destination (atomic +/// within one filesystem), and then every directory from the destination's up to the store root is fsynced (see +/// [`sync_dir_chain`]). On failure the temporary file is removed; one left behind by a crash is skipped by every +/// LocalFS listing (see [`is_partial`]). +async fn write_atomically(root: PathBuf, dest: PathBuf, contents: Bytes) -> std::io::Result<()> { tokio::task::spawn_blocking(move || { - commit_via_partial(&dest, |partial| { + commit_via_partial(&root, &dest, |partial| { let mut file = std::fs::File::create(partial)?; std::io::Write::write_all(&mut file, &contents)?; file.sync_all() @@ -860,9 +860,9 @@ async fn write_atomically(dest: PathBuf, contents: Bytes) -> std::io::Result<()> } /// Copies `src` to `dest` with the same all-or-nothing guarantee as [`write_atomically`]. `src` is left in place. -async fn copy_atomically(src: PathBuf, dest: PathBuf) -> std::io::Result<()> { +async fn copy_atomically(root: PathBuf, src: PathBuf, dest: PathBuf) -> std::io::Result<()> { tokio::task::spawn_blocking(move || { - commit_via_partial(&dest, |partial| { + commit_via_partial(&root, &dest, |partial| { std::fs::copy(&src, partial)?; // Windows' FlushFileBuffers (behind sync_all) needs a handle with write access. std::fs::OpenOptions::new() @@ -876,6 +876,7 @@ async fn copy_atomically(src: PathBuf, dest: PathBuf) -> std::io::Result<()> { } fn commit_via_partial( + root: &Path, dest: &Path, fill: impl FnOnce(&Path) -> std::io::Result<()>, ) -> std::io::Result<()> { @@ -885,13 +886,14 @@ fn commit_via_partial( .to_os_string(); name.push(format!(".{}{PARTIAL_SUFFIX}", ulid::Ulid::new())); let partial = dest.with_file_name(name); - if let Some(parent) = dest.parent() { - create_dirs_durably(parent)?; - } + let parent = dest + .parent() + .ok_or_else(|| std::io::Error::other(format!("{} has no parent", dest.display())))?; + std::fs::create_dir_all(parent)?; let result = fill(&partial) .and_then(|()| std::fs::rename(&partial, dest)) - .and_then(|()| sync_parent_dir(dest)); + .and_then(|()| sync_dir_chain(parent, root)); if result.is_err() { let _ = std::fs::remove_file(&partial); } @@ -905,36 +907,27 @@ fn is_partial(file_name: &str) -> bool { file_name.ends_with(PARTIAL_SUFFIX) } -/// Creates `dir` and any missing ancestors, then fsyncs the parent of each directory it created, so that after a -/// power loss a file written below them is still reachable. fsyncing only the file's own directory would persist -/// the file's entry but not the entries linking the new directories to their parents. -fn create_dirs_durably(dir: &Path) -> std::io::Result<()> { - let mut missing = Vec::new(); - let mut current = Some(dir); - while let Some(path) = current - && !path.exists() - { - missing.push(path.to_path_buf()); - current = path.parent(); - } - if missing.is_empty() { - return Ok(()); - } - std::fs::create_dir_all(dir)?; - for created in &missing { - sync_parent_dir(created)?; - } - Ok(()) -} - -/// Persists the directory entry created by a rename. Windows has no equivalent call for directories. -fn sync_parent_dir(path: &Path) -> std::io::Result<()> { +/// Makes a committed file reachable after a power loss: fsyncs `dir` (persisting the rename) and every ancestor up +/// to and including the store `root` (persisting the entries that link each directory to its parent). +/// +/// Syncing only the directories this write created is not enough: a directory created moments earlier by a +/// concurrent writer, or by code that never synced it, can still be lost and take this file with it. Syncing a +/// directory with no pending changes is close to free, so the whole chain is synced on every commit. +/// Windows has no equivalent call for directories. +fn sync_dir_chain(dir: &Path, root: &Path) -> std::io::Result<()> { #[cfg(unix)] - if let Some(parent) = path.parent() { - std::fs::File::open(parent)?.sync_all()?; + { + let mut current = Some(dir); + while let Some(path) = current { + std::fs::File::open(path)?.sync_all()?; + if path == root || !path.starts_with(root) { + break; + } + current = path.parent(); + } } #[cfg(not(unix))] - let _ = path; + let _ = (dir, root); Ok(()) } @@ -1042,7 +1035,7 @@ mod tests { let root = tempfile::tempdir().unwrap(); let dest = root.path().join("a/b/c/object.json"); - commit_via_partial(&dest, |partial| std::fs::write(partial, b"ok")).unwrap(); + commit_via_partial(root.path(), &dest, |partial| std::fs::write(partial, b"ok")).unwrap(); assert_eq!(std::fs::read(&dest).unwrap(), b"ok"); } @@ -1053,7 +1046,7 @@ mod tests { let dest = dir.path().join("object.json"); std::fs::write(&dest, b"old").unwrap(); - let err = commit_via_partial(&dest, |partial| { + let err = commit_via_partial(dir.path(), &dest, |partial| { std::fs::write(partial, b"half writ")?; Err(std::io::Error::other("disk full")) })