From 074223f7d19e152ddf043f4279cfcea085312e1d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:52:57 +0000 Subject: [PATCH 1/2] fix(engine): sync an export's file before it answers, and remove a failed export's file ExportTableToPointInTime wrote each line with tokio's write_all and answered COMPLETED without flushing or syncing the file. A tokio File runs each write on the blocking pool and reports its error to the next write or flush, so the last write could still be running when the answer went out, and its error was lost. A client that read the file at once could find it short, and an export whose last line hit a full disk answered COMPLETED with an ItemCount the file did not hold. The export now flushes the file, which waits for the last write and returns its error, then syncs it and syncs the directory that holds it, before it builds the COMPLETED description. An error from a write, the flush or the file's sync answers "Cannot write export file". sync_all alone would wait for the last write but drop its error, which is why the flush comes first. When the directory cannot be opened (EACCES, EPERM) or its fsync is not supported (EINVAL, ENOTSUP, EOPNOTSUPP, EBADF), the export logs a warning and answers COMPLETED without the directory sync, so an export into a directory the server can write to but not read completes as on main. EIO and every other directory sync error answer "Cannot write export file". PostgreSQL skips EACCES at the open and EBADF and EINVAL at the fsync, and logs nothing. An export that fails after its file is created (over max_export_item_count, a scan error, a write or sync error) used to leave the file under FilePath, and a retry with the same FilePath was refused as an existing file. A guard now removes the file on every error, when the handler's future is dropped, and on a panic. The file is still created with create_new, so an export never truncates or follows an existing file. On Unix the guard records the device and inode of the open file before the first page is read, and unlinks the path only while symlink_metadata reports the same pair, so a file another export put at the path stays. The check and the unlink are two calls, so a file put at the path between them is removed. When the pair cannot be read (there is no spare file descriptor), the export answers "Cannot write export file" before it writes a line and unlinks the path without the check, as it always does on other targets. A failed check or unlink is logged at warn level, and the file then stays. The write loop moves into a new export_file module, which takes the page source as a closure so the tests can drive it without a storage backend. libc becomes a Unix dependency of the engine for the error numbers. The export file tests drive write_export_file with a closure page source, so they need no storage backend. They check the file's size and line count right after each of 200 exports; that an export over the item limit, with a failing scan or dropped while it runs leaves no file and that its path can be used again; that a write failing on the last line or before it (RLIMIT_FSIZE, in a child process) answers "Cannot write export file" and leaves no file; and that can_skip_dir_sync skips the open and fsync errors it names and fails the export on EIO and every other error, with an export into a 0300 directory completing. They also check the guard: a failing export leaves the file another export created at its path; a failed export whose unlink fails leaves its file and logs a warning; an export that cannot read its file's identity (the soft limit on open files lowered to 3 in a child process) answers "Cannot write export file" before it reads a page and leaves no file; and a symlink put at the path of a failing export stays, because the guard compares the device and inode of the symlink itself. is_cannot_write lives in the Unix test module, so clippy with -D warnings passes for x86_64-pc-windows-msvc. --- Cargo.lock | 1 + crates/engine/Cargo.toml | 5 + crates/engine/src/export_file.rs | 293 +++++++++++ crates/engine/src/export_file_tests.rs | 671 +++++++++++++++++++++++++ crates/engine/src/import_export.rs | 74 ++- crates/engine/src/lib.rs | 1 + 6 files changed, 1001 insertions(+), 44 deletions(-) create mode 100644 crates/engine/src/export_file.rs create mode 100644 crates/engine/src/export_file_tests.rs diff --git a/Cargo.lock b/Cargo.lock index c59cdea4e..ffbb6639b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1816,6 +1816,7 @@ dependencies = [ "extenddb-storage", "hex", "hmac 0.12.1", + "libc", "serde", "serde_json", "sha2 0.10.9", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3634c9152..628c02c43 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,3 +21,8 @@ hmac = "0.12" sha2 = "0.10" hex = "0.4" tokio = { workspace = true } + +# The export file's directory sync reads the error number of a failure, and +# its tests lower the file size limit and check the effective uid. +[target.'cfg(unix)'.dependencies] +libc = { workspace = true } diff --git a/crates/engine/src/export_file.rs b/crates/engine/src/export_file.rs new file mode 100644 index 000000000..dc5d33e11 --- /dev/null +++ b/crates/engine/src/export_file.rs @@ -0,0 +1,293 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Writing an `ExportTableToPointInTime` file, and removing it when the export +//! does not complete. +//! +//! `handle_export_table` creates the file with `create_new` and hands it to +//! [`write_export_file`], which writes one line per item and returns only +//! once the file is complete on disk. tokio's `File` runs each write on the +//! blocking pool and reports its error to the next write or flush on the +//! file, so the last write can still be running when `write_all` returns. +//! The file is therefore flushed, which waits for that write and returns its +//! error, and then synced. `sync_all` on its own waits for the last write but +//! does not return its error (tokio keeps only the error's kind for a later +//! write or flush), so an export whose last line hit a full disk would answer +//! `COMPLETED` with a short file. +//! +//! The directory that holds the file is synced after the file, because a +//! file's fsync does not make its new directory entry durable on every +//! filesystem. Only that directory is synced. The handler refuses a +//! `FilePath` whose parent does not exist, so the directories above the file +//! existed before the export, and the export adds an entry to none of them. +//! The exception is the account directory the handler creates on an +//! account's first export: its entry in the export root is not synced here. +//! When the directory cannot be opened for its sync (`EACCES` or `EPERM`, as +//! for a directory the server can write to but not read) or its filesystem +//! has no fsync for directories (`EINVAL`, `ENOTSUP`, `EOPNOTSUPP` or +//! `EBADF`), the export logs a warning and completes without the directory +//! sync; the file itself has been synced. Every other error, `EIO` among +//! them, fails the export. `PostgreSQL` skips `EACCES` at the open and +//! `EBADF` and `EINVAL` at the fsync, and logs nothing; the export also skips +//! `EPERM`, `ENOTSUP` and `EOPNOTSUPP`, and logs a warning. +//! +//! An export that does not complete removes its file. A guard created before +//! the first page is read removes it on every error, when the export's future +//! is dropped (a client that disconnects), and on a panic. The handler opened +//! the file with `create_new`, so nothing else was at the path then, but the +//! name can change hands while the export runs: someone can remove the file +//! and another export can create its own at the same path. On Unix the guard +//! therefore records the device and inode of the open file, and unlinks the +//! name only while `symlink_metadata` of the path reports the same pair; when +//! the name is gone or names another file, it leaves the path alone. The +//! check and the unlink are two calls, so a file put at the path between them +//! is removed. Recording the pair needs a spare file descriptor; if that +//! fails, the export fails before it writes a line and the guard unlinks the +//! name without the check. On other targets the guard unlinks the name +//! without the check. The unlink never follows a symlink. +//! +//! Three cases leave a file: a future dropped while tokio's open is still +//! running on the blocking pool, before the handler holds the file (that open +//! cannot hand back a guard), a process that ends during the export, and a +//! file the server could not remove, which it logs as a warning. + +use std::future::Future; +use std::path::{Path, PathBuf}; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::types::Item; +use tokio::io::AsyncWriteExt; + +/// Write every item `next_page` returns to `file`, one line each, then flush +/// and sync the file and sync the directory that holds it. Returns the number +/// of items written. +/// +/// `file` is the file the caller has just created at `path` with +/// `create_new`. Unless this returns `Ok`, the file is removed while `path` +/// still names it, including when the returned future is dropped before it +/// finishes. On Unix, when the file's device and inode cannot be read (there +/// is no spare file descriptor), this fails before it writes a line and +/// unlinks `path` without checking what it names. On other targets `path` is +/// always unlinked without that check. +/// +/// `next_page` is called with the last key of the previous page (`None` for +/// the first) and answers one page of items and its last key; a page without +/// a last key is the final one. +/// +/// # Errors +/// +/// `Export item count exceeds maximum` when the table holds more than +/// `max_items` items, `Cannot write export file` when the file's identity +/// cannot be read or a write, the flush or a sync fails, and any error +/// `next_page` returns. +pub(crate) async fn write_export_file( + file: &mut tokio::fs::File, + path: &Path, + max_items: u64, + mut next_page: F, +) -> Result +where + F: FnMut(Option) -> Fut, + Fut: Future, Option), DynamoDbError>>, +{ + let mut created = RemoveOnDrop::new(path); + created.record_identity(file).map_err(|_| cannot_write())?; + + let mut item_count: i64 = 0; + let mut exclusive_start_key: Option = None; + loop { + let (items, last_key) = next_page(exclusive_start_key.take()).await?; + + item_count += i64::from(u16::try_from(items.len()).unwrap_or(u16::MAX)); + + if u64::try_from(item_count).unwrap_or(u64::MAX) > max_items { + return Err(DynamoDbError::ValidationException(format!( + "Export item count exceeds maximum ({max_items})" + ))); + } + + for item in &items { + // One encoding for the export line and the backup data file. + let line = extenddb_core::backup_format::encode_item_line(item).map_err(|e| { + tracing::error!(internal_error = %e, "failed to serialize export item"); + DynamoDbError::InternalServerError("Internal server error".to_owned()) + })?; + file.write_all(&line).await.map_err(|_| cannot_write())?; + } + + if last_key.is_none() { + break; + } + exclusive_start_key = last_key; + } + + // Waits for the last write and returns its error, which `sync_all` would + // not (see the module comment). + file.flush().await.map_err(|_| cannot_write())?; + // Defence in depth, no test: an fsync failure cannot be injected without + // a faulty filesystem, and the fsync matters only across a crash or a + // power loss. + file.sync_all().await.map_err(|_| cannot_write())?; + sync_parent(path).await.map_err(|_| cannot_write())?; + + created.disarm(); + Ok(item_count) +} + +fn cannot_write() -> DynamoDbError { + DynamoDbError::ValidationException("Cannot write export file".to_owned()) +} + +/// Fsync the directory that holds `path`, so the entry `create_new` made for +/// the file survives a crash. Opening the directory needs read permission on +/// it. An error `can_skip_dir_sync` accepts is logged, and the directory is +/// left unsynced. Windows has no directory handle to sync. +async fn sync_parent(path: &Path) -> std::io::Result<()> { + #[cfg(unix)] + { + let dir = match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + }; + let synced = match tokio::fs::File::open(dir).await { + Ok(handle) => handle.sync_all().await.map_err(|e| (DirStep::Fsync, e)), + Err(e) => Err((DirStep::Open, e)), + }; + if let Err((step, e)) = synced { + if !can_skip_dir_sync(step, &e) { + return Err(e); + } + tracing::warn!( + path = %dir.display(), + error = %e, + "could not sync the directory of an export file; the export completes without it" + ); + } + } + #[cfg(not(unix))] + { + let _ = path; + } + Ok(()) +} + +/// The call of the directory sync that failed. +#[cfg(unix)] +#[derive(Clone, Copy, Debug)] +enum DirStep { + /// Opening the directory for reading. + Open, + /// The directory's fsync. + Fsync, +} + +/// Whether an export completes without its directory sync after `step` +/// failed with `err`: the directory cannot be opened (`EACCES`, `EPERM`), or +/// its filesystem has no fsync for directories (`EINVAL`, `ENOTSUP`, +/// `EOPNOTSUPP`, `EBADF`). Every other error, `EIO` among them, fails the +/// export. +#[cfg(unix)] +fn can_skip_dir_sync(step: DirStep, err: &std::io::Error) -> bool { + let Some(code) = err.raw_os_error() else { + return false; + }; + let skipped: &[i32] = match step { + DirStep::Open => &[libc::EACCES, libc::EPERM], + // `ENOTSUP` and `EOPNOTSUPP` are one number on Linux and two on macOS. + DirStep::Fsync => &[libc::EINVAL, libc::ENOTSUP, libc::EOPNOTSUPP, libc::EBADF], + }; + skipped.contains(&code) +} + +/// Removes the export file from `Drop` unless disarmed. Every error return of +/// [`write_export_file`], its future being dropped at any await, and a panic +/// end here. The check and the unlink are synchronous because `Drop` cannot +/// await. A failure of either is logged: the export has already failed with +/// an error of its own, and the file stays at the path. +struct RemoveOnDrop { + path: PathBuf, + /// The device and inode of the file this export created, once recorded. + #[cfg(unix)] + created: Option<(u64, u64)>, + armed: bool, +} + +impl RemoveOnDrop { + fn new(path: &Path) -> Self { + Self { + path: path.to_path_buf(), + #[cfg(unix)] + created: None, + armed: true, + } + } + + /// Record the device and inode of `file`, the open export file, so the + /// guard unlinks `path` only while it names that file. Reading them from + /// the open file takes a duplicate of its descriptor. Nothing to record + /// on other targets. + fn record_identity(&mut self, file: &tokio::fs::File) -> std::io::Result<()> { + #[cfg(unix)] + { + use std::os::fd::AsFd; + let file = std::fs::File::from(file.as_fd().try_clone_to_owned()?); + self.created = Some(file_identity(&file.metadata()?)); + } + #[cfg(not(unix))] + { + let _ = file; + } + Ok(()) + } + + fn disarm(&mut self) { + self.armed = false; + } + + /// Whether `path` still names the file this export created. Without a + /// recorded identity, and on targets other than Unix, the name is taken + /// for the export's own. + fn names_the_created_file(&self) -> std::io::Result { + #[cfg(unix)] + if let Some(created) = self.created { + let now = file_identity(&std::fs::symlink_metadata(&self.path)?); + return Ok(now == created); + } + Ok(true) + } +} + +impl Drop for RemoveOnDrop { + fn drop(&mut self) { + if !self.armed { + return; + } + let removed = match self.names_the_created_file() { + Ok(true) => std::fs::remove_file(&self.path), + // Another file has the name: this export's file is no longer there. + Ok(false) => return, + Err(e) => Err(e), + }; + match removed { + Ok(()) => {} + // Nothing is at the path. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => tracing::warn!( + path = %self.path.display(), + error = %e, + "could not remove the file of a failed export" + ), + } + } +} + +/// The device and inode `meta` reports, which together name one file. +#[cfg(unix)] +fn file_identity(meta: &std::fs::Metadata) -> (u64, u64) { + use std::os::unix::fs::MetadataExt; + (meta.dev(), meta.ino()) +} + +#[cfg(test)] +#[path = "export_file_tests.rs"] +mod tests; diff --git a/crates/engine/src/export_file_tests.rs b/crates/engine/src/export_file_tests.rs new file mode 100644 index 000000000..836861fdb --- /dev/null +++ b/crates/engine/src/export_file_tests.rs @@ -0,0 +1,671 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The export file is complete when the export answers, and an export that +//! does not complete leaves nothing at its path. + +use super::*; +use extenddb_core::types::AttributeValue; + +/// Exports per run of [`the_file_is_complete_when_the_export_answers`]. +const EXPORTS: usize = 200; + +/// A fresh directory under the temp dir, removed when dropped. +struct Dir(PathBuf); + +impl Dir { + fn new() -> Self { + let dir = std::env::temp_dir().join(format!("eb-export-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn join(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn item(n: usize) -> Item { + Item::from([ + ("pk".to_owned(), AttributeValue::S(format!("item-{n}"))), + ("data".to_owned(), AttributeValue::S(format!("value-{n}"))), + ]) +} + +fn items(n: usize) -> Vec { + (0..n).map(item).collect() +} + +/// The bytes the export writes for `items`. +fn bytes_of(items: &[Item]) -> usize { + items + .iter() + .map(|i| { + extenddb_core::backup_format::encode_item_line(i) + .unwrap() + .len() + }) + .sum() +} + +/// Create the export file as the handler does, with `create_new`, so a file +/// left at `path` by an earlier export makes this fail. +async fn create(path: &Path) -> tokio::fs::File { + tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .await + .expect("nothing is at the path") +} + +type Page = Result<(Vec, Option), DynamoDbError>; + +/// A page source that answers `pages` in order, each with a last key except +/// the final one. +fn pages(pages: Vec>) -> impl FnMut(Option) -> std::future::Ready { + let mut pages = pages.into_iter().peekable(); + move |_| { + let page = pages.next().expect("no page is asked for after the last"); + let more = pages.peek().is_some(); + std::future::ready(Ok((page, more.then(Item::new)))) + } +} + +fn assert_no_file(path: &Path) { + let found = std::fs::symlink_metadata(path); + assert!( + found + .as_ref() + .is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound), + "the export left {found:?} at its path" + ); +} + +/// The file holds every line when the export answers. The last write runs on +/// the blocking pool, so an export that answers without waiting for it is +/// found short by a read made at once. +#[tokio::test] +async fn the_file_is_complete_when_the_export_answers() { + let dir = Dir::new(); + let items = items(3); + let expected = u64::try_from(bytes_of(&items)).unwrap(); + for n in 0..EXPORTS { + let path = dir.join(&format!("export-{n}.json")); + let mut file = create(&path).await; + let count = write_export_file(&mut file, &path, 3, pages(vec![items.clone()])) + .await + .unwrap(); + let size = std::fs::metadata(&path).unwrap().len(); + assert_eq!(size, expected, "export {n} of {EXPORTS} was short"); + let lines = std::fs::read_to_string(&path).unwrap().lines().count(); + assert_eq!((count, lines), (3, 3), "export {n} of {EXPORTS}"); + } +} + +/// An export that fails after writing lines (here on the item limit, passed +/// on the second page) leaves nothing at its path, so a second export to the +/// same path is not refused as an existing file. +#[tokio::test] +async fn an_export_over_the_item_limit_leaves_no_file_and_the_path_can_be_reused() { + let dir = Dir::new(); + let path = dir.join("export.json"); + let pages_of_two = || pages(vec![items(2), items(2)]); + + let mut file = create(&path).await; + let err = write_export_file(&mut file, &path, 3, pages_of_two()) + .await + .unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(m) + if m == "Export item count exceeds maximum (3)"), + "{err:?}" + ); + drop(file); + assert_no_file(&path); + + let mut file = create(&path).await; + let count = write_export_file(&mut file, &path, 4, pages_of_two()) + .await + .unwrap(); + assert_eq!(count, 4); + assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 4); +} + +/// A scan that fails after a page was written leaves no file either. +#[tokio::test] +async fn an_export_whose_scan_fails_leaves_no_file() { + let dir = Dir::new(); + let path = dir.join("export.json"); + let mut file = create(&path).await; + let mut calls = 0; + let err = write_export_file(&mut file, &path, 10, |_| { + calls += 1; + std::future::ready(if calls == 1 { + Ok((items(2), Some(Item::new()))) + } else { + Err(DynamoDbError::InternalServerError( + "Internal server error".to_owned(), + )) + }) + }) + .await + .unwrap_err(); + assert!( + matches!(err, DynamoDbError::InternalServerError(_)), + "{err:?}" + ); + assert_no_file(&path); +} + +/// An export whose future is dropped part way, as when its client +/// disconnects, leaves no file. +#[tokio::test] +async fn a_dropped_export_leaves_no_file() { + let dir = Dir::new(); + let path = dir.join("export.json"); + let mut file = create(&path).await; + let second_page_asked = tokio::sync::Notify::new(); + let mut calls = 0; + let export = write_export_file(&mut file, &path, 10, |_| { + calls += 1; + let first = calls == 1; + let asked = &second_page_asked; + async move { + if first { + Ok((items(2), Some(Item::new()))) + } else { + asked.notify_one(); + std::future::pending().await + } + } + }); + tokio::select! { + result = export => panic!("the second page never answers, got {result:?}"), + () = second_page_asked.notified() => {} + } + // `select!` has dropped the export's future. + assert_no_file(&path); +} + +#[cfg(unix)] +mod unix { + use std::os::unix::fs::PermissionsExt; + + use super::*; + + /// Set in the child process [`run_in_child`] starts, to the name of the + /// test it runs. + const CHILD_TEST: &str = "EXTENDDB_TEST_CHILD"; + + fn is_cannot_write(err: &DynamoDbError) -> bool { + matches!(err, DynamoDbError::ValidationException(m) if m == "Cannot write export file") + } + + /// Whether this process is the child [`run_in_child`] started for `name`. + fn is_child(name: &str) -> bool { + std::env::var(CHILD_TEST).is_ok_and(|n| n == name) + } + + /// Run the test `name` again in a child process (this test binary with + /// `--exact`) and assert that exactly that test ran and passed. For a test + /// that changes process-wide state, here a resource limit, which must not + /// reach the tests running beside it. + fn run_in_child(name: &str) { + let output = std::process::Command::new(std::env::current_exe().expect("test binary")) + .args([name, "--exact", "--nocapture", "--test-threads=1"]) + .env(CHILD_TEST, name) + .output() + .expect("spawn the child test process"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed"), + "child {name} failed ({}):\n--- stdout\n{stdout}\n--- stderr\n{}", + output.status, + String::from_utf8_lossy(&output.stderr) + ); + } + + /// Set this process's soft file size limit to `bytes`, or back to the + /// hard limit for `None`, and ignore `SIGXFSZ`, so a write past the limit + /// fails with `EFBIG` instead of ending the process. The hard limit is + /// kept, and the soft limit may be raised up to it. + fn limit_file_size(bytes: Option) { + // SAFETY: plain libc calls on a valid, initialised struct; only the + // child process this test runs in calls them. + unsafe { + libc::signal(libc::SIGXFSZ, libc::SIG_IGN); + let mut limit: libc::rlimit = std::mem::zeroed(); + assert_eq!(libc::getrlimit(libc::RLIMIT_FSIZE, &raw mut limit), 0); + limit.rlim_cur = bytes.map_or(limit.rlim_max, |bytes| bytes as libc::rlim_t); + assert_eq!( + libc::setrlimit(libc::RLIMIT_FSIZE, &raw const limit), + 0, + "setrlimit: {}", + std::io::Error::last_os_error() + ); + } + } + + /// Set this process's soft limit on open files to `count`, keeping the + /// hard limit, and return the soft limit it replaced. + fn set_open_files_limit(count: libc::rlim_t) -> libc::rlim_t { + // SAFETY: plain libc calls on a valid, initialised struct; only the + // child process this test runs in calls them. + unsafe { + let mut limit: libc::rlimit = std::mem::zeroed(); + assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit), 0); + let replaced = limit.rlim_cur; + limit.rlim_cur = count; + assert_eq!( + libc::setrlimit(libc::RLIMIT_NOFILE, &raw const limit), + 0, + "setrlimit: {}", + std::io::Error::last_os_error() + ); + replaced + } + } + + fn effective_uid_is_root() -> bool { + // SAFETY: geteuid has no preconditions. + unsafe { libc::geteuid() == 0 } + } + + /// The warnings logged on this thread while the guard [`Warnings::capture`] + /// returns is held, one line of `name=value` fields each. + #[derive(Clone, Default)] + struct Warnings(std::sync::Arc>>); + + impl Warnings { + fn capture() -> (Self, tracing::subscriber::DefaultGuard) { + let warnings = Self::default(); + let guard = tracing::subscriber::set_default(warnings.clone()); + (warnings, guard) + } + + fn lines(&self) -> Vec { + self.0.lock().unwrap().clone() + } + } + + impl tracing::Subscriber for Warnings { + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + *metadata.level() == tracing::Level::WARN + } + + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + + fn event(&self, event: &tracing::Event<'_>) { + let mut line = String::new(); + event.record(&mut Fields(&mut line)); + self.0.lock().unwrap().push(line); + } + + fn enter(&self, _: &tracing::span::Id) {} + + fn exit(&self, _: &tracing::span::Id) {} + } + + /// Writes an event's fields as `name=value` pairs. + struct Fields<'a>(&'a mut String); + + impl tracing::field::Visit for Fields<'_> { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + use std::fmt::Write as _; + let _ = write!(self.0, "{}={value:?} ", field.name()); + } + } + + /// A full disk on the last line, without root or a mount: past + /// `RLIMIT_FSIZE` a write fails with `EFBIG`, as one on a full + /// filesystem fails with `ENOSPC`. The limit falls inside the last line, + /// so the failing write is the last one, whose error tokio reports only + /// to a flush: `sync_all` waits for that write but does not return its + /// error. The export answers `Cannot write export file` and leaves no + /// file. The test runs in a child process because the limit applies to + /// the whole process. + #[tokio::test] + async fn a_write_that_fails_on_the_last_line_answers_cannot_write_and_leaves_no_file() { + const NAME: &str = "export_file::tests::unix::\ + a_write_that_fails_on_the_last_line_answers_cannot_write_and_leaves_no_file"; + if !is_child(NAME) { + run_in_child(NAME); + return; + } + let dir = Dir::new(); + let path = dir.join("export.json"); + let items = items(3); + let first_two = u64::try_from(bytes_of(&items[..2])).unwrap(); + let mut file = create(&path).await; + limit_file_size(Some(first_two + 4)); + let err = write_export_file(&mut file, &path, 3, pages(vec![items])) + .await + .unwrap_err(); + assert!(is_cannot_write(&err), "{err:?}"); + assert_no_file(&path); + } + + /// A write that fails before the last line, followed by writes that + /// succeed, as when space is freed between two pages: the limit falls + /// inside the second line of the first page and is raised again before + /// the second page. tokio reports the failed write's error to the next + /// write, and the export answers `Cannot write export file` and leaves no + /// file. The flush reports only the last write's error, so an export that + /// ignored the error of each write would answer with lines missing. The + /// test runs in a child process because the limit applies to the whole + /// process. + #[tokio::test] + async fn a_write_that_fails_before_the_last_line_answers_cannot_write_and_leaves_no_file() { + const NAME: &str = "export_file::tests::unix::\ + a_write_that_fails_before_the_last_line_answers_cannot_write_and_leaves_no_file"; + if !is_child(NAME) { + run_in_child(NAME); + return; + } + let dir = Dir::new(); + let path = dir.join("export.json"); + let page = items(3); + let inside_second_line = u64::try_from(bytes_of(&page[..1])).unwrap() + 4; + let mut file = create(&path).await; + let mut calls = 0; + let err = write_export_file(&mut file, &path, 10, |_| { + calls += 1; + let first = calls == 1; + limit_file_size(first.then_some(inside_second_line)); + std::future::ready(Ok((page.clone(), first.then(Item::new)))) + }) + .await + .unwrap_err(); + assert!(is_cannot_write(&err), "{err:?}"); + assert_no_file(&path); + } + + /// A directory without read permission (`0300`) cannot be opened for its + /// sync, although the file can be created and written in it (write and + /// search permission). The export logs a warning and answers with its + /// file complete, without the directory sync. Root bypasses that + /// permission, so the test is skipped as root. + #[tokio::test] + async fn a_directory_that_cannot_be_read_is_not_synced_and_the_export_completes() { + if effective_uid_is_root() { + eprintln!( + "SKIP a_directory_that_cannot_be_read_is_not_synced_and_the_export_completes: \ + running as root" + ); + return; + } + let (warnings, _capture) = Warnings::capture(); + let dir = Dir::new(); + let write_only = dir.join("write-only"); + std::fs::create_dir(&write_only).unwrap(); + std::fs::set_permissions(&write_only, std::fs::Permissions::from_mode(0o300)).unwrap(); + let path = write_only.join("export.json"); + let items = items(3); + let mut file = create(&path).await; + let result = write_export_file(&mut file, &path, 3, pages(vec![items.clone()])).await; + drop(file); + // Search permission is enough to read the file by its path. + let written = std::fs::read(&path).map(|bytes| bytes.len()); + // Restored before any assert, so `Dir` can remove the directory. + std::fs::set_permissions(&write_only, std::fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(result.unwrap(), 3); + assert_eq!(written.unwrap(), bytes_of(&items)); + let logged = warnings.lines(); + assert!( + logged.iter().any(|line| { + line.contains("could not sync the directory of an export file") + && line.contains("Permission denied") + }), + "{logged:?}" + ); + } + + fn os_error(code: i32) -> std::io::Error { + std::io::Error::from_raw_os_error(code) + } + + /// A directory that cannot be opened for its sync is left unsynced. + #[test] + fn a_directory_that_cannot_be_opened_is_not_synced() { + for code in [libc::EACCES, libc::EPERM] { + assert!(can_skip_dir_sync(DirStep::Open, &os_error(code)), "{code}"); + } + } + + /// A directory whose filesystem has no fsync for directories is left + /// unsynced. + #[test] + fn a_directory_without_an_fsync_is_not_synced() { + for code in [libc::EINVAL, libc::ENOTSUP, libc::EOPNOTSUPP, libc::EBADF] { + assert!(can_skip_dir_sync(DirStep::Fsync, &os_error(code)), "{code}"); + } + } + + /// `EIO` and every other error of the directory sync fail the export, + /// including an error that is accepted only at the other step and an + /// error without a number. + #[test] + fn an_io_error_or_any_other_directory_sync_error_fails_the_export() { + for (step, code) in [ + (DirStep::Open, libc::EIO), + (DirStep::Fsync, libc::EIO), + (DirStep::Open, libc::ENOENT), + (DirStep::Open, libc::EINVAL), + (DirStep::Fsync, libc::EACCES), + (DirStep::Fsync, libc::ENOSPC), + ] { + assert!(!can_skip_dir_sync(step, &os_error(code)), "{step:?} {code}"); + } + let no_number = std::io::Error::other("background task failed"); + assert!(!can_skip_dir_sync(DirStep::Fsync, &no_number)); + } + + /// Export A's file is removed by someone else while A runs (an operator + /// who takes it for a leftover), and export B creates its own file at the + /// same path. When A then fails, its guard finds that the path names + /// another file and leaves it, so B answers with its file in place. + #[tokio::test] + async fn a_failing_export_leaves_the_file_of_another_export_at_its_path() { + use tokio::sync::Notify; + + let dir = Dir::new(); + let path = dir.join("export.json"); + + let a_paused = Notify::new(); + let a_resume = Notify::new(); + let a_done = Notify::new(); + let b_paused = Notify::new(); + let b_resume = Notify::new(); + + let mut file_a = create(&path).await; + let mut a_calls = 0; + let export_a = write_export_file(&mut file_a, &path, 10, |_| { + a_calls += 1; + let first = a_calls == 1; + let (paused, resume) = (&a_paused, &a_resume); + async move { + if first { + return Ok((items(2), Some(Item::new()))); + } + paused.notify_one(); + resume.notified().await; + Err(DynamoDbError::InternalServerError( + "Internal server error".to_owned(), + )) + } + }); + let export_a = async { + let result = export_a.await; + a_done.notify_one(); + result + }; + + let mut b_lines = None; + let other = async { + a_paused.notified().await; + std::fs::remove_file(&path).unwrap(); + let mut file_b = create(&path).await; + let mut b_calls = 0; + let export_b = write_export_file(&mut file_b, &path, 10, |_| { + b_calls += 1; + let first = b_calls == 1; + let (paused, resume) = (&b_paused, &b_resume); + async move { + if first { + return Ok((items(2), Some(Item::new()))); + } + paused.notify_one(); + resume.notified().await; + Ok((vec![item(9)], None)) + } + }); + let driver = async { + b_paused.notified().await; + a_resume.notify_one(); + a_done.notified().await; + b_resume.notify_one(); + }; + let (result_b, ()) = tokio::join!(export_b, driver); + b_lines = std::fs::read_to_string(&path) + .ok() + .map(|s| s.lines().count()); + result_b + }; + + let (result_a, result_b) = tokio::join!(export_a, other); + assert!(result_a.is_err(), "export A fails: {result_a:?}"); + assert_eq!(result_b.as_ref().ok(), Some(&3), "export B answers Ok(3)"); + assert_eq!( + b_lines, + Some(3), + "export B answered Ok(3) but its path holds {b_lines:?} lines (None: no file)" + ); + } + + /// Recording the file's device and inode takes a duplicate of its + /// descriptor, which std places at 3 or above. With the soft limit on + /// open files at 3 the duplicate fails, so the export answers `Cannot + /// write export file` before it reads a page, and the guard, which then + /// has no identity to compare, unlinks the path. The test runs in a child + /// process because the limit applies to the whole process. + #[tokio::test] + async fn an_unreadable_file_identity_fails_the_export_before_any_page_and_leaves_no_file() { + const NAME: &str = "export_file::tests::unix::\ + an_unreadable_file_identity_fails_the_export_before_any_page_and_leaves_no_file"; + if !is_child(NAME) { + run_in_child(NAME); + return; + } + let dir = Dir::new(); + let path = dir.join("export.json"); + let mut file = create(&path).await; + let mut pages_asked = 0; + let replaced = set_open_files_limit(3); + let result = write_export_file(&mut file, &path, 10, |_| { + pages_asked += 1; + std::future::ready(Ok((items(2), None))) + }) + .await; + // Restored before any assert, so `Dir` can remove the directory. + set_open_files_limit(replaced); + let err = result.unwrap_err(); + assert!(is_cannot_write(&err), "{err:?}"); + assert_eq!(pages_asked, 0, "the export read a page"); + assert_no_file(&path); + } + + /// The export's file is moved to another name while the export runs, and + /// a symlink to it is put at the path. The guard compares the device and + /// inode of the symlink itself, not of the file it points to, so the + /// failed export leaves the symlink at the path. + #[tokio::test] + async fn a_symlink_put_at_the_path_of_a_failing_export_is_left() { + let dir = Dir::new(); + let path = dir.join("export.json"); + let moved = dir.join("moved.json"); + let mut file = create(&path).await; + let mut calls = 0; + let result = write_export_file(&mut file, &path, 10, |_| { + calls += 1; + std::future::ready(if calls == 1 { + Ok((items(2), Some(Item::new()))) + } else { + std::fs::rename(&path, &moved).unwrap(); + std::os::unix::fs::symlink(&moved, &path).unwrap(); + Err(DynamoDbError::InternalServerError( + "Internal server error".to_owned(), + )) + }) + }) + .await; + assert!(result.is_err(), "{result:?}"); + let left = std::fs::symlink_metadata(&path); + assert!( + left.as_ref() + .is_ok_and(|meta| meta.file_type().is_symlink()), + "the symlink is still at the path: {left:?}" + ); + } + + /// When the guard's unlink fails, the failed export leaves its file at + /// the path and the server logs a warning with the error. Here the + /// directory loses write permission while the export runs, so the unlink + /// fails with `EACCES`. Root bypasses that permission, so the test is + /// skipped as root. + #[tokio::test] + async fn a_failed_export_whose_unlink_fails_leaves_its_file_and_logs_a_warning() { + if effective_uid_is_root() { + eprintln!( + "SKIP a_failed_export_whose_unlink_fails_leaves_its_file_and_logs_a_warning: \ + running as root" + ); + return; + } + let (warnings, _capture) = Warnings::capture(); + let dir = Dir::new(); + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + let path = sub.join("export.json"); + let mut file = create(&path).await; + let mut calls = 0; + let result = write_export_file(&mut file, &path, 10, |_| { + calls += 1; + std::future::ready(if calls == 1 { + Ok((items(2), Some(Item::new()))) + } else { + std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o500)).unwrap(); + Err(DynamoDbError::InternalServerError( + "Internal server error".to_owned(), + )) + }) + }) + .await; + drop(file); + let left = std::fs::symlink_metadata(&path); + // Restored before any assert, so `Dir` can remove the directory. + std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o700)).unwrap(); + assert!(result.is_err(), "{result:?}"); + assert!(left.is_ok(), "the file is still at its path: {left:?}"); + let logged = warnings.lines(); + assert!( + logged.iter().any(|line| { + line.contains("could not remove the file of a failed export") + && line.contains("Permission denied") + }), + "{logged:?}" + ); + } +} diff --git a/crates/engine/src/import_export.rs b/crates/engine/src/import_export.rs index 7dd003761..b56ea9b06 100755 --- a/crates/engine/src/import_export.rs +++ b/crates/engine/src/import_export.rs @@ -185,7 +185,10 @@ pub async fn handle_import_table( /// Handle an `ExportTableToPointInTime` request. /// -/// Reads all items from the table and writes them to a local file. +/// Reads all items from the table and writes them to a local file. It answers +/// `COMPLETED` once the file is complete and synced to disk, and an export +/// that fails leaves no file at its `FilePath`, apart from a file the server +/// could not remove and the other cases the `export_file` module lists. /// /// # Errors /// @@ -271,49 +274,32 @@ pub async fn handle_export_table( } })?; - let mut item_count: i64 = 0; - let max_export_items = ctx.limits.max_export_item_count; - let mut exclusive_start_key: Option = None; - loop { - let (items, last_key) = ctx - .storage - .scan( - &key_info, - Some(1000), - exclusive_start_key.as_ref(), - None, - None, - None, - ) - .await - .map_err(storage_err_to_dynamo)?; - - item_count += i64::from(u16::try_from(items.len()).unwrap_or(u16::MAX)); - - if u64::try_from(item_count).unwrap_or(u64::MAX) > max_export_items { - return Err(DynamoDbError::ValidationException(format!( - "Export item count exceeds maximum ({max_export_items})" - ))); - } - - for item in &items { - // One encoding for the export line and the backup data file. - let line = extenddb_core::backup_format::encode_item_line(item).map_err(|e| { - tracing::error!(internal_error = %e, "failed to serialize export item"); - DynamoDbError::InternalServerError("Internal server error".to_owned()) - })?; - tokio::io::AsyncWriteExt::write_all(&mut file, &line) - .await - .map_err(|_| { - DynamoDbError::ValidationException("Cannot write export file".to_owned()) - })?; - } - - if last_key.is_none() { - break; - } - exclusive_start_key = last_key; - } + // The file at `output_path` is this export's own: `create_new` made it. + // `write_export_file` answers once every line is flushed and synced, and + // on any error or a dropped future removes the file while `output_path` + // still names it. + let item_count = crate::export_file::write_export_file( + &mut file, + &output_path, + ctx.limits.max_export_item_count, + |exclusive_start_key: Option| { + let (storage, key_info) = (&ctx.storage, &key_info); + async move { + storage + .scan( + key_info, + Some(1000), + exclusive_start_key.as_ref(), + None, + None, + None, + ) + .await + .map_err(storage_err_to_dynamo) + } + }, + ) + .await?; let end_time = epoch_seconds(); let export_arn = format!("{}:export/{}", input.table_arn, uuid::Uuid::new_v4()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 74083fbfa..110dd79c4 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,6 +18,7 @@ mod describe_endpoints; mod describe_limits; mod describe_table; mod expected; +mod export_file; mod expression_helpers; mod get_item; mod import_export; From 474dafa65f061f070e0ad434f3327e7d3e6e80c3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:52:57 +0000 Subject: [PATCH 2/2] docs: describe what a failed export leaves behind, and fix the export error headings The troubleshooting entry for "Cannot write export file" said that parent directories are created automatically. Only the account directory, //, is created; an export whose parent directory is missing is refused with "Parent directory does not exist or is not accessible". The entry now says which directory is created and what the error covers (a write, the flush, the file sync or the directory sync), and that on macOS some network volumes, such as SMB mounts, refuse the F_FULLFSYNC the server syncs the file with. A separate entry covers "Cannot create export file", which the open answers when the file cannot be created in an existing directory. The Import/Export Errors section opens with what an export can leave at its FilePath and when it completes without its directory sync. A failed export removes its file, so the same FilePath can be used again. A server that stops during an export can leave a partial file, a request cancelled while the file is being created can leave an empty one, and a file the server could not remove stays, with a warning in the server log. The "Export file already exists" entry lists what a leftover file can be, including the file of an export to that FilePath that is still running, and tells the operator to wait for it or use another FilePath before removing anything. The headings "Cannot open source file", "Invalid JSON at line N" and "Cannot write export file" lose a ": " suffix the server does not send. "Source path does not exist: " becomes "Path does not exist or is not accessible", and "Invalid table ARN: " becomes one entry for each message the server sends: "One or more parameter values were invalid: tableArn is not a valid ARN" and "Invalid Request: Table ARN is invalid." The security model's path section says how a failed export removes its file. On Unix it unlinks the path only while the path names the file it created, checked by device and inode, and a file put at the path between the check and the unlink is removed. When the server cannot read the device and inode, the export fails before it writes a line and unlinks the path without the check, as it does on other platforms. The unlink never follows a symlink. --- docs/manuals/10-security-model.md | 10 ++++++ docs/troubleshooting.md | 58 ++++++++++++++++++++++++------- 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index bb7a1c75d..9453de9fa 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -214,6 +214,16 @@ Import/export file paths are validated: - Symlinks detected and rejected, including one planted at the export filename - Export refuses to overwrite an existing file, so it cannot truncate a file it did not create +- An export that fails removes the file it created. On Unix it first checks + that the path still names that file (the same device and inode), and leaves + the path alone when it names another file, such as one a second export + created after the first file was removed. The check and the unlink are two + calls, so a file put at the path between them is removed. If the server + cannot read the file's device and inode (it has no spare file descriptor), + the export fails before it writes a line and unlinks the path without the + check. On other platforms the export unlinks the path without the check. + The unlink never follows a symlink, and a file the server cannot remove + stays, with a warning in the server log - Both operations record the acting account, the operation and the resolved path - Error messages use generic text (no raw paths leaked) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 11a35c1b5..dc44e046d 100755 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -170,9 +170,18 @@ use. Do not use symlinks that point outside the allowed directories. **Cause:** Export refuses to overwrite. Something already exists at the requested `FilePath`, so the export stopped rather than truncating it. A symlink -at that path produces the same error rather than being followed. - -**Fix:** Export to a new filename, or remove the existing file first. +at that path produces the same error rather than being followed. A failed export +removes its file, so what is there is a completed export, an export to that +`FilePath` that is still running, a file from somewhere else, a partial file +from a server that stopped during an export, an empty file from a request +cancelled while the file was being created, or the file of a failed export that +the server could not remove (the server logs a warning when that happens). + +**Fix:** Export to a new filename. If an export to that `FilePath` may still be +running, for example from a client that retried or from a second client, wait +for it to answer or use another `FilePath` before you remove anything: removing +its file makes it answer `COMPLETED` with no file at its `FilePath`. Otherwise +remove the existing file first. ### `Failed to daemonize: ` @@ -860,36 +869,61 @@ The error log line names the exact relations for one leaked table and gives this ## Import/Export Errors -### `Source path does not exist: ` +An export that fails removes its file, so it can be retried with the same +`FilePath`. A server that stops during an export can still leave a partial file +there, a request cancelled while the file is being created can leave an empty +one, and a file the server could not remove stays where it is; the server logs a +warning with the path and the error when that happens. + +An export syncs its file and the directory that holds it before it answers +`COMPLETED`. When the server cannot open that directory (for example, it can +write to the directory but not read it) or the filesystem cannot sync a +directory, the export completes without the directory sync and the server logs +a warning. Without that sync, a crash of the host soon after the answer can lose +the file's directory entry. + +### `Path does not exist or is not accessible` -**Cause:** The `FileSource.Path` in an `ImportTable` request points to a file or directory that does not exist on the server's filesystem. +**Cause:** The `FileSource.Path` in an `ImportTable` request points to a file or directory that does not exist on the server's filesystem, or that the extenddb process cannot reach. **Fix:** Verify the path is correct and accessible to the extenddb process. Paths are relative to the server's working directory. -### `Cannot open source file: ` +### `Cannot open source file` **Cause:** The import source file exists but cannot be opened (permission denied, is a directory, etc.). **Fix:** Check file permissions. The extenddb process must have read access to the file. -### `Invalid JSON at line N: ` +### `Invalid JSON at line N` **Cause:** A line in the DYNAMODB_JSON import file is not valid JSON. **Fix:** Each line must be a valid JSON object. The format is one item per line: `{"Item": {"pk": {"S": "val"}, ...}}` or bare `{"pk": {"S": "val"}, ...}`. -### `Cannot write export file: ` +### `Cannot create export file` + +**Cause:** The parent directory exists, but the server could not create the file in it: no write permission on the directory, a read-only filesystem, or a full disk. + +**Fix:** Give the extenddb process write access to the destination directory, or free disk space, then export again. -**Cause:** The export destination path is not writable (permission denied, disk full, etc.). +### `Cannot write export file` -**Fix:** Check that the extenddb process has write access to the destination directory. Parent directories are created automatically. +**Cause:** The server created the export file but could not write, flush or sync it, or sync the directory that holds it: a full disk, the file size limit, an I/O error, or the server's limit on open files. On macOS the server syncs the file with `F_FULLFSYNC`, which some network volumes, such as SMB mounts, refuse with `ENOTSUP`, so an export to such a volume gets this error. The export removes the file before it answers. If the server cannot remove it, the file stays and the server logs a warning with the path and the error. -### `Invalid table ARN: ` +**Fix:** Check that the disk has room and that the extenddb process can write to the destination directory, then export again. On macOS, export to a local volume rather than a network volume that refuses `F_FULLFSYNC`. The same `FilePath` can be used, unless the server logged that it could not remove the file; remove that file first. Only the account directory, `//`, is created for you. An export whose parent directory does not exist is refused with `Parent directory does not exist or is not accessible`, so create any other directory in the path first. -**Cause:** The `TableArn` in an `ExportTableToPointInTime` request is not a valid DynamoDB table ARN. +### `One or more parameter values were invalid: tableArn is not a valid ARN` + +**Cause:** The `TableArn` in an `ExportTableToPointInTime` request is not a well-formed DynamoDB table ARN. The server refuses it before authorization. **Fix:** Use the full ARN format: `arn:aws:dynamodb:::table/`. You can get the ARN from `DescribeTable`. +### `Invalid Request: Table ARN is invalid.` + +**Cause:** The `TableArn` in an `ExportTableToPointInTime` request is the ARN of an index, a stream or a backup of a table rather than the ARN of the table. + +**Fix:** Use the table's own ARN, `arn:aws:dynamodb:::table/`, which `DescribeTable` returns. + ## GSI Async Update Behavior ### GSI query returns stale data after a write