Contents10 of 15
Download the PDF (892 KB)Before You Blame the ModelPart III · The Work: checking what it did
Chapter 09State and memory
Survive the crash
A live thread object slipped into my agent's saved state, and from then on, saving quietly stopped working.
Long-running agents crash. The laptop sleeps, the server restarts, the process gets killed. So you save progress as you go, and the obvious way to save is to grab the agent's state and write it out. The trap is that "the agent's state" in a real program is full of live things: open connections, locks, threads, handles. One of those got carried into my saved state through a context variable, the save started failing, and nothing stopped the run. It kept going, cheerfully, with no way back.
#Save facts, not the running agent
- Save explicit data with a closed schema. Write out exactly the fields you mean to keep, as plain data in a format like JSON. Dumping the whole object graph (pickle and friends) saves far more than you meant, breaks on live objects at the worst moment, and isn't safe to load from anywhere you don't trust.
- A failed save blocks what depends on it. If the checkpoint didn't write, don't start the work that assumes it did.
- Write atomically. Write to a temp file, then rename. A crash mid-write should leave the last good checkpoint, never half of a new one.
#Make requests reproducible, then prove the resume
The quietest resume bug is one that "works" but rebuilds a slightly different request than the one the model originally saw. Then your resumed run is a different run. The fix is to make requests reproducible. Use ids that aren't random, and normalize anything volatile (timestamps, durations, memory addresses, temp paths) before it reaches the prompt, keeping the raw values in your logs. On my agent that got 40 of 40 requests identical, byte for byte, across two runs of the same input, apart from three clock fields I hadn't normalized yet. Once requests are reproducible, a resume can check itself. Rebuild the next request, compare it to the recorded one, and only go live if they match.
Keep both paths. Checkpoints are fast. Replaying the recorded responses is slow but almost impossible to get wrong, so it's the fallback whenever a checkpoint fails its own check.
One last trap: saving scales with the number of files you track, not with how much work the model did. On a 20,000-file repository, my first checkpoint spent 98 of its 174 seconds just forcing 10,053 files to disk one at a time. Doing it in parallel fixed it. If saving is slow, count files before you blame anything else.
def save(state: AgentState, path: Path):
data = json.dumps(asdict(state)) # fails loudly on anything not plain data
fd, tmp = tempfile.mkstemp(dir=path.parent) # unique, same disk
with os.fdopen(fd, "w") as f:
f.write(data)
f.flush()
os.fsync(f.fileno()) # really on disk before the swap
os.replace(tmp, path) # atomic: old or new, never half