Repository navigation
v0.2.0 — Restored Atomicity & Crash Durability
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
.baktwo-rename pattern — the oldatomicRenamedidpath→.bakthentmp→path, opening a window where the target didn't exist. Now a singleos.Rename(tmp, path)is one atomic syscall on POSIX and atomically replaces on Windows viaMoveFileEx. - Concurrent writer corruption —
tmpPathwas computed before the lock (path + ".tmp"), so two concurrentWrite()calls to the same target both truncated and wrote the same staging file, interleaving bytes. Now each writer gets a unique temp file viacrypto/randsuffix. - Concurrency test couldn't catch the bug —
TestConcurrentWriteRACEused 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
fsyncwas called anywhere. NowwriteAndSync()opens the temp file, writes data, callsfile.Sync(), and closes. On POSIX, the target directory is alsofsync'd after rename.
Added
fsyncfor crash durability — temp file is fsync'd before rename; target directory is fsync'd after rename (POSIX only)- Unique temp file names —
crypto/rand4-byte hex suffix prevents concurrent writer staging-file corruption - Platform-specific rename — split into
rename_unix.go(singlerename(2)+ directoryfsync) andrename_windows.go(retry loop onERROR_ACCESS_DENIED/ERROR_SHARING_VIOLATION, 5 retries with exponential backoff) writeAndSync(),randomSuffix(),syncDir()internal functionsTestWriteLeavesNoLeftoverFiles— verifies no.bakand no.tmpfiles remain after a successful write
Changed
Write()now stages to a unique temp file instead of a sharedpath + ".tmp"atomicRename()no longer creates.bakfiles — singleos.Renamereplaces atomicallyTestConcurrentWriteRACErewritten: 10 writers, divergent content, integrity check
Removed
TestWriteCreatesBackup— tested the.bakpattern as a feature; the pattern was a bug.bakfile 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
.tmpfiles (unique names prevent interference but don't self-clean)
Full Changelog: v0.1.1...v0.2.0