Search RU
Tasks / Concurrency / Atomic file write
Statement medium

Atomic file write

`atomic_write(path, chunks)` must write the whole file or leave it unchanged. In
`starter.py` data goes straight into the destination: it is opened for writing
and truncated, so a failure in the middle of the iterator leaves half the data,
and two concurrent writers interleave their bytes.

Fix the function so that:

- on success `path` contains exactly the concatenation of all chunks;
- on any exception from `chunks` or any write error the old file stays intact
and no new file appears;
- the temporary file is removed after a failure — no garbage is left in the
directory;
- the data reaches the disk: `fsync` of the temporary file is called **before**
`os.replace`; the directory `fsync` is best effort and must not break the
write;
- if the destination existed, its permissions are preserved;
- several threads may write the same `path` at once: the final content equals
one complete payload, never a mix;
- the temporary file is created in the same directory as the target (otherwise
`os.replace` may fail);
- the API does not change: `atomic_write(path, chunks)`.

`chunks` is an iterable of `bytes`; the generator may raise at any moment. The
destination directory already exists. Hidden tests monkeypatch `os.fsync` and
`os.replace` and check the call order.

Python
concurrencyfile-ioatomic-replacefsynccrash-safety
solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

What does a reader see if the target is opened for writing and the process fails
halfway? Where should the new bytes live until every chunk has been written?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts