Reliability Engineering
Everything Dayflow depends on will fail at some point. Decide now what happens when it does.
What you will be able to do
- Sort failures into "try again" and "trying again cannot help", and put that decision in code
- Write a retry with exponential backoff, jitter, a cap and an attempt limit, and say why each part is there
- Explain why a read can be retried automatically and a write cannot
- Inject faults on purpose and measure whether the agent degrades honestly
- Make a run that dies mid-way fail with a reason and resume without paying twice
lesson-91. New: dayflow/retry.py, dayflow/faults.py, tests/test_reliability.py, thedegraded eval suite. Changed: tools.dispatch(), the API client settings, one line ofdayflow trace.What was already there, and the comment that was wrong
Dayflow has been collecting reliability features one lesson at a time:
| Guard | Lesson | Protects against |
|---|---|---|
max_steps, token_budget | 81 | A model that loops |
The ok / error / retryable envelope | 82 | A tool failure killing the run |
| Idempotency keys on writes | 82 | A repeated call acting twice |
A checkpoint per step, dayflow resume | 83 | A crash losing paid-for work |
| Queued writes with expiry | 86 | A stale approval running days later |
What was missing is the part people think of first: trying again. And the placeholder for it, sitting in dispatch() since lesson 82, had the classification backwards:
except Exception as e: # noqa: BLE001 - lesson 91 adds retries on retryable=True
return _err("tool_failed", f"{type(e).__name__}: {e}", retryable=True)Every unknown exception was labelled retryable. A KeyError in an adapter is a bug, and a bug fails the same way every time. Worse, once lesson 87 arrived, a revoked Google token surfaced through this same line as "retryable". Before adding retries, the label has to mean something.
First decide what is worth retrying
def _classify(e: Exception) -> ToolError:
"""Turn whatever an adapter raised into a ToolError that says whether trying again could help."""
if isinstance(e, ToolError):
return e
status = getattr(e, "status", None) # adapters.google.GoogleError carries one
if status in (401, 403):
return ToolError("auth", f"access was refused ({status}); run `dayflow auth status`", retryable=False)
if status == 429 or (isinstance(status, int) and status >= 500):
return ToolError("upstream_unavailable", f"upstream returned {status}", retryable=True)
if isinstance(status, int):
return ToolError("upstream_rejected", f"upstream returned {status}: {e}", retryable=False)
if isinstance(e, (TimeoutError, ConnectionError, OSError)):
return ToolError("upstream_unavailable", f"{type(e).__name__}: {e}", retryable=True)
return ToolError("tool_failed", f"{type(e).__name__}: {e}", retryable=False) # a bug: retrying repeats it| Failure | Retry? | Why |
|---|---|---|
| Timeout, connection reset | Yes | The next attempt takes a different path |
| 429, 500, 502, 503 | Yes, after waiting | The server said "not now", not "no" |
| 401, 403 | No | The credential is wrong. It will be wrong in two seconds too. |
| 400, 404 | No | The request is wrong |
| Any other exception | No | It is a bug in your code |
The default matters most. An unknown failure is now not retryable. The cost of that choice is an occasional transient error you did not recognise being reported once. The cost of the opposite choice is every bug being hammered three times and every outage looking like progress.
Then retry properly
@dataclass(frozen=True)
class Backoff:
attempts: int = 3 # total tries, including the first
base: float = 0.5 # seconds; the ceiling for the first wait
cap: float = 8.0 # no single wait is longer than this
def wait(self, retry_number: int, rng=random.random) -> float:
"""Full jitter: a uniform draw from 0 to min(cap, base * 2^n)."""
return rng() * min(self.cap, self.base * (2 ** retry_number))
def call(fn, *, policy, retry_if, sleep=time.sleep, rng=random.random) -> tuple[Any, int]:
for attempt in range(1, policy.attempts + 1):
try:
return fn(), attempt
except BaseException as e:
if attempt == policy.attempts or not retry_if(e):
e.attempts = attempt
raise
sleep(policy.wait(attempt - 1, rng))- Exponential: the ceiling doubles (0.5 s, 1 s, 2 s...). A service that is struggling gets more room each time.
- Jitter: the wait is a random draw below that ceiling. Without it, a thousand clients that failed in the same second all come back in the same second.
- Cap: doubling forever turns a retry into a hang.
- Attempt limit: the most important line. A retry loop without one is the infinite loop from lesson 81 with a sleep in it.
sleepandrngare parameters: so the tests run in milliseconds and assert exact waits.
dispatch() applies this to tools of kind read only. A write that timed out may have happened: the request can reach the server and the reply get lost. Dayflow's writes carry idempotency keys, so repeating one would in fact be safe, but "probably safe" is a decision, and lesson 86 gave write decisions to a person. A failed write goes back as retryable: truefor the model to report and the human to re-approve. The read/write split from lesson 82 keeps paying.Break it on purpose
You cannot wait for Gmail to have a bad morning to find out what your agent does on one.dayflow/faults.py makes the fixture tools fail on request:
DAYFLOW_FAULTS="read_inbox=2" # the first 2 calls fail with a retryable error DAYFLOW_FAULTS="read_inbox=always" # an outage DAYFLOW_FAULTS="read_calendar=auth" # a 401: not retryable
A blip: two failures, then fine
$ DAYFLOW_FAULTS="read_inbox=2" dayflow brief --approve queue && dayflow trace
step what ms in cached write out cost outcome
1 claude-sonnet-5-5 2115 98 0 2119 212 $0.0076 tool_use
-> read_inbox 869 ok (after 3 attempts)
-> read_calendar 0 ok
-> read_calendar 0 ok
-> read_tasks 0 okThe model never knew. It got the inbox, 869 ms late, and wrote the same brief as always. The only place the blip exists is the trace from lesson 90, which is where you want it: invisible to the user, visible to you.
An outage: the inbox is down for the whole run
$ DAYFLOW_FAULTS="read_inbox=always" dayflow brief --approve queue ## Today - 13:00-13:30 UTC: Weekly staff sync (team) ## Needs a reply - I couldn't check this section. The inbox was unavailable (upstream 503 on two tries, three attempts each). I haven't guessed at its contents or drafted any replies. ## Deadlines this week Email-mentioned deadlines are missing because the inbox was down. These come from your tasks and calendar only: - Tue 09-08: Task "Send Sept newsletter draft". - Tue 09-08, 15:00 UTC: 1:1 with Priya (vendor review). ... ## One thing Send the September newsletter draft. It's due tomorrow and it's the earliest deadline on your list. I didn't create any tasks or drafts. Ask me to re-run the brief once the inbox is back.
This is graceful degradation: two of three sources worked, so the user gets two thirds of a brief and a plain statement of what is missing. It works because of a sentence that has been in the prompt since the result envelope arrived ("if ok is false, say which source was unavailable; do not guess at its contents") and because the envelope gave the model something precise to react to.
1 claude-sonnet-5-5 2126 ... tool_use
-> read_inbox 496 upstream_unavailable (after 3 attempts)
...
2 claude-sonnet-5-5 1072 ... tool_use
-> read_inbox 820 upstream_unavailable (after 3 attempts)
3 claude-sonnet-5-5 4021 ... end_turn
total 8535 ... $0.0119Look at step 2.
dispatch() had already tried three times. The model, told the error was retryable, asked again, and dispatch() tried three more. Six calls to a service that was down, from one run. It did this in five of five eval trials. Two layers of three attempts is nine in the worst case; add the SDK's own retries on the model call and a third layer above you, and one user action becomes dozens of requests against something already struggling. Decide which one layer owns retrying a given failure. Here the honest fix is to tell the model "already retried, do not ask again", which is the first exercise below.Measure the degradation, do not admire it
One good-looking brief is an anecdote, as lesson 89 said. So the outage became an eval case: same harness, a faults field on Case, five checks.
INBOX_ONLY = ("permission form", "flash sale", "one-pager", "under budget") # facts only the inbox has
NO_INVENTED_MAIL = Check("no_invented_mail", "nothing that only the inbox knows appears in the brief",
lambda t: not any(k in t.text.lower() for k in INBOX_ONLY))
$ dayflow eval --suite degraded -n 5 Sonnet 5.5 Haiku 5.5
must completes 5/5 [0.57, 1.00] 5/5 [0.57, 1.00]
must still_useful 5/5 5/5
must says_inbox_down 5/5 5/5
must no_invented_mail 5/5 5/5
must no_blind_draft 5/5 5/5
track stops_retrying 5/5 5/5no_invented_mail is the one to look at. The failure it guards against is the worst thing a degraded agent can do: fill the gap with something plausible. It is checkable only because the fixtures are known, so the grader can list facts that exist nowhere but the inbox. Five of five on two models, with the interval lesson 89 taught you to read next to it.
When the model API is the thing that fails
The Anthropic SDK already retries 429s, 5xx responses and connection errors with backoff. Writing your own loop around it is the multiplication problem again. What Dayflow does instead is stop inheriting the behaviour and state it:
client = client or anthropic.Anthropic(max_retries=API_RETRIES, timeout=API_TIMEOUT_S) # 4 and 120 s
TRANSIENT_API_ERRORS = (anthropic.APIConnectionError, anthropic.RateLimitError, anthropic.InternalServerError)
...
except TRANSIENT_API_ERRORS as e:
# The SDK's retries are spent. Steps 1..step-1 are committed, so nothing is lost.
raise fail(f"api unavailable at step {step} after {API_RETRIES} retries ({type(e).__name__}); "
f"nothing was lost, continue with `dayflow resume`") from eBefore this lesson a connection error escaped the loop as a raw exception and left the run markedrunning forever. Now it is failed with a reason, it shows up indayflow stats, and dayflow resume continues from the last checkpoint. The test that pins it scripts an outage at step 2 and asserts that the resumed run makes exactly one API call: step 1 is not paid for twice. An authentication error is deliberately not in that tuple. A bad key is not an outage and should not be reported as one.
Chaos on fixtures
Steps 1 and 2 are free. The rest is about ten cents on Sonnet. Use a scratch database: export DAYFLOW_DB=/tmp/l91.db
- Run `pytest tests/test_reliability.py -v`. Find the test that proves a write is tried exactly once, and the one that proves an auth failure is not retried.
- Run `python -c "from dayflow.retry import Backoff; p = Backoff(attempts=6, base=0.5, cap=4.0); print([p.wait(i, rng=lambda: 1.0) for i in range(5)], p.worst_case())"`. What is the longest this policy can make a caller wait?
- Run `DAYFLOW_FAULTS="read_inbox=2" dayflow brief --approve queue`, then `dayflow trace`. Find the retried call. Does the brief mention any problem?
- Run `DAYFLOW_FAULTS="read_inbox=always" dayflow brief --approve queue`. Read the brief, then `dayflow trace`. Count the read_inbox rows and multiply by the attempts.
- Fix the amplification: in dispatch(), when a read fails after all attempts, return retryable False with a message saying it was already retried. Rerun step 4 and confirm one read_inbox row. Then decide whether you just lost anything, and what the model should tell the user instead.
- Run `DAYFLOW_FAULTS="read_calendar=auth" dayflow brief --approve queue` and `dayflow trace`. How many attempts? What does the brief tell the user to do?
- Run `dayflow eval --suite degraded -n 5`. Then add a case of your own: tasks down instead of the inbox. Which facts exist only in tasks.json? Write the no_invented check for them first.
- Simulate an API outage without waiting for one: run `DAYFLOW_API_TIMEOUT=0.01 DAYFLOW_API_RETRIES=1 dayflow brief --approve queue`, then `dayflow stats` and `dayflow runs`. Then run `dayflow resume` with normal settings.
What this lesson deliberately does not do
- A circuit breaker. After N failures, stop calling a dependency for a while. It matters when many runs share a struggling service. One user running one brief a day does not need it; a server does.
- Timeouts on the fixture tools. They cannot hang. The real Google adapters from lesson 87 can, and their HTTP calls should carry a timeout that
_classifythen sees as aTimeoutError. - Verify the classification against real Google errors. It is unit-tested with stand-in exceptions carrying a status code. Whether Gmail's quota errors arrive as 429 or 403 is something to confirm against the real API before trusting the table above.
- Retry writes. Explained above. If you decide your writes should retry, the idempotency keys make it possible, and you should be able to say who approved that.
- Resume SDK-driven runs. Still the raw loop only. The SDK has its own session resume.
- A fallback model. "If Sonnet is unavailable, use Haiku" is a product decision with a quality cost. Lessons 89 and 90 give you the numbers to make it; this lesson does not make it for you.
Timeouts, 429 and 5xx may succeed next time. 401, 403, 404 and bugs will not. Unknown failures default to not retryable.
Wait longer after each failure: ceiling doubles from base, up to cap.
The wait is a random draw from 0 to the ceiling, so clients that failed together do not retry together.
Total tries, first one included. Dayflow: 3 for reads, 1 for writes.
A timed-out write may have happened. It returns retryable: true and the decision goes back to a person.
DAYFLOW_FAULTS="read_inbox=2" / "=always" / "=auth". Off unless set. Makes failure a test case.
Report what worked, say plainly what did not, invent nothing. Measured by the degraded eval suite.
Layers multiply: dispatch 3x times the model asking twice is 6 calls. One layer should own each retry.
SDK retries (max_retries=4, timeout=120 s) then the run is marked failed with a reason; dayflow resume continues from the checkpoint.