Sub topic 12
Avoiding conflicting writers
This chapter assumes you have read the chapters on checkpoints and atomic writes. It also assumes you know basic Python file handling. Atomic writes protect a file from a crash. They do not protect it from a second writer.
The problem
Suppose agent A is resuming a task, and agent B starts on the same task because a handoff went out twice. Both load checkpoint.json, both run the next step, and both save. Each write is atomic, but the last one wins. One agent's progress disappears, and a side effect such as an upload may have run twice.
Two situations cause this most often:
- A handoff is sent while the previous owner is still running.
- A scheduler restarts a job that was slow, not dead.
Use a lock file
The simplest fix is one lock file per task. Only the process that creates the file owns the task. os.O_EXCL makes creation fail if the file already exists, and the operating system performs that check and the creation as one step.
import json
import os
class LockHeld(Exception):
pass
def acquire_lock(lock_path):
try:
fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
raise LockHeld(f"{lock_path} is held by another run")
with os.fdopen(fd, "w") as f:
json.dump({"pid": os.getpid()}, f)
def release_lock(lock_path):
os.unlink(lock_path)
def run_exclusive(lock_path, work):
acquire_lock(lock_path)
try:
return work()
finally:
release_lock(lock_path)Wrap the whole resume-and-run routine in run_exclusive. Take the lock before you load the checkpoint, not after. Otherwise you may act on state that another writer is about to change.
Handle stale locks
A crash skips the finally block when the process is killed outright, for example by kill -9 or a power loss. The lock file then stays behind and blocks every later run. This is the same failure that checkpoints exist to survive, so plan for it.
The lock file above records the process ID. A new run can check whether that process still exists before deciding the lock is stale. This works only when both runs are on the same machine.
For agents on different machines, a lock file on a shared disk is unreliable on some network file systems. Use a database row, an object store with conditional writes, or a lock service instead.
Add a version check
A lock prevents overlap while it is held. A version number in the checkpoint helps you notice when the lock failed, or when someone edited the file by hand.
- Store
"version": 7in the state. - When you load, remember the version.
- Before you save, reread the file under the lock. If the version differs from what you loaded, stop and report a conflict instead of saving.
- Otherwise increment the version and save.
This is not a replacement for the lock. Between the reread and the save, another writer can still slip in if you hold no lock.
Reduce shared writes
Locks are easier to get right when fewer things are shared:
- Give each agent its own output directory and its own checkpoint, and merge at the end.
- Let only one agent, the owner, write
progress.md. Others send notes to the owner. - Record the owner's name in the handoff note, and have the previous owner confirm it has stopped before the new one starts.
Exercise
Agent A crashed with kill -9 and left task.lock behind. Agent B starts, sees the lock, and the file names a PID that no longer exists on the same machine. What should B do, and why not simply delete every lock it finds?
Show answer
B should confirm the recorded process is gone, remove the stale lock, and then acquire its own lock before loading the checkpoint. After that it should verify the saved state against reality, since A may have died mid-step. B must not delete locks blindly because a lock held by a live process, even a slow one, protects the task from duplicate side effects and overwritten checkpoints.