atomic-write

A single-file Python module providing crash-safe file writes that either fully succeed or leave the previous contents intact — no partial writes, no `.tmp` residue, no torn data visible to readers.

languagepython
entrypointatomic_write.py
test runnerpytest
kindcode

latest run

round May 8, 2026
winner mimo mimo-v2.5-pro
29.0/30 spec 10.0 · qual 19.0
models
7
samples
7
tests
all pass
spend
$0.259

contract

must

  • Python 3.10+, stdlib only — no pip install, no new dependencies.
  • The temp file must live in the same directory as the target so the
  • The file must be fsync'd before close, and the parent directory
  • On any error during the write (disk full, permission, interrupted
  • Concurrent writers to the same target must not corrupt each other:
  • The replace must be atomic from the perspective of any concurrent

out of scope

  • Locking (advisory or mandatory) — readers see atomic transitions; coordination between writers is the caller's job.
  • Backup of previous contents — this is a write primitive, not a versioning system.
  • Append semantics — atomic appends are a separate problem.
  • Network filesystems — POSIX-atomic semantics on NFS/CIFS are filesystem-specific; we target local filesystems (ext4, APFS, btrfs, xfs).

full contract

The raw documents handed to every model and every judge. Read these as the source of truth.

SPEC spec.md what done looks like

atomic_write.py — implementation spec

A single-file Python module providing crash-safe file writes that either fully succeed or leave the previous contents intact — no partial writes, no .tmp residue, no torn data visible to readers.

Library API

atomic_write_text(path, data, *, encoding="utf-8", mode=None) -> None

Atomically write the string data to path.

Parameter Type Default Behaviour
path str or os.PathLike required target path
data str required content to write
encoding str "utf-8" text encoding
mode int or None None if set, chmod the new file to this mode (octal). If None and the target already exists, preserve the target's existing mode; otherwise the new file gets the default umask-derived mode.

Raises:

  • FileNotFoundError — parent directory doesn't exist (no temp residue)
  • IsADirectoryErrorpath exists and is a directory
  • PermissionError — can't create temp file or replace target
  • OSError — any other I/O failure (disk full, etc.); temp file is cleaned up

atomic_write_bytes(path, data, *, mode=None) -> None

Same contract as atomic_write_text but for bytes. No encoding parameter.

Durability requirements

In order, every write must:

  1. Open a temp file in the same directory as path (not tempfile.gettempdir() — cross-filesystem os.replace is not atomic).
  2. Write all bytes.
  3. fsync the file descriptor.
  4. Close the temp file.
  5. os.replace(tmp, path) — atomic rename.
  6. fsync the parent directory (so the rename itself is durable).
  7. If the target already existed and mode is None, the new file inherits the target's pre-existing mode bits.

If any of steps 1–6 raise, the temp file (if it was created) must be removed before the exception propagates.

CLI

python atomic_write.py <path>

Reads stdin (bytes mode, no decoding) and writes the contents to path atomically using the bytes API. Exits 0 on success, non-zero on any error with a message on stderr.

Concurrency contract

Two threads (or processes) calling atomic_write_text(path, ...) with different content must result in path containing one writer's full content, never a mix. No reader at any wall-clock instant sees a truncated or partially-written file.

Symlinks

If path is a symlink, write to the symlink target, not replace the symlink itself. (Common gotcha: naive os.replace would replace the symlink, breaking the link.) The temp file lives next to the resolved target so the rename stays on the same filesystem.

Examples

from atomic_write import atomic_write_text, atomic_write_bytes

atomic_write_text("config.json", '{"version": 2}\n')
atomic_write_bytes("blob.dat", b"\x00\x01\x02")
atomic_write_text("script.sh", "#!/bin/sh\necho hi\n", mode=0o755)
echo '{"version": 2}' | python atomic_write.py config.json

Out of scope

  • Locking (advisory or mandatory) — readers see atomic transitions; coordination between writers is the caller's job.
  • Backup of previous contents — this is a write primitive, not a versioning system.
  • Append semantics — atomic appends are a separate problem.
  • Network filesystems — POSIX-atomic semantics on NFS/CIFS are filesystem-specific; we target local filesystems (ext4, APFS, btrfs, xfs).
PRMT prompt.md what the model reads

Task: implement atomic_write.py

Read SPEC.md in this directory. Implement atomic_write.py exactly per spec: two library functions (atomic_write_text, atomic_write_bytes) plus a CLI entry point for use in shell pipelines.

This task covers only atomic_write.py. Do not create helper modules, test files, or packaging metadata.

Hard constraints

  • Python 3.10+, stdlib only — no pip install, no new dependencies.
  • The temp file must live in the same directory as the target so the final os.replace is on the same filesystem (cross-fs renames are not atomic on POSIX).
  • The file must be fsync'd before close, and the parent directory must be fsync'd after the replace, so a power loss between writes doesn't surface a missing or empty file.
  • On any error during the write (disk full, permission, interrupted syscall, etc.) the temp file must be cleaned up — no .tmp residue on disk after a failed call.
  • Concurrent writers to the same target must not corrupt each other: the result must be the full content of one writer or the other, never a mix.
  • The replace must be atomic from the perspective of any concurrent reader: a reader either sees the old content in full, or the new content in full — never a truncated intermediate.

Deliverable

A single file atomic_write.py at the worktree root that:

  1. Exposes two top-level functions:

    def atomic_write_text(path, data, *, encoding="utf-8", mode=None) -> None: ...
    def atomic_write_bytes(path, data, *, mode=None) -> None: ...
    
  2. Provides a CLI that reads stdin and writes atomically to a target path:

    python atomic_write.py <path>
    

What to do when finished

  1. Run a quick smoke test: write a small file, verify the target exists and matches what you wrote, verify no .tmp files remain in the dir.
  2. State: "Done. Implementation in atomic_write.py."

What NOT to do

  • Do not modify PROMPT.md or SPEC.md.
  • Do not add requirements.txt, pyproject.toml, or any other dependency manifest.
  • Do not write test files; the hidden tests are added later.
RUBR judge_rubric.md how judges score

Judge rubric: atomic-write task

Fill one copy per implementation, saved as output/<label>_rubric.md. Also write output/<label>_scores.json with the structured form (see JUDGE_PROMPT.md).

Implementation reviewed: <label> (e.g. A, B, C) File: implementations/<label>.py

Hard-fail (any miss = fail run)

Cite line numbers when something fails.

  • [ ] atomic_write.py provided as <label>.py
  • [ ] Top-level atomic_write_text(path, data, *, encoding="utf-8", mode=None) matches SPEC signature
  • [ ] Top-level atomic_write_bytes(path, data, *, mode=None) matches SPEC signature
  • [ ] No external Python dependencies (stdlib-only imports)
  • [ ] Temp file created in the same directory as the target (not tempfile.gettempdir() or a hardcoded /tmp)
  • [ ] File is fsync'd before close
  • [ ] Parent directory is fsync'd after os.replace

Hard-fail result: pass / fail If fail, reasons (with line refs):

Spec compliance — score 0–10

Award 1 point per item present and correct. Cite line numbers.

  • [ ] Uses os.replace (not os.rename — Windows differs) for the atomic step
  • [ ] Cleans up the temp file on every error path (try/except/finally or context manager that survives mid-write exceptions)
  • [ ] If target exists and mode is None, the new file inherits the target's pre-existing mode bits (os.stat then os.chmod)
  • [ ] If mode is set explicitly, applies it (os.chmod) before the replace
  • [ ] Raises FileNotFoundError cleanly when the parent directory doesn't exist (and leaves no temp residue)
  • [ ] Raises IsADirectoryError when path is an existing directory
  • [ ] CLI: python atomic_write.py <path> reads stdin (bytes mode) and writes atomically
  • [ ] CLI: exits 0 on success, non-zero on any error with a stderr message
  • [ ] Symlink targets: writes to the resolved target, not replacing the symlink itself (or explicitly documented if not handling)
  • [ ] Concurrent writers: uses a unique temp name (e.g. tempfile.NamedTemporaryFile(dir=...) or pid+rand suffix) so two concurrent calls don't collide on the temp filename

Subtotal: __ / 10 Notes:

Code quality — score each 0–5

  • [ ] Clarity — naming, structure, function decomposition: __
  • [ ] Conciseness — no over-engineering, no unused branches: __
  • [ ] Error handling — temp cleanup on every failure path; specific exception types per SPEC: __
  • [ ] Comments — only at the genuinely non-obvious points (parent-dir fsync rationale, temp-in-same-dir constraint, symlink semantics): __

Subtotal: __ / 20

One-line summary

Verdict

ship-with-cleanup / rewrite / unusable