Sub topic 12
Making Reruns Safe: Idempotency and Retries
This chapter assumes you can write a wrapper script like the one from the timeouts chapter, and that you know Git branches and exit codes. A scheduled agent job will eventually run twice for the same period. This chapter shows how to make that harmless.
Why reruns happen
You will not control how often your job starts. Common causes:
Persistent=trueon a systemd timer runs a missed job at the next boot, possibly alongside a manual run.- Someone clicks "Re-run" on a failed CI job.
- A retry loop starts a second attempt after the first one crashed halfway.
- A timeout kills the agent after it pushed a branch but before the script recorded success.
- An operator runs the script by hand to see why last night's run failed.
A lock stops two runs from happening at the same time. It does nothing about two runs happening one after the other. That is the job of idempotency.
An operation is idempotent if running it twice leaves the system in the same state as running it once. A job is idempotent when a second run for the same period either does nothing or reproduces the first run's result, without duplicating its side effects.
Find the side effects
List everything the job changes outside its own working directory. Agents are good at producing side effects you did not plan for, so check the tool permissions you granted as well as the prompt.
| Side effect | Duplicate-run risk | Idempotency technique |
|---|---|---|
| Push a branch | Second push is rejected, or a second branch appears | Deterministic branch name per period |
| Open a pull request | Two PRs for the same work | Check for an existing PR or branch first |
| Post a comment or message | Spam | Embed a marker string and search for it |
| Create a ticket | Duplicate tickets | Look up by a stable key before creating |
| Write a report file | Overwrite or clutter | Name by period, so a rerun overwrites the same file |
The pattern is the same each time: derive a run key from the period the job covers (such as the UTC date), put it in the name of everything the job creates, and check for that name before creating anything.
Use the period the job is about, not the time it started. A run that starts at 23:59 and a rerun at 00:01 would otherwise get different keys and both do the work.
Decide what "already done" means
There are two places to record completion, and they fail differently.
- Local state file. It is cheap to check, but it is lost if the machine is rebuilt. In a CI runner with a fresh filesystem it is useless.
- The remote result. Check whether the branch or pull request exists. It survives machine loss, and it is the thing you actually care about.
Prefer checking the remote. Use a local file only as a fast path in front of it.
Write the "done" marker last, after the final side effect succeeds. If the job crashes between the push and the marker, the next run re-checks the remote, sees the branch, and exits cleanly.
Retries
A retry is an automatic rerun inside the same job. Retrying helps only when the failure was transient: a network error, an API rate limit, or a brief outage. It hurts when the failure is permanent, because each attempt costs time and model usage and may repeat a partial side effect.
Rules that keep retries safe:
- Cap attempts. Three is a common ceiling. An unbounded loop turns one bad night into a large bill.
- Back off. Wait longer between attempts (for example 60 s, then 120 s) so you do not hammer a service that is already struggling.
- Do not retry a timeout by default. Exit status 124 from
timeoutmeans the run used its whole time budget. Another attempt will usually do the same, and it doubles the cost. - Reset state before each attempt. A failed attempt may have left edited files behind. Start every attempt from the same clean checkout.
- Retry only what you can classify. Many agents return the same non-zero code for different failures. Check your agent's documentation, and if codes are not distinguishable, keep the retry count low.
A rerun-safe wrapper
This script extends the wrapper from the timeouts chapter. It uses a date-based run key, checks the remote before doing work, resets the checkout between attempts, retries with backoff, and pushes only if the agent committed something. It does not open the pull request. That belongs to the next chapter.
#!/usr/bin/env bash
# nightly-agent-safe.sh
# AGENT_CMD is a placeholder for your agent's non-interactive command.
# This script assumes it reads the prompt from stdin.
# Run it in a dedicated clone: it discards uncommitted changes.
set -u
: "${AGENT_CMD:?set AGENT_CMD to your agent's non-interactive command}"
REPO=/srv/repos/my-project
RUN_KEY="$(date -u +%Y-%m-%d)" # the period this run covers
BRANCH="agent/nightly-$RUN_KEY"
STATE_DIR="$HOME/agent-state"
LOG_DIR="$HOME/agent-logs"
DONE="$STATE_DIR/nightly-$RUN_KEY.done"
MAX_ATTEMPTS=3
mkdir -p "$STATE_DIR" "$LOG_DIR"
# Fast path: this period was already completed on this machine.
if [ -f "$DONE" ]; then
echo "run $RUN_KEY already done, skipping"
exit 0
fi
cd "$REPO" || exit 1
git fetch origin --prune || exit 1
# Source of truth: does the result already exist on the remote?
if git ls-remote --exit-code --heads origin "$BRANCH" > /dev/null 2>&1; then
echo "branch $BRANCH already exists on origin, skipping"
touch "$DONE"
exit 0
fi
status=1
for attempt in $(seq 1 "$MAX_ATTEMPTS"); do
# Every attempt starts from the same clean state.
git switch --detach origin/main > /dev/null 2>&1 || exit 1
git reset --hard origin/main > /dev/null || exit 1
git clean -fd > /dev/null || exit 1
git switch -C "$BRANCH" > /dev/null 2>&1 || exit 1
LOG="$LOG_DIR/nightly-$RUN_KEY-attempt$attempt.log"
# AGENT_CMD is intentionally unquoted so arguments split into words.
timeout 20m $AGENT_CMD < prompts/nightly.md > "$LOG" 2>&1
status=$?
[ "$status" -eq 0 ] && break
if [ "$status" -eq 124 ]; then
echo "attempt $attempt timed out, not retrying" >&2
break
fi
echo "attempt $attempt failed with status $status" >&2
[ "$attempt" -lt "$MAX_ATTEMPTS" ] && sleep $((60 * attempt))
done
[ "$status" -eq 0 ] || exit "$status"
# Publish only if the agent actually committed something.
if [ "$(git rev-list --count origin/main..HEAD)" -gt 0 ]; then
git push --set-upstream origin "$BRANCH" || exit 1
else
echo "agent made no commits for $RUN_KEY"
fi
touch "$DONE" # written last, after the final side effect
exit 0Three details matter here. The remote check happens before any agent time is spent. The reset happens inside the loop, so attempt 2 never inherits attempt 1's half-finished edits. And a run with no commits still records completion, because "nothing to do" is a valid result for that period.
The flow
Edge cases
- Crash between push and marker. Handled by the remote check on the next run.
- Branch exists but is incomplete. If the agent pushed partway, the remote check would treat the period as done. If your agent pushes more than once per run, push only once at the end, as the script does. Alternatively, mark completion with something that appears only on success, such as a pull request or a final commit trailer.
- Time zone drift. The key uses
date -u. A key built from local time changes meaning when daylight saving shifts. - Intentional redo. Sometimes you want to rerun a day. Delete the remote branch and the marker, or add an explicit
FORCE=1path. Don't weaken the default check. - External systems that cannot be queried. If you cannot look up whether a message was sent, send it from a step that records its own marker immediately after, and accept that a crash in between may cause one duplicate.
Exercise
Exercise
A systemd timer with Persistent=true starts your job at boot because the 02:00 run was missed. An engineer also triggers the script by hand at the same minute. The flock lock stops the overlap, but the second process starts a few minutes after the first finishes. Name two checks in the rerun-safe script that stop the second process from duplicating the work, and say which one still works if the machine was rebuilt in between.
Show answer
The local done marker file and the check that the branch already exists on origin. The marker is the fast path, and the remote branch check still works after a rebuild because it reads the state from the remote, not the local disk.
Exercise
Why does the retry loop skip further attempts when the exit status is 124, and why does it reset the checkout at the start of every attempt?
Show answer
Status 124 means the agent used its full time budget, so another attempt will most likely hit the same limit and double the cost. The reset removes edits left by a failed attempt, so each attempt starts from the same state and cannot build on partial changes.