Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 10 · 45 minutes

Secure the ML pipeline with release gates

After this lesson you can
  • Write a script of seven gates that decides, by its exit code, whether a model may ship
  • Record where a model came from in a provenance file that the gates check
  • Break a release folder in two ways and read which gate sees which
Lab files of this lesson (19)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Northgate Parcels has a rule: no model goes to the service until someone has checked it. At the moment "someone" is a developer with a notebook, and the checks differ every time. Your lead asks you to turn the rule into a script that runs the same way every week, in the build, and stops the release by itself.

Recall

Lesson 8: what are the three layers that the loader demands?

The format (.json, .npz or .safetensors), the hash that the caller gives, and the content (exactly three arrays of finite numbers with the right shapes).

Lesson 3: what did the scan report for the clean model, and what limit did the course set?

The largest share was 0.25 at the place (5,5), and the limit is 0.60. A model is flagged when one patch moves more than that share of the predictions to one class.

The idea

A gate is a check that returns pass or fail, with a reason. A gate between two steps of a pipeline stops the model that fails. The exit code of a program is the number that it returns to the shell: 0 means success and any other number means failure. A build system reads it, so a gate that exits with 1 stops the release.

The gates use what the earlier lessons built, and they run in this order (the number in each text is the lesson that built the gate). A file that fails the file gate is not opened by the later gates. The thresholds are your policy: write them down and give them an owner.

The seven gates of a release
Release folderProvenanceFileDataReproduceClass floorBackdoor scanPrivacyReleaserecord names model and data (10)format allowed, hash matches (8)shape, range, classes, no copies (10)same weights after training again (10)every recall at least 0.80 (2)no patch moves over 0.60 of answers (3)membership attack right at most 0.60 (5)all seven passed, exit code 0Release folderProvenanceFileDataReproduceClass floorBackdoor scanPrivacyRelease12345678
  1. Release folder → Provenance: record names model and data (10)
  2. Provenance → File: format allowed, hash matches (8)
  3. File → Data: shape, range, classes, no copies (10)
  4. Data → Reproduce: same weights after training again (10)
  5. Reproduce → Class floor: every recall at least 0.80 (2)
  6. Class floor → Backdoor scan: no patch moves over 0.60 of answers (3)
  7. Backdoor scan → Privacy: membership attack right at most 0.60 (5)
  8. Privacy → Release: all seven passed, exit code 0

Worked example

1. Build a folder that can be released

A provenance record says where a thing came from: who made it, from which data, when, with which libraries, and the hash of each file. ship.py trains the course model, exports it in the safe format of lesson 8, saves the training data, and writes the record. sys.argv is the list of words that you typed after the program name. date.today() is today's date.

ship.py

"""ship.py: put a model, its training data and its provenance record into one folder that can be released."""
import json
import sys
from datetime import date
from pathlib import Path

import numpy as np
import sklearn

from common import digits, train
from safeload import export_json, sha256_of

folder = Path(sys.argv[1] if len(sys.argv) > 1 else "ship")
folder.mkdir(exist_ok=True)
X_train, X_test, y_train, y_test = digits()
export_json(train(X_train, y_train), folder / "model.json")
np.savez(folder / "train.npz", X=X_train, y=y_train)
record = {
    "model": "model.json",
    "model_sha256": sha256_of(folder / "model.json"),
    "data": "train.npz",
    "data_sha256": sha256_of(folder / "train.npz"),
    "data_source": "sklearn digits, split 75/25, seed 42",
    "owner": "you",
    "trained_on": date.today().isoformat(),
    "libraries": {"scikit-learn": sklearn.__version__, "numpy": np.__version__},
}
(folder / "provenance.json").write_text(json.dumps(record, indent=2) + "\n")
print("wrote", *sorted(p.name for p in folder.iterdir()))
python3 ship.py
wrote model.json provenance.json train.npz
cat ship/provenance.json
{
  "model": "model.json",
  "model_sha256": "5147ace33493d7c89bc906a586e01175b95ffc6154a0f0afdf5bd902fa0c02b8",
  "data": "train.npz",
  "data_sha256": "4ad4cc00c0aa84168e1615fc35ce83b5d56a9dac36459bc9fc3fd20b933ef44a",
  "data_source": "sklearn digits, split 75/25, seed 42",
  "owner": "you",
  "trained_on": "2026-11-21",
  "libraries": {
    "scikit-learn": "1.9.1",
    "numpy": "2.5.5"
  }
}

Your trained_on is your date, and your model_sha256 will differ: it hashes the printed weights, and another processor changes their last digits (lesson 8, step 5). data_sha256 is the same for everyone.

The parts of provenance.json
model.jsonthe model filea 64-digit hashits SHA-256 (yours differs)train.npzthe training data4ad4cc00...f44aits SHA-256 hashdigits, seed 42where the data came fromyouthe owner2026-11-21when it was trainedmodel.jsonthe model filea 64-digit hashits SHA-256 (yours differs)train.npzthe training data4ad4cc00...f44aits SHA-256 hashdigits, seed 42where the data came fromyouthe owner2026-11-21when it was trained

2. Write the gates

record.get(name) returns nothing, not an error, when a key is missing. gates.py imports the scan, the loader and the attack of earlier lessons. reproduce_gate trains again from the data in the record and compares the weights with the shipped ones: it assumes that the recipe is train of lesson 1, which settles, so the weights agree on any processor. plain accepts only a file name without a folder, so that a record cannot point out of its folder. leak_measure is the membership attack of lesson 5 with the threshold chosen on the data itself: the best case for the attacker, so a cautious measure. run collects the results in a fixed order as triples (name, passed, reason), and the last lines print them and exit with 0 or 1. *provenance_gate(...) puts the two items that the gate returns into the triple after the name. np.unique(X, axis=0) lists each different row once, so the gate counts the rows that are copies of another row.

gates.py

"""gates.py: the checks that a model folder must pass before release. Exit code 0 means release, 1 means hold.

    python3 gates.py ship        the folder holds model.json, train.npz and provenance.json
"""
import json
import sys
from pathlib import Path

import numpy as np

from backdoor import SCAN_LIMIT, scan
from common import digits, recalls, train
from leak import best_threshold, confidence
from poison import RECALL_FLOOR      # 0.80: one place for the number
from safeload import Refused, load_model, sha256_of

LEAK_LIMIT = 0.60       # a membership attack may not be right more often than this
MIN_SHARE = 0.05        # every class needs at least this share of the training data
FIELDS = ("model", "model_sha256", "data", "data_sha256", "owner", "trained_on", "libraries")


def data_gate(X, y):
    """The training data: right shape, pixels in range, no missing class, no duplicates."""
    problems = []
    if X.ndim != 2 or X.shape[1] != 64 or len(X) != len(y):
        return False, "wrong shape"
    if not np.isfinite(X).all() or X.min() < 0 or X.max() > 16:
        problems.append("pixels out of range")
    if np.bincount(y, minlength=10).min() < MIN_SHARE * len(y):
        problems.append("a class has under 5 percent of the data")
    copies = len(X) - len(np.unique(X, axis=0))
    if copies:
        problems.append(f"{copies} duplicate images")
    return not problems, "; ".join(problems) or f"{len(X)} images, all classes present, no duplicates"


def reproduce_gate(model, X, y):
    """Train again from the recorded data. The shipped model must have the same weights, up to 1e-3: `train` settles
    (lesson 1), so another processor moves them far less."""
    gap = np.abs(train(X, y).coef_ - model.coef_).max()
    if gap < 1e-3:
        return True, "trained again from the data, same weights"
    return False, f"model does not come from this data, largest weight difference {gap:.2g}"


def class_gate(model, X_val, y_val):
    """Per-class recall on trusted data."""
    r = recalls(model, X_val, y_val)
    return r.min() >= RECALL_FLOOR, f"worst class {int(r.argmin())}, recall {r.min():.2f}, floor {RECALL_FLOOR}"


def backdoor_gate(model, X_val):
    row, col, cls, share = scan(model, X_val)
    return share <= SCAN_LIMIT, f"largest move {share:.2f} to class {cls} at ({row},{col}), limit {SCAN_LIMIT}"


def leak_measure(model, X_in, X_out):
    """Best-case membership attack: the best confidence threshold on the data itself. 0.5 is no leak."""
    n = min(len(X_in), len(X_out), 300)
    c_in, c_out = confidence(model, X_in[:n]), confidence(model, X_out[:n])
    t = best_threshold(c_in, c_out)
    return ((c_in > t).sum() + (c_out <= t).sum()) / (2 * n)


def privacy_gate(model, X_train, X_val):
    m = leak_measure(model, X_train, X_val)
    return m <= LEAK_LIMIT, f"membership attack right {m:.2f}, limit {LEAK_LIMIT}"


def plain(name):
    """A file name without a folder: a record may not point out of its folder."""
    return isinstance(name, str) and name not in ("", ".", "..") and Path(name).name == name


def file_gate(folder, record):
    """The model file: an allowed format, and the hash that the provenance record gives."""
    if not plain(record.get("model")):
        return False, "the model name in the record is not a plain file name"
    path = folder / record["model"]
    try:
        load_model(path, record.get("model_sha256", ""))
    except (Refused, OSError) as reason:
        return False, str(reason)
    return True, f"{path.name} loads, hash matches"


def provenance_gate(folder, record):
    """The record: every field is there, and the data file is the one it names."""
    missing = [f for f in FIELDS if not record.get(f)]
    if missing:
        return False, "missing " + ", ".join(missing)
    if not (plain(record["model"]) and plain(record["data"])):
        return False, "a file name in the record is not a plain file name"
    try:
        same = sha256_of(folder / record["data"]) == record["data_sha256"]
    except OSError:
        same = False
    if not same:
        return False, "the data file is not the one in the record"
    return True, f"record by {record['owner']}, {record['trained_on']}"


def run(folder):
    folder = Path(folder)
    try:
        record = json.loads((folder / "provenance.json").read_text())
        if not isinstance(record, dict):
            raise ValueError
    except (OSError, ValueError):
        return [("provenance", False, "no provenance.json")]
    _, X_val, _, y_val = digits()                      # the trusted data stays on our side
    results = [("provenance", *provenance_gate(folder, record))]
    file_ok, file_detail = file_gate(folder, record)
    results.append(("file", file_ok, file_detail))
    if file_ok and plain(record.get("data")) and (folder / record["data"]).is_file():     # only now is the file opened
        model = load_model(folder / record["model"], record["model_sha256"])
        with np.load(folder / record["data"], allow_pickle=False) as d:
            X, y = d["X"], d["y"]
        results += [("data", *data_gate(X, y)), ("reproduce", *reproduce_gate(model, X, y)),
                    ("class floor", *class_gate(model, X_val, y_val)), ("backdoor scan", *backdoor_gate(model, X_val)),
                    ("privacy", *privacy_gate(model, X, X_val))]
    return results


if __name__ == "__main__":
    results = run(sys.argv[1])
    for name, ok, detail in results:
        print(f"{'pass' if ok else 'FAIL'}  {name:<15}{detail}")
    allowed = all(ok for _, ok, _ in results)
    print("release:", "ALLOWED" if allowed else "BLOCKED")
    sys.exit(0 if allowed else 1)

3. Run the gates on a good folder

python3 gates.py ship; echo "exit code $?"
pass  provenance     record by you, 2026-11-21
pass  file           model.json loads, hash matches
pass  data           1347 images, all classes present, no duplicates
pass  reproduce      trained again from the data, same weights
pass  class floor    worst class 8, recall 0.84, floor 0.8
pass  backdoor scan  largest move 0.25 to class 3 at (5,5), limit 0.6
pass  privacy        membership attack right 0.56, limit 0.6
release: ALLOWED
exit code 0
One line of the gate output
passverdictclass floorthe gateworst class 8the class with the lowest recallrecall 0.84the measurefloor 0.8the limitpassverdictclass floorthe gateworst class 8the class with the lowest recallrecall 0.84the measurefloor 0.8the limit

All seven pass, and the exit code is 0. In a build script, python3 gates.py ship && ./deploy.sh runs the second command only when the first exits with 0.

4. Change one byte of the model

Add one space at the end of model.json in a copy of the folder: a different file, the same weights.

cp -r ship ship-edit && echo " " >> ship-edit/model.json
python3 gates.py ship-edit; echo "exit code $?"
pass  provenance     record by you, 2026-11-21
FAIL  file           hash does not match
release: BLOCKED
exit code 1

The hash no longer matches, so the file gate fails, the later gates do not run, and the exit code is 1. Check the hash at the end of the build and again at deployment, and a swap in between shows.

Your turn

Run makebad.py. It makes two damaged copies of ship; shutil.copytree(a, b, dirs_exist_ok=True) copies a folder and does not fail when b exists. In ship-bad the training data is replaced by a file in which 131 copies of images of the digit 8 carry the label 3 (the injection of lesson 2); the record and the model are untouched. In ship-flip an attacker inside the pipeline flips 40 percent of the labels of the 8, retrains the model, and writes a record that matches both new files. Run the gates on each folder and read each line.

makebad.py

"""makebad.py: make two damaged copies of the folder ship: ship-bad and ship-flip."""
import json
import shutil
from pathlib import Path

import numpy as np

from common import train
from poison import flip_labels, inject
from safeload import export_json, sha256_of

with np.load("ship/train.npz") as d:
    X, y = d["X"], d["y"]

shutil.copytree("ship", "ship-bad", dirs_exist_ok=True)
X_bad, y_bad = inject(X, y, 8, 3, 131)                          # 131 copies of 8, labelled 3
np.savez("ship-bad/train.npz", X=X_bad, y=y_bad)                # record and model stay as they were
print("wrote ship-bad with", len(y_bad), "training rows")

shutil.copytree("ship", "ship-flip", dirs_exist_ok=True)
y_flip = flip_labels(y, 8, 3, 0.4)                              # no new rows, no copies
np.savez("ship-flip/train.npz", X=X, y=y_flip)
export_json(train(X, y_flip), "ship-flip/model.json")          # the attacker retrains ...
record = json.loads(Path("ship/provenance.json").read_text())
record["model_sha256"] = sha256_of("ship-flip/model.json")      # ... and writes a matching record
record["data_sha256"] = sha256_of("ship-flip/train.npz")
Path("ship-flip/provenance.json").write_text(json.dumps(record, indent=2) + "\n")
print("wrote ship-flip with", int((y_flip != y).sum()), "labels changed")

Then explain why the data gate and the reproduce gate pass on ship-flip, and which gate is the only one that can see it.

Check yourself

Why does a gate return a reason as well as pass or fail?

A person must decide what to do with a failed release. A reason and a measure (such as "recall 0.31, floor 0.8") say which part to examine.

The class floor, the scan and the privacy gate passed on ship-bad. Why?

The model of ship-bad is the clean model: only the data file was swapped, and those gates measure the model. The provenance gate sees the swapped file, the data gate the 131 copies, and the reproduce gate that the model does not come from this data.

Which gate sees ship-flip, and why do the others pass?

Only the class floor (the recall of the 8 is 0.65). The attacker wrote the record again, so the hashes match. The flipped labels add no copies and no new rows, so the data gate has nothing to count. The model was retrained on the flipped data, so the reproduce gate finds the same weights. A gate that compares the data with itself cannot see data that is wrong from the start. Only a measure on trusted data can.

Who may change the thresholds, and what must happen when they change?

A named owner, with a written reason, and a review by a second person. A threshold that a developer can relax during a deadline is not a control. Keep it in the repository.

What does the pass of all seven gates not tell you?

It does not tell you that the model is safe. It passed these seven checks at these thresholds: a trigger of a different shape (lesson 3), an attacker who sees the scores (lesson 5) or a poisoned trusted set (lesson 2) can still be there. A gate is a floor.

Field notes

  • MLSecOps means DevSecOps in the ML pipeline: version and hash the data, the code and the model; review changes; test automatically; sign what you release; monitor what runs. The gates are the test step.
  • Run the gates in the build, on a machine that the developer cannot change by hand, and store the output with the release. A gate that can be skipped is advice.
  • Add what a script cannot do: a review of who may write to each stage, a second person who approves a new data source, a signed model (OpenSSF Model Signing and Sigstore), and a plan to recall a bad model.
  • A provenance record answers "which release used the file that was later found to be poisoned?" in minutes.