Skip to content

v0.2.0 — Restored Atomicity & Crash Durability

Choose a tag to compare

@LarsArtmann LarsArtmann released this 11 Jul 20:18
· 238 commits to master since this release

The release that made "atomic-write" actually atomic

v0.1.0 shipped with a .bak two-rename pattern that opened a window where the target file didn't exist. A concurrent reader could see ENOENT, and a crash between the two renames left the target missing. The library named "atomic-write" was not atomic.

v0.2.0 fixes this with a single rename(2) on POSIX, adds fsync for real crash durability, and gives each concurrent writer a unique temp file to prevent byte interleaving.

Fixed

  • Removed .bak two-rename pattern — the old atomicRename did path→.bak then tmp→path, opening a window where the target didn't exist. Now a single os.Rename(tmp, path) is one atomic syscall on POSIX and atomically replaces on Windows via MoveFileEx.
  • Concurrent writer corruption — tmpPath was computed before the lock (path + ".tmp"), so two concurrent Write() calls to the same target both truncated and wrote the same staging file, interleaving bytes. Now each writer gets a unique temp file via crypto/rand suffix.
  • Concurrency test couldn't catch the bug — TestConcurrentWriteRACE used identical content from all writers, so byte interleaving was undetectable. Rewritten with 10 writers using divergent content plus an integrity check.
  • "Crash safety" doc claim was false — no fsync was called anywhere. Now writeAndSync() opens the temp file, writes data, calls file.Sync(), and closes. On POSIX, the target directory is also fsync'd after rename.

Added

  • fsync for crash durability — temp file is fsync'd before rename; target directory is fsync'd after rename (POSIX only)
  • Unique temp file names — crypto/rand 4-byte hex suffix prevents concurrent writer staging-file corruption
  • Platform-specific rename — split into rename_unix.go (single rename(2) + directory fsync) and rename_windows.go (retry loop on ERROR_ACCESS_DENIED/ERROR_SHARING_VIOLATION, 5 retries with exponential backoff)
  • writeAndSync(), randomSuffix(), syncDir() internal functions
  • TestWriteLeavesNoLeftoverFiles — verifies no .bak and no .tmp files remain after a successful write

Changed

  • Write() now stages to a unique temp file instead of a shared path + ".tmp"
  • atomicRename() no longer creates .bak files — single os.Rename replaces atomically
  • TestConcurrentWriteRACE rewritten: 10 writers, divergent content, integrity check

Removed

  • TestWriteCreatesBackup — tested the .bak pattern as a feature; the pattern was a bug
  • .bak file creation — no longer created alongside the target

Caveats

  • Windows rename retry loop compiles via build tags but is untested on real Windows hardware
  • No POSIX-equivalent directory fsync on Windows
  • No stale temp file cleanup — crashed writes leave .tmp files (unique names prevent interference but don't self-clean)

Full Changelog: v0.1.1...v0.2.0