Sub topic 11
Handling Failures and Retries
This chapter assumes that you know Python functions, exceptions, dataclasses, and basic machine learning stages such as loading data, training, and evaluation. You should also know basic command-line and Git usage. The goal is to make a failed pipeline safe to run again without repeating successful work or corrupting outputs.
Classify the failure first
A retry is useful only when the same operation might succeed later. Common failure types need different responses:
| Failure type | Example | Usual response |
|---|---|---|
| Transient | Network timeout, temporary service error, preempted worker | Retry with backoff |
| Deterministic | Missing column, invalid configuration, corrupt input | Stop and fix the cause |
| Resource | Out-of-memory error, full disk | Stop, resize, or change the stage |
| Quality | Accuracy below the promotion threshold | Stop without retrying |
A failed model evaluation does not become better because it runs again with the same inputs. A temporary object-storage timeout might.
Retry at stage boundaries
A pipeline stage should have clear inputs and outputs. This gives the runner a safe place to retry. If a data download fails, retry the download stage rather than retraining every model that came before it.
A retry policy should answer four questions:
- Which exception types are safe to retry?
- How many attempts are allowed?
- How long should the runner wait between attempts?
- What information should be recorded for each attempt?
Exponential backoff increases the delay after each failure. Jitter adds a small random amount so many workers do not retry at exactly the same time.
import random
import time
from typing import Callable, TypeVar
T = TypeVar("T")
class TransientStageError(Exception):
"""An error that may succeed when attempted again."""
def retry_stage(
operation: Callable[[], T],
*,
max_attempts: int = 4,
base_delay: float = 0.1,
max_delay: float = 2.0,
) -> T:
if max_attempts < 1:
raise ValueError("max_attempts must be at least 1")
for attempt in range(1, max_attempts + 1):
try:
return operation()
except TransientStageError as error:
if attempt == max_attempts:
raise
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
delay += random.uniform(0, delay * 0.1)
print(f"attempt {attempt} failed: {error}; retrying in {delay:.2f}s")
time.sleep(delay)
raise RuntimeError("unreachable")
attempts = 0
def flaky_fetch() -> str:
global attempts
attempts += 1
if attempts < 3:
raise TransientStageError("temporary storage timeout")
return "training-data-version-17"
if __name__ == "__main__":
print(retry_stage(flaky_fetch))The retry wrapper has a bounded number of attempts. It catches only the known transient exception. A programming error such as KeyError is allowed to fail immediately.
Make retries safe with idempotency
An idempotent stage produces the same intended result when run more than once with the same inputs. Idempotency matters because a worker can fail after completing an operation but before reporting success. The orchestrator then starts the stage again.
For example, a training stage can write to a temporary path and publish the final model only after the write completes:
- Build the output path from the run ID, stage name, and configuration fingerprint.
- Write the model to a temporary path.
- Verify that the temporary artifact can be read.
- Rename or publish it to the final path.
- On a retry, reuse the valid final artifact instead of training again.
Avoid appending to a shared file or creating an untracked “latest model” during a retry. Those side effects can produce duplicate records or overwrite another run.
Preserve context and checkpoints
Record the run ID, stage name, configuration fingerprint, input versions, attempt number, start time, and exception details. These fields let you distinguish a repeated transient failure from a new failure caused by changed inputs.
A successful stage should persist its output and metadata before downstream stages start. This output becomes a checkpoint. If evaluation fails, the pipeline can restart evaluation without repeating data preparation and training.
In a dependency graph, a failed stage should invalidate only its downstream work. A cached upstream result remains usable when its input versions and configuration fingerprint are unchanged.
Test failure behavior
Test the policy, not only the successful path. A unit test can use a fake operation that fails twice and succeeds on the third attempt. Another test should verify that the final transient error is raised after the attempt limit. Add a smoke test that runs the complete pipeline with a small, fixed dataset.
At the command line or in CI, return a nonzero exit code when retries are exhausted. An orchestrator can then mark the run failed and apply its own alerting policy. Do not hide failure by returning an empty model or a partial metric.
Exercise
A stage writes a model to a shared path and then times out before reporting success. What change makes a retry safer?
Show answer
Write to a unique temporary path, verify the artifact, and publish it atomically to a run-scoped final path. A retry can detect or replace that exact output without corrupting another run.