How Worktrunk Ensures Data Safety During File Writes: Atomic Operations Explained

Worktrunk guarantees data safety during file writes by never truncating target files directly, instead employing the write_atomically and write_new_atomically helpers defined in src/utils.rs to perform atomic rename-based operations that ensure files are either fully persisted or completely untouched.

Worktrunk is a Rust-based utility designed for reliable data persistence and configuration management. To eliminate the risk of data corruption from partial writes, system crashes, or concurrent access, the codebase implements a rigorous atomic file replacement strategy. This approach fundamentally ensures data safety during file writes by removing any window of vulnerability where a file might exist in an incomplete or inconsistent state.

The Atomic Write Algorithm

According to the Worktrunk source code, the library avoids direct truncating writes to target files. Instead, it implements a six-step atomic write sequence in src/utils.rs (lines 40–84) that guarantees transactional file updates.

Step-by-Step Safety Protocol

  1. Create a temporary file in the target directory. Worktrunk generates a temporary file within the same directory as the destination file. This placement ensures that the final rename operation remains on a single filesystem, preventing cross-filesystem copy operations that could be interrupted.

  2. Write full contents to the temporary file. The complete data payload is written to the temporary file rather than the target.

  3. Preserve original file permissions. If the target file already exists, Worktrunk copies its mode and ownership permissions to the temporary file. This prevents accidental privilege escalation and maintains expected access controls.

  4. Synchronize to storage device. The implementation calls fsync on the temporary file to force the data from OS buffers onto physical storage before proceeding.

  5. Execute atomic rename. The temporary file is renamed over the target file using an atomic POSIX rename operation. On Unix-like systems, this operation either completes entirely or leaves the original file untouched, eliminating half-written states.

  6. Handle new-file race conditions. The write_new_atomically variant uses persist_noclobber to atomically fail if the target file appears between the existence check and the rename operation, preventing accidental overwrites created by concurrent processes.

Critical Safety Mechanisms

The atomic approach in src/utils.rs provides specific technical guarantees that ensure data safety during file writes:

  • Same-directory temporaries: By creating temporary files in the destination directory (rather than /tmp), Worktrunk ensures the rename operation is a simple metadata update rather than a data copy across filesystem boundaries.

  • Permission fidelity: Copying existing file permissions to the temporary file before renaming ensures the final file retains its original security context, preventing permission drifts during updates.

  • Durable persistence: The explicit fsync call before renaming guarantees that data reaches non-volatile storage. Even if the system crashes immediately after the rename, the file contents are fully committed.

  • Atomic visibility: The POSIX atomic rename ensures that other processes never observe a partial file; they see either the complete previous version or the complete new version, with no intermediate state.

  • Exclusive creation: write_new_atomically prevents TOCTOU (Time-of-Check-Time-of-Use) race conditions by failing if the target file was created by another process after the initial existence check.

Implementation Details and Testing

The core atomic write utilities reside in src/utils.rs between lines 40–84. These functions handle the low-level file operations, error cleanup, and permission management required for safe persistence.

Unit tests located at lines 90–130 of the same file verify three critical behaviors:

  • Files are created and replaced without leaving stray temporary files in the directory.
  • write_new_atomically correctly refuses to overwrite existing files.
  • Default permissions of 0600 (owner-only read/write) are applied when creating new files without existing targets.

Real-World Application

All higher-level persistence code throughout Worktrunk delegates to these atomic primitives. For example, src/config/user/persistence.rs calls write_atomically when saving user configuration files, ensuring that every user-visible write benefits from the same crash-resistant guarantees.

Practical Code Examples

Replacing or Creating a File Atomically

Use write_atomically when you need to update an existing file or create a new one safely:

use std::path::Path;
use worktrunk::utils::write_atomically;

// Safely write a configuration file.
let path = Path::new("config.toml");
let content = "[settings]\nenabled = true\n";
write_atomically(path, content).expect("failed to write atomically");

Creating a File Only If It Does Not Exist

Use write_new_atomically to prevent accidental overwrites in concurrent environments:

use std::path::Path;
use worktrunk::utils::write_new_atomically;

let path = Path::new("secret.key");
let key = "super-secret";
write_new_atomically(path, key).expect("file already existed");

Summary

  • Worktrunk ensures data safety during file writes by implementing atomic rename-based writes in src/utils.rs rather than truncating files directly.
  • The algorithm creates same-directory temporary files, preserves permissions, calls fsync for durability, and executes atomic renames to prevent partial write states.
  • Two primary APIs exist: write_atomically for general replacement and write_new_atomically for exclusive creation using persist_noclobber.
  • Comprehensive unit tests verify that no stray temporary files remain, overwrites are prevented when requested, and proper permissions are maintained.
  • All configuration persistence in src/config/user/persistence.rs utilizes these atomic primitives for crash-resistant operation.

Frequently Asked Questions

What happens if Worktrunk crashes during a file write?

If a crash occurs after the fsync but before the rename, the temporary file remains but the original target stays untouched. If the crash happens before fsync, the temporary file may be incomplete but the rename never executes, leaving the existing file in its original valid state. Either way, data safety during file writes is maintained because the atomic rename never exposes partial data.

How does write_new_atomically prevent race conditions?

The write_new_atomically function uses persist_noclobber, which performs an atomic existence check and rename operation. If another process creates the target file between the initial check and the rename attempt, the operation fails rather than overwriting the new file. This prevents TOCTOU vulnerabilities in concurrent environments.

Does Worktrunk preserve file permissions during atomic writes?

Yes. When replacing an existing file, Worktrunk explicitly copies the original file's mode and ownership permissions to the temporary file before renaming. This ensures the final file maintains its expected security context, preventing accidental permission changes during updates.

Where are the atomic write utilities implemented in the codebase?

The atomic write helpers write_atomically and write_new_atomically are implemented in src/utils.rs between lines 40–84. Unit tests verifying these safety guarantees appear at lines 90–130 of the same file. Consumption of these utilities occurs in higher-level modules such as src/config/user/persistence.rs.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →