Sub topic 9
Idempotent Stages and Caching
This chapter assumes you can write Python functions and dataclasses, and that you have read the earlier chapters on stages, configuration, and reproducibility. It uses the TrainConfig dataclass and the stage functions load_data, split, train, and evaluate from those chapters. It adds a way to run each stage safely more than once and to skip work that has already been done.
Idempotency and caching are different ideas
Two terms are easy to confuse.
- An idempotent stage gives the same result and leaves the same state whether it runs once or five times with the same inputs. Idempotency is about safety.
- Caching means reusing a stored result instead of running the stage again. Caching is about speed.
Idempotency comes first. A cache is only correct if rerunning the stage would have produced the same output anyway. If a stage is not idempotent, a cache hides the problem until the day the cache is cleared.
Idempotency also lets an orchestrator or CI system retry a failed run without a person checking what was left half done. The failure-handling chapter relies on this.
What makes a stage idempotent
A stage is easier to make idempotent when it has these properties:
- Its output depends only on its arguments. It reads no wall-clock time, environment variables, or module-level state, and it uses no unseeded random numbers. Anything that matters is passed in, as the stages in this tutorial already do with
cfg. - It does not mutate its inputs. If
splitsortedXin place, a second call would see different data. - Its writes are replaceable, not cumulative. Writing the file
models/<key>.pkltwice leaves one file. Appending a row to a results table twice leaves two rows. - Its writes are atomic. A crash in the middle of a write must not leave a partial file that looks like a finished one.
Property 3 is where side-effecting stages usually fail. A "register model" stage that creates a new version every time it runs is not idempotent. Name the output after something deterministic, such as the run key, and make "already exists" a success.
Cache keys
A cache stores a result under a key. The key must change whenever the result could change, and it should stay the same otherwise. A stage's result can change for four reasons:
- the stage's parameters changed (for example
n_estimators) - the stage's code changed
- the data or upstream results changed
- the stage's name differs (a trivial case, but two stages with identical parameters must not collide)
The chapter on configuration showed config_fingerprint, which hashes the whole configuration. That is the wrong granularity here. Changing min_accuracy only moves the evaluation gate, so it should not force a retrain. Each stage should hash only the parameters it reads.
To cover upstream changes without hashing large arrays, chain the keys. Each stage's key includes the keys of the stages it depends on. If load_data changes, its key changes, so the split key changes, and so on down the graph. This works because every stage is deterministic. The same upstream key always means the same upstream data.
The dependency chapter showed the stages as a graph. The key chain follows the same edges.
A small file-based cache
The cache below stores one pickle file per key. It writes to a temporary file in the same directory and then calls os.replace, which swaps the file in as a single step on the same filesystem. A reader sees either the old state (no file) or the complete new file.
import hashlib
import json
import os
import pickle
import tempfile
from pathlib import Path
def digest(obj) -> str:
payload = json.dumps(obj, sort_keys=True, default=str)
return hashlib.sha256(payload.encode()).hexdigest()[:16]
class StageCache:
def __init__(self, root):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
def _path(self, key: str) -> Path:
return self.root / f"{key}.pkl"
def get(self, key: str):
path = self._path(key)
if not path.exists():
return False, None
with path.open("rb") as f:
return True, pickle.load(f)
def put(self, key: str, value) -> None:
fd, tmp = tempfile.mkstemp(dir=self.root, suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
pickle.dump(value, f)
os.replace(tmp, self._path(key))
except BaseException:
Path(tmp).unlink(missing_ok=True)
raiseWriting the same key twice is harmless. The second os.replace overwrites the first file with identical content, so put is idempotent.
The helper run_cached combines key construction, lookup, and execution:
def run_cached(cache, name, version, params, upstream_keys, fn, *args):
key = digest(
{
"stage": name,
"version": version,
"params": params,
"upstream": upstream_keys,
}
)
hit, value = cache.get(key)
if hit:
print(f"[cache hit] {name} {key}")
return key, value
print(f"[run] {name} {key}")
value = fn(*args)
cache.put(key, value)
return key, valueThe version argument is a string you bump by hand when you change the stage's code. Hashing source code automatically is tempting, but it also invalidates the cache after a comment edit or a rename, and it misses changes in helper functions the stage calls. A manual version is blunt, but you can see it and review it in a pull request.
Wiring the stages together
The stages are the same functions as before. They are repeated here so the example runs on its own.
import dataclasses
from dataclasses import dataclass
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
min_accuracy: float = 0.8
def load_data():
X, y = load_iris(return_X_y=True)
return X, y
def split(X, y, cfg):
return train_test_split(
X, y, test_size=cfg.test_size, random_state=cfg.seed, stratify=y
)
def train(X_train, y_train, cfg):
model = RandomForestClassifier(
n_estimators=cfg.n_estimators, random_state=cfg.seed
)
return model.fit(X_train, y_train)
def evaluate(model, X_test, y_test):
return {"accuracy": accuracy_score(y_test, model.predict(X_test))}
def run_cached_pipeline(cfg, cache):
k_data, (X, y) = run_cached(
cache, "load_data", "1", {"dataset": "iris"}, [], load_data
)
k_split, parts = run_cached(
cache, "split", "1",
{"seed": cfg.seed, "test_size": cfg.test_size},
[k_data], split, X, y, cfg,
)
X_train, X_test, y_train, y_test = parts
k_train, model = run_cached(
cache, "train", "1",
{"seed": cfg.seed, "n_estimators": cfg.n_estimators},
[k_split], train, X_train, y_train, cfg,
)
_, metrics = run_cached(
cache, "evaluate", "1", {},
[k_train, k_split], evaluate, model, X_test, y_test,
)
if metrics["accuracy"] < cfg.min_accuracy:
raise ValueError(
f"accuracy {metrics['accuracy']:.3f} is below the gate of {cfg.min_accuracy}"
)
return model, metrics
if __name__ == "__main__":
cache = StageCache(".stage_cache")
run_cached_pipeline(TrainConfig(), cache)
run_cached_pipeline(TrainConfig(), cache)
run_cached_pipeline(TrainConfig(n_estimators=200), cache)
run_cached_pipeline(TrainConfig(min_accuracy=0.9), cache)Put StageCache and run_cached in the same file, or import them. Read the code for these points:
- The evaluation gate sits outside
run_cached. It always runs, because it is cheap and its threshold is a decision, not a computation. evaluatehas no parameters of its own, so its params are{}. Its key still changes when the model or the split changes, throughupstream.trainlists onlyseedandn_estimators. It never readstest_sizedirectly. Atest_sizechange still reaches it throughk_split.
The four calls in __main__ behave as follows:
| Call | Stages that run | Why |
|---|---|---|
| 1. Default config | all four | The cache is empty. |
| 2. Default config again | none | All four keys exist. |
| 3. `n_estimators=200` | `train`, `evaluate` | Only `train` params changed, and `evaluate` inherits the new key. |
| 4. `min_accuracy=0.9` | none | No stage key includes that field. Only the gate runs. |
Run 4 is the case that whole-config fingerprinting gets wrong. The gate decides again, with a new threshold, using cached metrics.
One limit of this design: a cache hit still loads the upstream values, such as the full dataset, into memory, because the next stage may need them. For large data, store file paths or handles in the cache instead of the data, and load the data inside the stage that needs it.
Testing the cache
A cache bug returns old results with no error, so test it directly. These tests use pytest's tmp_path fixture so that no real cache is touched.
def test_cached_stage_runs_once(tmp_path):
cache = StageCache(tmp_path)
calls = []
def stage(x):
calls.append(x)
return x * 2
first = run_cached(cache, "double", "1", {}, [], stage, 21)
second = run_cached(cache, "double", "1", {}, [], stage, 21)
assert first == second
assert len(calls) == 1
def test_version_bump_invalidates(tmp_path):
cache = StageCache(tmp_path)
key_v1, _ = run_cached(cache, "double", "1", {}, [], lambda: 1)
key_v2, _ = run_cached(cache, "double", "2", {}, [], lambda: 1)
assert key_v1 != key_v2Combine these with the determinism test from the chapter on reproducibility. If a stage is not deterministic, caching it fixes one random answer in place, which hides the problem instead of solving it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| An edited stage returns the old result | The code changed but `version` did not | Bump `version` in the same commit as the code change. |
| A parameter change has no effect | The parameter is missing from `params` | List every config field the stage reads. A test that varies each field catches this. |
| Everything retrains when only a threshold changed | The key uses the whole-config fingerprint | Key each stage on only the fields it reads. |
| A corrupt or truncated cache file after a crash | The write was not atomic | Write to a temporary file, then `os.replace`. |
| Two runs differ with an identical key | A hidden input, such as the current time, an environment variable, or an unseeded generator | Pass the value in as an argument and include it in `params`. |
| A cache file fails to load after a library upgrade | Pickle depends on class definitions | Include library versions in the key, or clear the cache when the environment changes. |
| A results table has duplicate rows after a retry | The stage appends | Write to a path named by the key, or upsert by key. |
Idempotent side effects
Stages that publish something, such as writing a model to a registry directory, need the same discipline as the cache. Name the artifact after the run key and treat "already there" as success:
from pathlib import Path
import shutil
def publish(model_path, run_key, registry_dir):
target = Path(registry_dir) / run_key
if target.exists():
return target
target.parent.mkdir(parents=True, exist_ok=True)
staging = target.with_name(target.name + ".partial")
shutil.rmtree(staging, ignore_errors=True)
shutil.copytree(model_path, staging)
staging.rename(target)
return targetA crash before the final rename leaves only a .partial directory. The next attempt deletes it and starts again, and a finished target is never half written. Calling publish twice returns the same path and creates one artifact.
When not to cache
Caching every stage is not always right.
- Cheap stages. If a stage runs in milliseconds, the cache adds a lookup, storage, and a new place for bugs.
- Stages that must always run. Gates, notifications, and "write a run record" steps should execute every time.
- Fast-changing code. During development of a stage, a manual
versionbump on each edit is tedious. Skip caching for the stage you are editing, or use a throwaway cache directory. - Very large outputs. Storing a multi-gigabyte intermediate for every parameter combination fills the disk. Add an eviction rule, such as deleting entries not read for 30 days.
Orchestrators and data-versioning tools offer the same mechanism with more features, usually the same key idea of hashing inputs, parameters, and code. Understanding the key chain here makes their behavior easier to predict.
Exercise
You add a max_depth field to TrainConfig and pass it to RandomForestClassifier inside train, but you forget to add it to the params dictionary for the train stage. You run the pipeline with max_depth=3 after a run with max_depth=None. What happens, and what two changes prevent it?
Show answer
The train key is identical for both runs, so the second run gets a cache hit and returns the model trained with max_depth=None. The metrics look valid but belong to the wrong configuration. First, add "max_depth": cfg.max_depth to the train params. Second, bump the stage version so entries cached under the old key definition are not reused. A test that varies each config field and asserts the key changes would catch this.
Exercise
A "log the run" stage appends one line to runs.csv each time it executes. The orchestrator retries it after a timeout that happened after the line was written. Why is the stage not idempotent, and how would you change it?
Show answer
Each execution adds a line, so the retry creates a duplicate row. Make the write replaceable. Key the row by the run key and upsert it: read the file, skip or replace any row with that key, and write the result with a temporary file and os.replace. Alternatively, write one file per run named after the run key, so repeating the write leaves one file.
Exercise
Why does the gate in run_cached_pipeline sit outside run_cached, and what would go wrong if min_accuracy were part of the evaluate params?
Show answer
The gate is a cheap decision that must run every time, using the current threshold. If min_accuracy were in the evaluate params, changing the threshold would produce a new key and force evaluate to rerun, and its upstream key chain would be affected too if the field leaked into other params. The metrics themselves do not depend on the threshold, so recomputing them wastes time and a cache hit would be the correct behavior.