Replace a snapshot file by writing a complete new file in its destination directory, synchronizing that staged file, atomically replacing the destination, and then synchronizing the directory. In an agent-written Rust patch, require the caller to distinguish failure before replacement from failure after replacement. Once the new file is visible, a later synchronization error cannot truthfully mean that nothing changed.
This guide implements that sequence for a Linux application with one serialized writer and an existing, trusted parent directory. It suits a small generated configuration or checkpoint whose bytes have already passed application validation. Atomic replacement protects readers from an in-place partial rewrite; synchronization addresses persistence through a system crash. Those are separate properties, and both need explicit review evidence.
Last reviewed: 2026-11-21 (Asia/Shanghai). Sources and runnable example checked on 2026-11-20 UTC, the same local review day.
Decide what a successful snapshot update promises
Write down the observable contract before asking the coding agent to change the file-writing helper. For this example, readers open one pathname and consume the whole snapshot through that handle. A reader that already opened the old file may finish reading the old version; a later open after replacement sees the new version. The update does not require every reader to switch versions simultaneously.
The Linux rename reference documents atomic replacement of an existing destination without an intervening missing-path state. It also explains that open file descriptors remain unaffected by renaming. These semantics motivate the reader test below. They do not make a reader that separately opens several related files observe one consistent generation.
For a successful return, this helper additionally requires successful synchronization of the staged file and its parent directory. Linux’s fsync reference states that synchronizing a file does not necessarily persist its containing directory entry; an explicit directory synchronization is needed. Storage, filesystem and mount behavior still belong in the deployment’s durability assessment.
Keep the scope narrow. The parent directory and its ancestors must remain stable and inaccessible to untrusted writers throughout the operation. The process must serialize updates itself. A second authorized writer could otherwise replace a newer snapshot with older content while each individual replacement remains atomic. Use the site’s concurrency-testing guide when reviewing that separate ownership rule.
Put staging and replacement on the same filesystem
The NamedTempFile reference
provides the two operations needed here: new_in() creates a named temporary file in a specified directory, and persist() atomically replaces an existing target file. Its documentation explicitly warns that persistence across filesystems is unsupported and that persist() synchronizes neither the contents nor the containing directory.
Create the staged file in the actual destination parent. Using a global temporary directory can place it on a different filesystem. A fallback that copies bytes into the live destination would abandon the visibility contract just when an exceptional path is hardest to inspect. Deleting the old destination before moving the new one also creates a missing-file interval and discards the previous version prematurely.
Retain the staged handle while writing and synchronizing. Rust’s File reference
documents that File::create() truncates an existing file, that sync_all() attempts to synchronize content and metadata, and that close errors are ignored by Drop. A direct create-and-write implementation can therefore damage the live snapshot before it knows whether the complete replacement can be written.
The following helper receives a bounded, validated byte slice. Serialization, size admission and content validation happen before calling it. It uses the staged file’s metadata; it does not preserve the old destination’s mode, ownership, ACLs or other attributes. If readers run under another identity, define and apply the intended metadata before synchronizing and installing the staged file, then test reader access explicitly. The existing temporary-file race guide covers secure creation and directory ownership in more detail.
Keep the replacement boundary in the error type
The helper has two failure outcomes. BeforeReplace means this operation has not installed the new snapshot under the stated local-filesystem assumptions. ReplacedButDirectorySyncFailed means replacement succeeded and the new bytes are visible, but the directory synchronization did not confirm the requested persistence step. That second outcome requires reconciliation rather than treating the old version as current.
Create an empty disposable Cargo library project. Put this dependency in its Cargo.toml:
[dependencies]
tempfile = "=3.27.0"
Replace src/lib.rs with the complete implementation and tests below. The Linux condition deliberately limits the example to the platform contract discussed here; zero tests on another operating system would not verify it.
#![cfg(target_os = "linux")]
use std::{fs::File, io::{self, Write}, path::Path};
use tempfile::NamedTempFile;
#[derive(Debug)]
pub enum ReplaceError {
BeforeReplace(io::Error),
ReplacedButDirectorySyncFailed(io::Error),
}
pub fn replace_snapshot(path: &Path, bytes: &[u8]) -> Result<(), ReplaceError> {
replace_with_sync(path, bytes, File::sync_all, File::sync_all)
}
fn replace_with_sync(
path: &Path,
bytes: &[u8],
sync_file: impl FnOnce(&File) -> io::Result<()>,
sync_directory: impl FnOnce(&File) -> io::Result<()>,
) -> Result<(), ReplaceError> {
let before = ReplaceError::BeforeReplace;
let parent = path.parent().filter(|p| !p.as_os_str().is_empty())
.ok_or_else(|| before(io::Error::new(
io::ErrorKind::InvalidInput, "use an explicit parent directory")))?;
let directory = File::open(parent).map_err(before)?;
let mut staged = NamedTempFile::new_in(parent).map_err(before)?;
staged.write_all(bytes).map_err(before)?;
sync_file(staged.as_file()).map_err(before)?;
let _installed = staged.persist(path)
.map_err(|failure| before(failure.error))?;
sync_directory(&directory)
.map_err(ReplaceError::ReplacedButDirectorySyncFailed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs, io::Read};
const OLD: &[u8] = b"version=1\ncomplete=old\n";
const NEW: &[u8] = b"version=2\ncomplete=new\n";
#[test]
fn an_open_reader_keeps_old_bytes_and_a_new_open_gets_new_bytes() {
let dir = tempfile::tempdir_in(".").unwrap();
let path = dir.path().join("snapshot.txt");
fs::write(&path, OLD).unwrap();
let mut old_reader = File::open(&path).unwrap();
replace_snapshot(&path, NEW).unwrap();
let mut previous = Vec::new();
old_reader.read_to_end(&mut previous).unwrap();
assert_eq!(previous, OLD);
assert_eq!(fs::read(&path).unwrap(), NEW);
}
#[test]
fn file_sync_failure_preserves_the_previous_snapshot() {
let dir = tempfile::tempdir_in(".").unwrap();
let path = dir.path().join("snapshot.txt");
fs::write(&path, OLD).unwrap();
let mut directory_sync_called = false;
let result = replace_with_sync(&path, NEW,
|_| Err(io::Error::other("injected file-sync failure")),
|_| { directory_sync_called = true; Ok(()) });
assert!(matches!(result, Err(ReplaceError::BeforeReplace(_))));
assert_eq!(fs::read(&path).unwrap(), OLD);
assert!(!directory_sync_called);
}
#[test]
fn directory_sync_failure_reports_that_replacement_already_happened() {
let dir = tempfile::tempdir_in(".").unwrap();
let path = dir.path().join("snapshot.txt");
fs::write(&path, OLD).unwrap();
let result = replace_with_sync(&path, NEW, File::sync_all,
|_| Err(io::Error::other("injected directory-sync failure")));
assert!(matches!(result,
Err(ReplaceError::ReplacedButDirectorySyncFailed(_))));
assert_eq!(fs::read(&path).unwrap(), NEW);
}
#[test]
fn a_failed_persist_does_not_remove_an_existing_directory() {
let dir = tempfile::tempdir_in(".").unwrap();
let path = dir.path().join("snapshot.txt");
fs::create_dir(&path).unwrap();
fs::write(path.join("sentinel"), OLD).unwrap();
let result = replace_snapshot(&path, NEW);
assert!(matches!(result, Err(ReplaceError::BeforeReplace(_))));
assert_eq!(fs::read(path.join("sentinel")).unwrap(), OLD);
}
}
Opening the directory before staging makes an initial open failure occur before replacement. The trusted, stable parent remains a prerequisite: holding a directory handle does not make the later pathname operations resistant to hostile ancestor changes. This is an application-owned snapshot writer, not a general safe-write interface for attacker-selected paths.
The two injected synchronization functions let the tests force each error boundary. The public function always supplies File::sync_all for both. Review the actual wiring as well as the tests; an error-path test cannot show that an unexecuted durability operation reached physical storage.
Run four checks and one deliberate regression
Run the example in the disposable project using a writable temporary directory:
mkdir -p fixture-tmp
TMPDIR="$PWD/fixture-tmp" cargo test
The example was run on Linux with Rust 1.100.0 and tempfile 3.27.0. All four unit tests passed, the documentation-test phase contained zero tests, and the command exited successfully. The local harness needed a writable project temporary directory because its system temporary directory was unavailable. Record the filesystem and supported runtime when repeating this in your repository.
| Check | Expected observation | What it establishes |
|---|---|---|
| Reader opened before replacement | Its complete bytes remain OLD; a fresh open returns NEW | The update swaps files instead of overwriting the old reader’s file |
| Staged-file synchronization fails | BeforeReplace, old bytes retained, no directory-sync call | Replacement is gated on successful file synchronization |
| Directory synchronization fails | ReplacedButDirectorySyncFailed, new bytes readable | The caller can recognize an already-visible update |
| Target is an existing directory | BeforeReplace, sentinel inside retained | Failure does not trigger deletion or a destructive fallback |
Check that the reader assertion detects a plausible bad patch. In a disposable copy, replace the persist() statement with a direct std::fs::write(path, bytes) call while retaining the rest of the helper. The focused reader test failed in the local negative control: the previously opened reader returned NEW instead of OLD. Restore the replacement implementation afterward. The site’s mutation-testing guide
explains how to use deliberate regressions to evaluate test sensitivity.
These tests verify application-visible behavior and injected failure handling. They do not simulate a power cut, disk-full writeback, controller failure or every possible reader schedule. A process kill also leaves the kernel alive, so restart tests alone cannot establish a power-loss durability claim. Keep any stronger storage guarantee tied to platform-specific evidence.
Reconcile an update that became visible before failure
Make callers handle the outcomes explicitly. On BeforeReplace, report the failed update while continuing to identify the previous snapshot as current, assuming the single-writer contract still holds. Diagnose the underlying I/O error before any retry. A permission error or unsupported synchronization operation needs a deployment fix; copying over the destination is not a repair.
On ReplacedButDirectorySyncFailed, keep the intended generation identifier and inspect the current snapshot under the same writer ownership. Report that the new generation was installed but its persistence step failed. The recovery policy may retry the directory synchronization or schedule controlled recovery after diagnosing the error. It must not blindly publish an older generation or claim that the live file remained unchanged. If the process crashes after replacement and before recording a result, restart recovery likewise needs to inspect the file’s validated generation rather than infer state from a missing success message.
The helper does not create a durable transaction log, coordinate several snapshot files, preserve backups, or implement compare-and-swap. Replacement also leaves hard links and already-open readers referring to their prior objects, as the rename reference describes. If the application needs coordinated generations across several files, use a separate generation-selection design and verify that whole protocol.
Keep this implementation restricted to the assessed Linux local filesystem. The rename documentation warns that NFS failures can be ambiguous because a server may perform a rename before a retry reports failure; the simple BeforeReplace interpretation does not cover that case. Windows replacement and directory synchronization also require their own adapter and tests. Do not expand the supported platform list based on compilation alone.
For the next review, choose one snapshot-writing helper changed by an agent. Require its destination ownership rule, intended metadata, file-sync ordering, directory-sync outcome, and four recorded assertions. Attach the runtime, dependency lock, filesystem class, command and negative-control result. That gives a reviewer a concrete replacement contract to approve and a caller-visible state to recover when the final persistence step fails.
Sources checked
These primary technical references were fetched successfully on 2026-11-20 UTC, corresponding to 2026-11-21 in Asia/Shanghai. They support an evergreen implementation task. The Rust page identified version 1.100.0, and the tempfile page identified version 3.27.0; the Linux pages were from the live man-pages documentation. Local test observations are reported separately above.
- Rust standard library: File
— truncation by
create(), explicit synchronization, file buffering, and ignored errors on drop. - tempfile: NamedTempFile
— directory-local staging, atomic replacement by
persist(), cross-filesystem limits, lack of implicit synchronization, and pathname security caveats. - Linux man-pages: rename(2) — atomic destination replacement, open-descriptor and hard-link behavior, directory constraints, and the NFS failure ambiguity.
- Linux man-pages: fsync(2) — synchronization of file data and metadata, the separate containing-directory requirement, and synchronization errors.