Sub topic 11
Handling Failures and Retries
A training pipeline that runs on someone else's machine at 3 a.m. will eventually fail. The network drops while downloading data. A disk fills up. A worker is preempted. A model misses its accuracy threshold. This chapter covers how to tell these failures apart, how to retry the ones worth retrying, and how to make sure a failed run leaves a clear record and no half-written files.
It assumes you have read the earlier chapters on stages, configuration fingerprints, idempotent stages, evaluation gates, and orchestration. The code reuses TrainConfig, config_fingerprint, and run_pipeline from them. It also assumes you can read Python exceptions and decorators.
Failures are not all the same
The most important decision in failure handling is whether to try again. Repeating a call helps only if the cause was temporary. Repeating a call that fails for a permanent reason wastes time and hides the real problem.
| Kind | Example | Retry? | What to do |
|---|---|---|---|
| Transient | Connection reset, HTTP 503, storage timeout, preempted worker | Yes, with backoff | Retry a limited number of times, then fail |
| Permanent | Missing column, bad config value, code bug | No | Fail immediately with a clear message |
| Quality gate | Accuracy 0.74 against a gate of 0.80 | No | Report the result and stop promotion |
| Resource | Out of memory, disk full | Only after a change | Fail, then change the config or the machine |
The quality gate is not a bug. The pipeline worked correctly and found that the model was not good enough. Running it again with the same seed and data gives the same model and the same refusal. If you retry gate failures, you also invite the habit of rerunning until a lucky result passes, which defeats the gate.
Naming the failure types in code
Make the distinction explicit in code by using different exception classes. The retry logic can then react to the class and does not have to guess from message text.
import random
import time
from functools import wraps
class TransientError(Exception):
"""A failure that may succeed if the same call is repeated."""
class GateFailure(ValueError):
"""The model trained correctly but did not meet the evaluation gate."""
def retry(
max_attempts=3,
base_delay=1.0,
max_delay=30.0,
retry_on=(TransientError,),
sleep=time.sleep,
):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return fn(*args, **kwargs)
except retry_on as exc:
if attempt == max_attempts:
raise
ceiling = min(max_delay, base_delay * 2 ** (attempt - 1))
delay = random.uniform(0, ceiling)
print(
f"{fn.__name__}: attempt {attempt} failed ({exc}); "
f"retrying in {delay:.1f}s"
)
sleep(delay)
return wrapper
return decoratorGateFailure subclasses ValueError, so the gate from the evaluation chapter keeps working if you change run_pipeline to raise GateFailure instead of a bare ValueError. Callers that catch ValueError still catch it.
How the retry helper behaves
- Only listed exceptions are retried. Anything not in
retry_onpropagates on the first failure. AKeyErrorfrom a missing column fails at once. - The last failure is re-raised. After
max_attempts, the original exception reaches the caller with its traceback. The wrapper does not return a default value or swallow the error. - Delays grow exponentially. The ceiling doubles with each attempt (1, 2, 4, 8 seconds) up to
max_delay. - Jitter spreads out retries.
random.uniform(0, ceiling)picks a random delay below the ceiling. Without it, many workers that failed together would all retry together and overload the service again. sleepis a parameter. Tests can pass a function that does nothing, so they run instantly.
Apply the decorator to the smallest unit that can fail transiently, such as one download or one upload. Do not wrap the whole pipeline. If the whole pipeline is retried, a transient error in the last stage repeats the training that already succeeded.
import urllib.error
import urllib.request
@retry(max_attempts=4, base_delay=0.5, retry_on=(TransientError,))
def fetch_bytes(url: str, timeout: float = 10.0) -> bytes:
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.read()
except urllib.error.HTTPError as exc:
if exc.code >= 500 or exc.code == 429:
raise TransientError(f"HTTP {exc.code} from {url}") from exc
raise # 404, 403 and similar will not fix themselves
except (urllib.error.URLError, TimeoutError) as exc:
raise TransientError(f"network problem for {url}: {exc}") from excThis function is where classification happens. HTTP 5xx and 429 (too many requests) become TransientError. A 404 is re-raised unchanged, because the file is not going to appear on the next attempt. HTTPError is a subclass of URLError, so its handler must come first. Translating library exceptions into your own classes at the edge keeps the rest of the pipeline free of library details.
Retries depend on idempotent stages
Retrying is only safe when running a stage twice leaves the same state as running it once. Chapter 9 introduced idempotent stages. Failure handling is the reason they matter. The typical hazard is a stage that dies halfway through writing an output. The next attempt, or the next stage, then finds a truncated file that looks like a real artifact.
The fix is to write to a temporary file in the same directory and rename it into place. On the same filesystem, os.replace is atomic: readers see either the old file or the complete new one, never a partial file.
import os
import tempfile
from pathlib import Path
def write_atomic(path, text: str) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_name, path)
except BaseException:
Path(tmp_name).unlink(missing_ok=True)
raiseThe temporary file must be in the destination directory. A rename across filesystems is a copy followed by a delete, and that is not atomic. The except BaseException clause also cleans up after KeyboardInterrupt, so a Ctrl+C does not leave stray .tmp files.
Other practices that make retries safe:
- Derive output paths from the config fingerprint. A rerun with the same configuration writes to the same
runs/<fingerprint>/directory and overwrites its own output. A rerun with a different configuration cannot clobber it. - Treat a missing output as "not done". Mark a stage complete only after its output is fully written. With atomic writes, "the file exists" is a reliable completion check, and a cached stage can skip itself on resume.
- Avoid appending to shared state. Inserting a row into a results table on every attempt creates duplicates. Use an upsert keyed by the run ID, or write one file per run.
Timeouts and failing loudly
A hung call is worse than a failed one, because nothing retries or reports it. Set an explicit timeout on every network call, as fetch_bytes does, and on every subprocess (subprocess.run(..., timeout=...)). For the whole run, set a wall-clock limit in your CI job or orchestrator, so a stuck training job is killed and reported instead of holding a runner for hours.
Do not catch broad exceptions inside stages to "keep going". A try/except Exception: pass around data loading turns a clear failure into a model trained on no data. Let the exception propagate and handle it in one place at the top of the pipeline.
Recording the outcome and signalling it
When a run fails, whoever looks at it later needs three things: which configuration it used, which stage failed, and why. Write a small status file next to the run's other artifacts, and return an exit code that tells CI and orchestrators what happened. Exit codes are how they detect failure at all.
import json
import sys
import time
import traceback
from pathlib import Path
EXIT_OK = 0
EXIT_ERROR = 1
EXIT_GATE = 2
def write_status(path, state, **details):
record = {"state": state, "finished_at": time.time(), **details}
write_atomic(path, json.dumps(record, indent=2, sort_keys=True))
def main() -> int:
cfg = TrainConfig()
run_id = config_fingerprint(cfg)
status_path = Path("runs") / run_id / "status.json"
try:
_, metrics = run_pipeline(cfg)
except GateFailure as exc:
write_status(status_path, "gate_failed", run_id=run_id, error=str(exc))
return EXIT_GATE
except Exception:
write_status(
status_path, "error", run_id=run_id, error=traceback.format_exc()
)
return EXIT_ERROR
write_status(
status_path,
"succeeded",
run_id=run_id,
metrics={k: float(v) for k, v in metrics.items()},
)
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())Two distinct nonzero codes let the caller treat the cases differently. An orchestrator can retry a task that exits with 1 (an unexpected error, possibly infrastructure), and it can mark the run as "rejected" on 2 without retrying. Exit code 0 must mean the model passed the gate and all artifacts were written. The except Exception here is deliberate: it is the single top-level handler that records the failure and still returns a nonzero code. It does not hide the error.
Keep in mind that the status file is written with write_atomic, so a crash while recording the failure cannot leave a corrupt status either.
Testing the failure paths
Failure code is rarely exercised, so it tends to be broken when it is finally needed. Test it the same way you tested the stages, by injecting the failure. The sleep argument makes these tests instant.
import pytest
def test_retry_recovers_from_transient_errors():
calls = {"n": 0}
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("connection reset")
return "ok"
wrapped = retry(max_attempts=3, sleep=lambda s: None)(flaky)
assert wrapped() == "ok"
assert calls["n"] == 3
def test_retry_does_not_repeat_permanent_errors():
calls = {"n": 0}
def broken():
calls["n"] += 1
raise ValueError("missing column 'species'")
wrapped = retry(max_attempts=3, sleep=lambda s: None)(broken)
with pytest.raises(ValueError):
wrapped()
assert calls["n"] == 1
def test_retry_gives_up_after_max_attempts():
def always_down():
raise TransientError("503")
wrapped = retry(max_attempts=2, sleep=lambda s: None)(always_down)
with pytest.raises(TransientError):
wrapped()Add a test for write_atomic that makes the write fail, for example by passing a value that is not a string, and then asserts that the destination is unchanged and no .tmp file remains. Add one more that sets min_accuracy=1.01 in the config and asserts that main() returns EXIT_GATE.
Common mistakes
- Retrying everything.
retry_on=(Exception,)retries bugs and gate failures. Keep the list narrow. - Retrying without a limit. An endless loop on a permanent outage turns one failure into a stuck job and a large bill. Always cap attempts and total time.
- Backoff without jitter. Synchronized retries from many workers can keep an overloaded service down.
- Retrying at the wrong level. Wrapping the entire pipeline repeats expensive training. Wrap the small call that can fail, and let caching skip finished stages when the whole run is restarted.
- Treating a gate failure as a crash. If both produce the same exit code, a dashboard cannot tell "the infrastructure broke" from "the model is not good enough".
- Losing the traceback. Catching an exception and raising a new one without
from exchides the original cause. Useraise ... from exc, as infetch_bytes. - Forgetting that seeds make failures repeatable. Because the pipeline is deterministic, a failure that depends only on code and data will repeat exactly. A failure that disappears on rerun points to the environment, such as network, memory, or disk. That is useful when diagnosing.
Exercise
A stage that uploads the trained model to remote storage fails with a connection timeout. A second stage then computes a report from the local metrics file, and that fails with a KeyError because a metric name was misspelled. Which of these two failures should be retried, and why? What exit code behavior would you want from the pipeline in each case?
Show answer
Retry only the upload. A connection timeout is transient, so it is raised as TransientError and retried a limited number of times with exponential backoff and jitter, and the upload should be safe to repeat, for example by writing to a path derived from the config fingerprint. The KeyError is a permanent bug in the code: it will fail identically every time, so it must fail on the first attempt with a clear traceback. If the upload still fails after the last attempt, or the KeyError occurs, the pipeline records the failure in the status file and exits with a nonzero code (1 for unexpected errors), so CI or the orchestrator marks the run as failed.
Exercise
Why does write_atomic create its temporary file in the same directory as the destination instead of using the system temp directory, and what goes wrong in a retry scenario if a stage writes its output directly to the final path?
Show answer
os.replace is atomic only when the source and destination are on the same filesystem. The system temp directory is often on a different filesystem, where a move becomes a copy followed by a delete, which can leave a partial file if interrupted. If a stage writes directly to the final path and dies midway, a truncated file remains. On retry or resume, the completion check "does the output exist?" passes, and later stages read corrupt data. Writing to a temporary file and renaming means the output either does not exist or is complete.