Sub topic 17
Guardrails: cooldowns, budgets, and human approval
This chapter assumes you know the trigger types and the trigger policy from the earlier chapters. It also assumes you know the pipeline stages: validate, train, evaluate, register, roll out. It also assumes basic Python. Here you add the controls that stop an automated pipeline from hurting you when its own logic misfires.
Why an automated pipeline needs guardrails
A trigger policy decides when to retrain. A guardrail limits what the pipeline may do even when the policy says "go". The two are separate because the policy can be wrong in ways it cannot detect itself.
Three failure modes come up most often:
- Retraining loops. A trigger fires, the pipeline trains and deploys, and the new model still looks drifted against the old reference. The trigger fires again, and this repeats.
- Runaway cost. A noisy signal or a bug starts many training runs. Each run uses GPUs, storage, and labeling or data-warehouse queries.
- Bad-data poisoning. An upstream bug, an outage, or an attack corrupts the new data. The pipeline retrains on it, passes a weak check, and ships a worse model.
Cooldowns
A cooldown is a minimum time between two training runs. The should_retrain function from the trigger policy chapter already checks one: it returns False with reason cooldown if the model is younger than cooldown.
Pick the cooldown from three quantities:
- How long a full run takes, including validation and rollout. The cooldown should never be shorter than this.
- How long the rollout observation window lasts. You cannot judge a new model's drift against a reference until it has served traffic.
- How fast the world changes. A fraud model may tolerate a cooldown of hours. A model that retrains on weekly seasonal data gains nothing from retraining daily.
A cooldown breaks the loop described above, but it only slows it down. If the loop is caused by a bad reference, fix the reference. After a successful promotion, reset the drift reference to the data the new model was trained on. Otherwise PSI against the old reference stays high forever.
Cooldowns should measure from the last attempt, not only the last success. If failed runs do not start the cooldown, a persistent failure retries continuously.
Budgets
A budget is a hard cap on resources over a time window. Useful caps are:
- Runs per window, for example at most 4 runs per 7 days.
- Compute spend per window, in currency or GPU-hours.
- Consecutive failures, after which the pipeline stops and pages a person.
Enforce budgets before launching the expensive work, and record usage in a store that survives restarts. The sketch below keeps a run log and refuses to start when a cap is hit.
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
@dataclass(frozen=True)
class BudgetConfig:
max_runs: int = 4
window: timedelta = timedelta(days=7)
max_spend: float = 500.0
max_consecutive_failures: int = 3
@dataclass
class RunRecord:
started: datetime
cost: float
succeeded: bool
@dataclass
class RunLog:
records: list = field(default_factory=list)
def in_window(self, now, window):
return [r for r in self.records if now - r.started <= window]
def consecutive_failures(self):
count = 0
for record in reversed(self.records):
if record.succeeded:
break
count += 1
return count
def budget_allows(now, log, cfg, estimated_cost):
"""Return (allowed, reason) before a run starts."""
if log.consecutive_failures() >= cfg.max_consecutive_failures:
return False, "too_many_failures"
recent = log.in_window(now, cfg.window)
if len(recent) >= cfg.max_runs:
return False, "run_limit"
if sum(r.cost for r in recent) + estimated_cost > cfg.max_spend:
return False, "spend_limit"
return True, "ok"
now = datetime(2026, 11, 30, tzinfo=timezone.utc)
log = RunLog([
RunRecord(now - timedelta(days=1), 180.0, True),
RunRecord(now - timedelta(days=3), 200.0, True),
])
print(budget_allows(now, log, BudgetConfig(), 150.0))
print(budget_allows(now, log, BudgetConfig(), 100.0))The first call is blocked by spend_limit: 380 already spent plus 150 exceeds 500. The second call is allowed, because 380 plus 100 is under the cap.
Budgets need an estimated cost, so keep the cost of past runs and use the recent maximum as the estimate. Also set a per-run timeout in the orchestrator. A budget on runs does not help if one run hangs for days.
Guarding against poisoned data
Cooldowns and budgets limit how often the pipeline runs. They do not stop one bad run. Defend against poisoning in layers:
- Data validation before training, from the earlier chapter: schema, null rates, ranges, and row counts. Treat a sudden drop or spike in volume as suspect rather than as a reason to retrain.
- Drift that is too large. A PSI above a very high ceiling, such as 1.0, usually means a pipeline bug, not a real change in the world. Block the run and ask a person to look.
- The evaluation gate. Score the challenger on a held-out set that the new data cannot influence, such as a frozen golden set or a time-based slice that was labeled independently.
- Label checks. If labels come from user behavior, an attacker or a bug can shape them. Compare the new label rate with its history.
Note the two-sided use of drift: moderate drift can trigger a run, and extreme drift should block one.
Human approval
Automation should not mean the absence of people. Human approval is a gate where a person must say yes before a step proceeds. Decide where to place it by asking how costly a bad outcome is and how hard it is to undo.
| Step | Typical approval policy |
|---|---|
| Start a training run | Automatic, within budget |
| Register a challenger | Automatic |
| Promote to staging or shadow | Automatic if the gate passes |
| Promote to full production | Required for high-risk models, optional for low-risk ones |
| Exceed a budget | Always required |
| Run after extreme drift | Always required |
Make approval useful, not ceremonial. The approver should see the evaluation report, the metric deltas against the champion, the data validation summary, the drift values, and the lineage of data and code. Give approvals an expiry, such as 48 hours, after which the run is cancelled, so stale candidates do not get promoted against changed conditions.
Putting the guardrails together
Compose the checks in order from cheapest to most expensive, and always record the reason for a block. The function below combines the earlier policy functions with a budget and a drift ceiling.
def guarded_decision(trigger, budget, extreme_drift, needs_approval):
"""Combine trigger, budget, and drift ceiling into one outcome.
Each argument is a (bool, reason) pair except the last two flags.
"""
fire, trigger_reason = trigger
if not fire:
return "skip", trigger_reason
allowed, budget_reason = budget
if not allowed:
return "needs_approval", budget_reason
if extreme_drift:
return "needs_approval", "extreme_drift"
if needs_approval:
return "needs_approval", "production_promotion"
return "run", trigger_reason
print(guarded_decision((True, "drift_with_enough_data"), (True, "ok"), False, False))
print(guarded_decision((True, "drift_with_enough_data"), (False, "spend_limit"), False, False))
print(guarded_decision((True, "max_model_age"), (True, "ok"), True, False))The outcomes are run, needs_approval, and skip. Log every one of them with its reason. Those logs let you answer the question "why did we retrain on Tuesday?" and "why did we not retrain last month?" months later.
Common mistakes
- Starting the cooldown only after successes, which allows tight retry loops on failure.
- Forgetting to reset the drift reference after promotion.
- Keeping budget counters in memory, so a restarted scheduler forgets its spend.
- Applying the same approval policy to every model regardless of risk.
- Having no way to pause the pipeline. Provide a single kill switch, such as a flag the trigger checks first, so an on-call engineer can stop automatic runs in seconds.
Exercise
A drift trigger fires, training finishes, and the new model is promoted. Two hours later the trigger fires again and the cycle repeats every few hours. Name two guardrail or configuration fixes, and say which one addresses the root cause.
Show answer
First, add or lengthen a cooldown so runs cannot start within the training and observation period. Second, reset the drift reference to the new model's training data after promotion. The reset addresses the root cause: the PSI is still computed against the old reference, so it stays above the threshold no matter how many times the model is retrained. The cooldown only slows the loop.
Exercise
In the budget sketch, the log holds two successful runs costing 180 and 200 inside the window, and the cap is 500. Does a run with an estimated cost of 120 start? Why or why not?
Show answer
No. The spend would be 180 + 200 + 120 = 500 and the code blocks when the total is greater than the cap, so 500 is allowed, not blocked. The run does start. A run estimated at 121 would be blocked with reason spend_limit.