Sub topic 9
Idempotent Stages and Caching
Assume you know Python functions, dataclasses, Git, and the basic train-validate-test workflow. This chapter focuses on what happens when a pipeline stage runs again after a timeout, machine failure, or code change.
Why retries need safe stages
A pipeline stage is idempotent when running it more than once with the same inputs produces the same intended result without causing unwanted extra effects. For example, a feature-building stage can write the same output file each time. It should not append duplicate rows or create a different result because it ran twice.
Idempotency is different from speed. A stage can be idempotent but slow. Caching improves speed by reusing an output that was already produced for the same inputs.
A useful stage contract includes:
- Input data and its version.
- Configuration values.
- Code or environment version when it affects the result.
- Output location and format.
- A way to determine whether an existing output is valid.
| Property | Question to answer | Example |
|---|---|---|
| Idempotency | What happens when the stage runs twice? | The same output is replaced safely |
| Cache identity | Which inputs define the result? | Data digest plus configuration fingerprint |
| Atomicity | Can a partial output be mistaken for a complete one? | Write a temporary file, then rename it |
Build cache keys from real inputs
A cache key is an identifier for one exact computation. It should include every value that can change the output. A configuration fingerprint alone is not enough if the input data can change.
For a feature stage, a key might include:
- The version or digest of the input dataset.
- The stage name and implementation version.
- The relevant configuration.
- The runtime or dependency version when it affects results.
If an input is missing from the key, the cache can return stale or incorrect data. This is called a cache invalidation error.
The following example uses the SHA-256 digest of the input file and a sorted JSON representation of the configuration. It writes output atomically, so a failed write does not leave a file that looks complete.
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Any
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as file:
for block in iter(lambda: file.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def cache_key(stage: str, input_digest: str, config: dict[str, Any]) -> str:
config_text = json.dumps(config, sort_keys=True, separators=(",", ":"))
payload = f"{stage}|{input_digest}|{config_text}".encode()
return hashlib.sha256(payload).hexdigest()[:16]
def build_features(input_path: Path, scale: float) -> dict[str, float]:
text = input_path.read_text(encoding="utf-8")
nonempty_lines = [line for line in text.splitlines() if line.strip()]
return {
"row_count": len(nonempty_lines),
"scaled_row_count": len(nonempty_lines) * scale,
}
def run_feature_stage(
input_path: Path, cache_dir: Path, config: dict[str, Any]
) -> dict[str, float]:
input_digest = sha256_file(input_path)
key = cache_key("features-v1", input_digest, config)
output_path = cache_dir / f"{key}.json"
cache_dir.mkdir(parents=True, exist_ok=True)
if output_path.exists():
print(f"cache hit: {output_path.name}")
return json.loads(output_path.read_text(encoding="utf-8"))
result = build_features(input_path, config["scale"])
temporary_path = output_path.with_suffix(".tmp")
temporary_path.write_text(json.dumps(result, sort_keys=True), encoding="utf-8")
temporary_path.replace(output_path)
print(f"cache miss: wrote {output_path.name}")
return result
if __name__ == "__main__":
source = Path("training-data.txt")
source.write_text("red\nblue\n\n green\n", encoding="utf-8")
settings = {"scale": 2.0}
print(run_feature_stage(source, Path(".cache"), settings))
print(run_feature_stage(source, Path(".cache"), settings))The first call computes the result. The second call uses the cached result. Changing settings["scale"] or changing the source file creates a different key and causes a recomputation.
Idempotency in a dependency graph
In a directed acyclic graph, or DAG, downstream stages depend on upstream outputs. A changed input should invalidate that stage and the stages that consume its output.
A training stage should not write to a shared mutable model file without coordination. Two retries could overwrite each other. Prefer a run-specific artifact path based on the cache key, then publish a selected artifact only after evaluation succeeds.
Common errors
- Omitting a parameter from the key. The pipeline reuses an output created with different settings.
- Including unstable values such as the current time. Every run becomes a cache miss.
- Mutating input files in place. A retry no longer sees the original input.
- Writing directly to the final path. A process killed during the write may leave corrupt output.
- Caching failed results. Record success only after the output is complete and readable.
- Assuming deterministic code guarantees reproducibility. Seeds, package versions, hardware, and data versions can also matter.
A practical test runs the same stage twice and compares both the returned value and the artifact contents. Another test changes each key input and verifies that the cache is not reused.
Exercise
Why should a cache key include both the input data digest and the configuration?
Show answer
Either one can change the stage's output. Including both prevents a result made for old data or different settings from being reused.