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 06 · 45 minutes

Build a release script that promotes a model only when every gate passes

After this lesson you can
  • Run unit tests, an evaluation and a security scan as gates before a release
  • Record the promoted model in a registry file and roll back to the one before
  • Judge a gate result by an exit code that a build can use
Lab files of this lesson (27)

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

The data team has trained a new version of the login-risk model and asks to "copy it to production". Last quarter a model went live with an empty feature column, and nobody noticed for three weeks. The new rule is: no model reaches models/current unless a script says yes, and the script says yes only when every gate passes. You write the script, and you prove that it says no when it should.

Recall

Lesson 5: why is a read-only model file not enough on its own?

You own the file, so you can change the mode back, and so can any code that runs as you. The release script adds a second control: a hash and a record catch a changed file.

Lesson 2: where does the service check the hash of the model, and what does it do on a mismatch?

In load_model. It compares the SHA-256 of model.json with manifest.json and raises an error, so the service refuses to start with a changed file.

The idea

A release gate is a check that must pass before a version moves forward. A release pipeline runs the gates in order and promotes the version only when none fails. A CI service (it runs your checks on every change) would run this script and read its exit code. The gates here guard the release of a service; lesson 10 of "Securing models and the ML supply chain" builds gates for model security. New here are the registry, the promotion and the rollback.

This pipeline has six gates:

GatePasses whenWhat it stops
testsEvery test_*.py file in the lab folder (lessons 2 to 4 at this point) exits with code 0Broken code
accuracyAt least 0.90 on a fixed evaluation setA worse model
recallAt least 0.85 of the suspicious events are foundA model that looks good and misses attacks
hashmodel.json matches its manifestA file that changed after training
secretsThe scanner finds nothing in the model folderA key that was saved with the model
file modeNo write bit for group or othersA model file that anyone can change

An evaluation as a gate means that the model is scored on data that it never saw, and a number decides. The data is 500 fixed events (seed 99). Two numbers are needed: a model that misses many attacks can still pass an accuracy gate (version 3 below has 0.92 accuracy and 0.83 recall).

The registry is a JSON file, models/registry.json. Only the release script writes it. It holds one record for each promoted version, the current version and the history. Promoting copies the version into models/current, the folder that the service reads.

A release record of the registry
v1the version85eec023d661...c708b9219sha256 of model.json0.95accuracy on the evaluation set0.88recall of suspicious eventssix gatesall passed2026-11-21the day it was promotedv1the version85eec023d661...c708b9219sha256 of model.json0.95accuracy on the evaluation set0.88recall of suspicious eventssix gatesall passed2026-11-21the day it was promoted
The release pipeline
CandidateGatesPromoteCurrentRegistryrun all sixevery gate passeda gate failed,nothing changescopy the filesthen write the recordCandidateGatesPromoteCurrentRegistry12345
  1. Candidate → Gates: run all six
  2. Gates → Promote: every gate passed
  3. Gates → Candidate: a gate failed, nothing changes
  4. Promote → Current: copy the files
  5. Current → Registry: then write the record

Worked example

1. Save the release script

release.py has four parts. collect runs the gates and returns their raw results. gate judges the results and is a pure function, so a recorded results file can be judged without running anything. promote and rollback change the registry. write_json writes a temporary file and then calls os.replace, which swaps it in one step, so a reader never sees half a file. subprocess.run starts another program and gives back its exit code.

release.py

"""release.py: promote a model version only when every gate passes.

    python3 release.py v2 [--root .] [--today 2026-11-21]     run the gates, promote on success
    python3 release.py check results.json                     judge recorded gate results (exit code 0 or 1)
    python3 release.py rollback [--root .]                    go back to the version before the current one
Exit codes: 0 done, 1 a gate failed or there is nothing to roll back, 2 wrong use.
"""
import hashlib
import json
import os
import shutil
import stat
import subprocess
import sys
from datetime import date
from pathlib import Path

import scan_secrets
import service
from data import make_events

HERE = Path(__file__).resolve().parent
MIN_ACCURACY, MIN_RECALL = 0.90, 0.85
GATES = ["tests", "accuracy", "recall", "hash", "secrets", "file mode"]


def evaluate(model):
    """Accuracy and recall of the suspicious class on a fixed evaluation set (seed 99, 500 events)."""
    events = make_events(99, 500)
    guesses = [service.score(model, [e[f] for f in model["features"]]) >= 0.5 for e in events]
    right = sum(g == bool(e["suspicious"]) for g, e in zip(guesses, events))
    caught = sum(g for g, e in zip(guesses, events) if e["suspicious"])
    return round(right / len(events), 2), round(caught / sum(e["suspicious"] for e in events), 2)


def collect(version, root):
    """Run the gates for a version and return their raw results in one dict."""
    folder = Path(root, "models", version)
    text = (folder / "model.json").read_text()
    manifest = json.loads((folder / "manifest.json").read_text())
    hash_ok = hashlib.sha256(text.encode()).hexdigest() == manifest["sha256"]
    tests = subprocess.run([sys.executable, "-m", "unittest", "discover", "-p", "test_*.py", "-q"], cwd=HERE, capture_output=True)
    results = {"tests_passed": tests.returncode == 0, "hash_ok": hash_ok, "accuracy": None, "recall": None,
               "secrets_found": len(scan_secrets.scan(folder)), "model_mode": format(stat.S_IMODE((folder / "model.json").stat().st_mode), "o")}
    if hash_ok:   # a file that does not match its manifest is not evaluated
        results["accuracy"], results["recall"] = evaluate(json.loads(text))
    return results


def gate(r):
    """Judge the results. Return (gate name, passed, detail) for every gate."""
    return [("tests", r["tests_passed"], "unit tests exit 0" if r["tests_passed"] else "unit tests failed"),
            ("accuracy", (r["accuracy"] or 0) >= MIN_ACCURACY, f"{r['accuracy']} (needs {MIN_ACCURACY})"),
            ("recall", (r["recall"] or 0) >= MIN_RECALL, f"{r['recall']} (needs {MIN_RECALL})"),
            ("hash", r["hash_ok"], "matches the manifest" if r["hash_ok"] else "does not match the manifest"),
            ("secrets", r["secrets_found"] == 0, f"{r['secrets_found']} found"),
            ("file mode", not int(r["model_mode"], 8) & 0o022, f"mode {r['model_mode']} (no write for group or others)")]


def report(lines):
    for name, ok, detail in lines:
        print(("pass  " if ok else "FAIL  ") + name.ljust(10) + detail)
    return [name for name, ok, _ in lines if not ok]


def write_json(path, data):
    temp = Path(str(path) + ".tmp")
    temp.write_text(json.dumps(data, indent=1) + "\n")
    os.replace(temp, path)   # one step: a reader sees the old file or the new one, never half of it


def install(version, root):
    """Make models/current a copy of a version. Replace the files, so a read-only current file is no problem."""
    current = Path(root, "models", "current")
    current.mkdir(exist_ok=True)
    for name in ("model.json", "manifest.json"):
        shutil.copy(Path(root, "models", version, name), current / (name + ".tmp"))
        os.replace(current / (name + ".tmp"), current / name)
        (current / name).chmod(0o444)   # read-only for everybody, as lesson 5 asks


def load_registry(root):
    path = Path(root, "models", "registry.json")
    return json.loads(path.read_text()) if path.exists() else {"current": None, "history": [], "versions": {}}


def promote(version, root, today, results):
    registry = load_registry(root)
    manifest = json.loads(Path(root, "models", version, "manifest.json").read_text())
    registry["versions"][version] = {"sha256": manifest["sha256"], "accuracy": results["accuracy"], "recall": results["recall"],
                                     "gates": GATES, "promoted": today}
    registry["current"] = version
    if registry["history"][-1:] != [version]:
        registry["history"].append(version)
    install(version, root)
    write_json(Path(root, "models", "registry.json"), registry)


def rollback(root):
    registry = load_registry(root)
    if len(registry["history"]) < 2:
        print("nothing to roll back to")
        return 1
    registry["history"].pop()
    registry["current"] = registry["history"][-1]
    install(registry["current"], root)
    write_json(Path(root, "models", "registry.json"), registry)
    print("current is now", registry["current"])
    return 0


def main(argv):
    root, today = ".", date.today().isoformat()
    for flag, name in (("--root", "root"), ("--today", "today")):
        if flag in argv:
            i = argv.index(flag)
            value = argv[i + 1]
            root, today = (value, today) if name == "root" else (root, value)
            del argv[i:i + 2]
    if len(argv) == 2 and argv[0] == "check":
        return 1 if report(gate(json.load(open(argv[1])))) else 0
    if argv == ["rollback"]:
        return rollback(root)
    if len(argv) != 1:
        print(__doc__)
        return 2
    results = collect(argv[0], root)
    failed = report(gate(results))
    if failed:
        print(f"release {argv[0]}: BLOCKED by {', '.join(failed)}")
        return 1
    promote(argv[0], root, today, results)
    print(f"release {argv[0]}: promoted")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

2. Promote version 1

Version 1 exists since the set-up. Its release makes the registry.

python release.py v1
echo "exit code $?"
cat models/registry.json
pass  tests     unit tests exit 0
pass  accuracy  0.95 (needs 0.9)
pass  recall    0.88 (needs 0.85)
pass  hash      matches the manifest
pass  secrets   0 found
pass  file mode mode 644 (no write for group or others)
release v1: promoted
exit code 0
{
 "current": "v1",
 "history": [
  "v1"
 ],
 "versions": {
  "v1": {
   "sha256": "85eec023d661f4f82a784b933885c6a17069ac8bad159c4223c72a1c708b9219",
   "accuracy": 0.95,
   "recall": 0.88,
   "gates": [
    "tests",
    "accuracy",
    "recall",
    "hash",
    "secrets",
    "file mode"
   ],
   "promoted": "2026-11-21"
  }
 }
}

3. Block two bad versions

Version 2 is trained with the failed column set to zero, as if a pipeline had lost it. Version 3 loses new_device. The third argument of train.py names the lost column.

python train.py v2 1 failed
python train.py v3 1 new_device
python release.py v2
python release.py v3
echo "exit code $?"
{'version': 'v2', 'sha256': '67298e97c981233de882fea790df4cb099f03b0a86afae5e419b057c709c69f2'}
{'version': 'v3', 'sha256': '09644d676298df253b92ca90f4849d4eb99156b2be28798ecce51a85e1f1488f'}
pass  tests     unit tests exit 0
FAIL  accuracy  0.72 (needs 0.9)
FAIL  recall    0.1 (needs 0.85)
pass  hash      matches the manifest
pass  secrets   0 found
pass  file mode mode 644 (no write for group or others)
release v2: BLOCKED by accuracy, recall
pass  tests     unit tests exit 0
pass  accuracy  0.92 (needs 0.9)
FAIL  recall    0.83 (needs 0.85)
pass  hash      matches the manifest
pass  secrets   0 found
pass  file mode mode 644 (no write for group or others)
release v3: BLOCKED by recall
exit code 1

Version 3 passes the accuracy gate with 0.92 and fails the recall gate with 0.83: it misses too many attacks. This is why the pipeline has two evaluation numbers. The registry is unchanged: both releases stopped before promotion.

4. Block a changed file

Train version 4, then change one digit of its model file, as an attacker or a bad copy would.

python train.py v4 2
sed -i 's/"weights": \[/"weights": [1/' models/v4/model.json
python release.py v4
{'version': 'v4', 'sha256': '30a2a1a372fecef802efe726c68c3e090081ac4dd72bb17996738fb60b1cd671'}
pass  tests     unit tests exit 0
FAIL  accuracy  None (needs 0.9)
FAIL  recall    None (needs 0.85)
FAIL  hash      does not match the manifest
pass  secrets   0 found
pass  file mode mode 644 (no write for group or others)
release v4: BLOCKED by accuracy, recall, hash

The hash gate failed, so the script did not score the file: a model that does not match its manifest is not worth a score.

5. Promote a better version, then roll back

Train version 5 with another seed, release it, then roll back. rollback makes the version before the current one current again. grep prints lines that contain a text.

python train.py v5 2
python release.py v5 | tail -1
grep -A3 '"history"' models/registry.json | head -4
python release.py rollback
grep '"current"' models/registry.json
{'version': 'v5', 'sha256': '30a2a1a372fecef802efe726c68c3e090081ac4dd72bb17996738fb60b1cd671'}
release v5: promoted
 "history": [
  "v1",
  "v5"
 ],
current is now v1
 "current": "v1",

The releases and the rollback of steps 2 to 5, in order:

Five releases and a rollback
v1promoted: all six gates passedv2blocked by accuracy and recallv3blocked by recall: 0.83, needs 0.85v4blocked by the hash gate: file changedv5promoted: the history is v1, v5rollbackcurrent is v1 againv1promoted: all six gates passedv2blocked by accuracy and recallv3blocked by recall: 0.83, needs 0.85v4blocked by the hash gate: file changedv5promoted: the history is v1, v5rollbackcurrent is v1 again

6. Judge a recorded result

A CI service can run the gates in one place and judge in another. check reads a results file and prints the same table.

results-a.json

{"tests_passed": true, "hash_ok": true, "accuracy": 0.93, "recall": 0.91, "secrets_found": 0, "model_mode": "644"}

results-b.json

{"tests_passed": true, "hash_ok": true, "accuracy": 0.89, "recall": 0.91, "secrets_found": 0, "model_mode": "644"}
python release.py check results-a.json | tail -1
python release.py check results-a.json > /dev/null; echo "exit code $?"
python release.py check results-b.json | grep FAIL
python release.py check results-b.json > /dev/null; echo "exit code $?"
pass  file mode mode 644 (no write for group or others)
exit code 0
FAIL  accuracy  0.89 (needs 0.9)
exit code 1

> /dev/null throws the table away, so that only the exit code is left: 0 for a good result and 1 for a bad one. A CI service needs nothing more.

Your turn

Two more recorded results are below. Save them, and judge them with release.py check.

results-c.json

{"tests_passed": true, "hash_ok": false, "accuracy": null, "recall": null, "secrets_found": 0, "model_mode": "644"}

results-d.json

{"tests_passed": true, "hash_ok": true, "accuracy": 0.95, "recall": 0.84, "secrets_found": 0, "model_mode": "666"}

Then plant two faults in a copy of version 1 (cp -r models/v1 models/v6): add a file models/v6/notes.txt that holds the line api_key = abcdefghijklmnop1234, and give the model file mode 666 with chmod. Release v6.

Check yourself

The evaluation set is fixed. What is the risk of using the same set for every release?

Teams start to tune the model to that set, and the score stops saying how the model will do on new data. Keep a second set that nobody sees during development, and add the cases that went wrong in production (lesson 7).

Why does the pipeline copy the files first and write the registry last?

If the script stops in the middle, the registry still names the old version, and no reader sees half a file, because each file is swapped in one step. A stop between the two swaps leaves a new model beside an old manifest. The service refuses that pair (lesson 2) and lesson 10 reports it. A registry that named a version with no copied files would be a lie.

Who can still skip the gates, and how do you close that?

Anyone who can write to models/current can copy a file there by hand. Close it by file ownership: only the release user may write there (lesson 5). A real release job also signs the model, and the service verifies the signature. A hash proves that a file did not change, and a signature proves who made it.

Field notes

  • Run the same gates on every change of code and of data, and not only on a model release. The evaluation set, the thresholds and the scan rules are code: review them like code.
  • Add gates that fit your risk: a fairness check per group, a test with known attack inputs, a size and speed check, a licence check on the training data.
  • A real registry also records the data version, the code version and the person who ran the release.
  • The evaluation set has 500 events and 155 of them are suspicious. A recall of 0.88 on 155 events has a margin of about plus or minus 0.05, so a gate of 0.85 cannot tell 0.88 from 0.83 with confidence. A real gate needs a larger set, or a confidence interval on the number.
  • Try the rollback before you need it: an untried rollback is a hope.
  • NIST's Secure Software Development Framework (SSDF, SP 800-218) is the general base for the pipeline, and SP 800-218A is its profile for generative AI. Take the current text from NIST.