Sub topic 4
Making Steps Safe to Repeat
This chapter assumes you can read basic Python and know that a long task is split into steps. It also assumes you know a crash can interrupt a step partway through.
Why repetition happens
A resumed run often repeats work. The agent may crash after a step finishes but before the checkpoint records it. A retry after a timeout may also run a step that actually succeeded. In both cases the step runs a second time.
A step is idempotent if running it twice leaves the world in the same state as running it once. Idempotent steps turn "did that finish?" from a dangerous question into a harmless one. When in doubt, run the step again.
Common patterns
| Not idempotent | Idempotent version |
|---|---|
| Append a line to a log file | Write the whole file, or check whether the line exists first |
| Create a file named with a timestamp | Create a file named from the input, such as the month |
| Add 10 to a counter | Set the counter to a computed value |
| Send an email | Send with a unique key and record the key |
| Insert a database row | Insert or update keyed on a unique ID |
Three rules cover most cases:
- Derive names from inputs, not from the clock or a counter.
2023-08.csvis the same on every run.export-1693526400.csvis not. - Set values instead of changing them. "Status is published" can be repeated. "Increment the version" cannot.
- Replace instead of append. Write a complete output and swap it in, as in the atomic write pattern.
A deterministic output step
This step writes the same file path for the same month. Running it again overwrites the file with identical content.
import os
import tempfile
def export_month(month, rows, out_dir="out"):
os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f"{month}.csv")
fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".tmp")
with os.fdopen(fd, "w") as f:
for row in rows:
f.write(",".join(str(v) for v in row) + "\n")
os.replace(tmp_path, final_path)
return final_path
print(export_month("2023-08", [(1, "a"), (2, "b")]))
print(export_month("2023-08", [(1, "a"), (2, "b")]))A step with an external side effect
Some effects cannot be undone or overwritten, such as sending a message. Give each effect a unique key and record the keys you have already used.
import json
import os
def send_once(ledger_path, key, send):
done = set()
if os.path.exists(ledger_path):
with open(ledger_path) as f:
done = set(json.load(f))
if key in done:
return False
send(key)
done.add(key)
with open(ledger_path, "w") as f:
json.dump(sorted(done), f)
return True
sent = []
send_once("ledger.json", "invoice-1001", sent.append)
send_once("ledger.json", "invoice-1001", sent.append)
print(sent)On a fresh directory this prints ['invoice-1001']. The second call sees the key and does nothing.
Marking steps that cannot be repeated
Some steps cannot be made idempotent. Examples are charging a card through an API that has no idempotency keys, or deleting the only copy of data. Record these in the progress file as "do not repeat" steps. Before running one, check the real system for the result, not only the checkpoint.
Exercise
A step writes report-{timestamp}.txt to a folder and then the agent crashes before checkpointing. What goes wrong on resume, and how do you fix it?
Show answer
The resumed run uses a new timestamp, so it creates a second file and the folder holds a duplicate. Name the file from the input instead, for example report-2023-08.txt, and write it with a replace operation. A rerun then overwrites the same file.