Sub topic 12
Avoiding Conflicting Writers
This chapter assumes you have read the chapters on checkpoints and atomic writes. It also assumes you can read Python and know that a process is a running program with its own memory. Most long-running tasks have one writer, but a task that gets resumed, retried, or split across agents can easily end up with two. This chapter covers how to prevent that, and how to detect it when prevention fails.
Why atomic writes are not enough
An atomic write guarantees that a reader never sees a half-written file. It does not guarantee that two writers will cooperate. Each writer reads the state, changes it in memory, and writes the whole file back. If the reads overlap, the second write silently erases the first writer's change. This is called a lost update.
Every individual write in this diagram was atomic, and the file is still wrong. Atomic writes protect against crashes. Locks and version checks protect against other writers.
How two writers appear
You rarely plan to have two writers. They show up in a few predictable ways:
- A run is restarted while the old process is still alive, for example after a timeout that only killed the parent.
- A scheduler launches a new run before the previous one finishes.
- Two agents work on parts of the same task and share one checkpoint file.
- A human edits
progress.mdwhile an agent is also updating it. - A handoff happens, and the previous owner keeps going for a while.
The last case matters most for this tutorial. A handoff should transfer ownership, which means the old owner must stop writing.
Choose the simplest strategy that works
Try these in order. Each one costs more than the one before.
| Strategy | How it works | Use it when |
|---|---|---|
| Single writer | Exactly one process or agent may write. Others read only. | You can assign ownership clearly. This is the best default. |
| Separate files | Each writer owns its own file, such as `checkpoint-agent-a.json`. A reader merges them. | Writers work on independent parts of the task. |
| Lock around read-modify-write | A writer takes a lock, reads, changes, writes, and releases. | Writers share one file and each update is short. |
| Version check | Each state carries a version number. A write fails if the version has changed since the read. | Writers hold state for a long time between read and write. |
| Lease | A lock that expires unless it is renewed. | The owner may crash or hang, and other writers must be able to take over. |
Separate files avoid the problem entirely, so prefer them when the work can be split. The rest of this chapter covers the locking and version options.
A lock around read-modify-write
On Linux and macOS, fcntl.flock gives you an advisory lock. Advisory means the operating system only enforces it between processes that ask for it. A writer that ignores the lock can still overwrite the file.
Two details matter in the code below:
- The lock is taken on a separate
.lockfile, not on the checkpoint. The atomic save replaces the checkpoint withos.replace, which swaps in a new file. A lock on the old file would then protect nothing. - The operating system releases the lock when the process dies, so a crash does not leave a permanent lock.
import fcntl
import json
import os
import tempfile
import time
from contextlib import contextmanager
def save_checkpoint(path, state):
directory = os.path.dirname(os.path.abspath(path))
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(state, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
def load_checkpoint(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return None
@contextmanager
def checkpoint_lock(path, timeout=10.0):
deadline = time.monotonic() + timeout
with open(path + ".lock", "a") as lock_file:
while True:
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(f"could not lock {path}")
time.sleep(0.1)
try:
yield
finally:
fcntl.flock(lock_file, fcntl.LOCK_UN)
def update_checkpoint(path, change):
with checkpoint_lock(path):
state = load_checkpoint(path) or {"completed": [], "notes": [], "version": 0}
change(state)
state["version"] += 1
save_checkpoint(path, state)
return state
if __name__ == "__main__":
result = update_checkpoint(
"demo-checkpoint.json",
lambda s: s["completed"].append("fetch"),
)
print(result)The first two functions repeat the atomic-write code from the earlier chapter so this file runs on its own. The new part is update_checkpoint. The read, the change, and the write all happen while the lock is held, so no other writer can slip in between them. The lock times out instead of waiting forever, so a stuck writer produces an error you can see.
Keep the work inside the lock short. Do not call a model or a slow API while holding it. Compute the result first, then lock, apply it, and release.
Version checks for long gaps
A lock is a poor fit when a writer reads state, spends twenty minutes on a step, and then wants to save. Holding a lock that long blocks everyone else. Instead, record a version number and check it at save time. This is called optimistic concurrency: you assume no conflict will happen and verify that assumption when you write.
class StaleStateError(Exception):
pass
def save_if_unchanged(path, state, expected_version):
with checkpoint_lock(path):
current = load_checkpoint(path)
current_version = current["version"] if current else 0
if current_version != expected_version:
raise StaleStateError(
f"expected version {expected_version}, found {current_version}"
)
state["version"] = expected_version + 1
save_checkpoint(path, state)This function builds on the code above. A writer does this:
- Load the state and remember
state["version"]. - Do the slow work.
- Call
save_if_unchangedwith the remembered version. - If
StaleStateErroris raised, reload the state and decide what to do.
The decision in step 4 depends on the task. Sometimes the other writer's change is unrelated and you can reapply yours on top. Sometimes the other writer already did the same step, and you should discard your result. Never respond to the error by saving anyway, because that brings back the lost update.
Leases and stale locks
A plain lock file created with os.open(path, os.O_CREAT | os.O_EXCL) works across more file systems than flock, but a crash leaves the file behind and nobody can tell whether its owner is alive. A lease fixes this by storing who owns the lock and when the claim expires:
{"owner": "agent-B", "expires_at": "2026-11-28T07:30:00Z"}The owner renews the lease on a timer while it works. Another writer may take over only after the expiry time has passed. Choose the duration with care:
- If it is too short, a slow but healthy owner loses the lease while still working.
- If it is too long, a crashed owner blocks everyone for that whole time.
Even a correct lease has a gap. An owner can stall, lose its lease without noticing, and then wake up and write. To guard against this, combine the lease with the version check above, so the stale owner's write is rejected.
Concurrency in progress files
Progress files are Markdown and are often edited by hand, so locks do not help much. These habits reduce conflicts:
- Give each writer a clear section, or a separate file per writer.
- Append to a log instead of rewriting the whole file. A short single
writeto a file opened in append mode is much less likely to collide. - Put the owner and a timestamp at the top:
Owner: agent-B, since 2026-11-28 07:00. - During a handoff, the old owner writes a final line such as
Released by agent-Abefore the new owner starts.
Spotting a conflict after the fact
Conflicts are easier to prevent than to repair, but you should be able to notice them. Signs include:
- The version number jumps by more than one between your read and your save.
- A step you did not run appears in
completed. - Two
.tmpfiles from different processes exist in the same directory. - Side effects happened twice, such as duplicate uploads. The handoff example earlier in this tutorial warned about exactly this.
When you resume, run the checks from the chapter on verifying saved state. If the state and reality disagree, treat reality as correct, repair the state, and record the repair in the progress file.
Exercise
Two agents each read checkpoint.json, add a different completed step, and save it with an atomic write. Why can one step still be lost, and what is the smallest change that prevents it?
Show answer
Atomic writes only prevent partial files. Both agents wrote the whole file from their own copy, so the later write replaced the earlier one. The smallest fix is to hold a lock (on a separate .lock file) around the whole read, change, and write sequence, for example with update_checkpoint. Using a version check at save time also detects the conflict.
Exercise
Why does checkpoint_lock lock "checkpoint.json.lock" instead of locking checkpoint.json itself?
Show answer
The atomic save uses os.replace, which swaps in a new file with a different identity. A lock on the old checkpoint file would not apply to the new one, so a second writer could take a lock on the new file while the first still thinks it holds the lock. A separate lock file is never replaced, so the lock stays meaningful.
Exercise
A writer reads a checkpoint at version 7, works for 20 minutes, and calls saveifunchanged with expected_version=7. The file is now at version 9. What should the writer do?
Show answer
It should not save. saveifunchanged raises StaleStateError. The writer reloads the version 9 state, checks whether its work is already covered or conflicts with the two changes it missed, and then either discards its result or reapplies it on top of the new state, using the new version number.