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

Contain an AI incident, roll back and prove the recovery

After this lesson you can
  • Contain an incident with the smallest action that stops it
  • Roll back a model or an index to a version that a registry calls known-good
  • Verify the recovery with a test set and keep a record of every change
Lab files of this lesson (24)

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

It is Friday, and the alerts of week 2 are real: an injected document made Orbi send emails to an outside address, and since Wednesday the answers are worse. The playbook says "disable the tool, roll back, verify". You have a config file that the assistant reads at every request, a registry of the versions that someone tested, and a test set. You write the one script that does the switching, so that each change is the same on every run and leaves a line in a record.

Recall

Lesson 3: when did the drift start, and what changed on that day?

On Wednesday 2026-10-14 the PSI went from 0.01 to 1.36. On the same day the model version in the log changed from orbi-1.2 to orbi-1.3. The cause is a change you can reverse.

Lesson 6: why do the first actions say "contain before you analyse"?

Each minute with the tool on lets the injection act again. A containment can be undone, and the evidence is kept under hold. An investigation while the harm continues cannot make up for the harm.

The idea

Containment has steps of different size. Use the smallest one that stops the harm, because every step also stops something that works.

ActionWhat it stopsWhat it costs
Disable one toolMisuse of that toolOne feature, for example outside emails
Revoke a keyEverything that the key could reachEvery service that uses the key
Limit or block a userOne user's requestsThat user, so first check that the user is not a known integration
Switch to a safe modeAll tools and documents; the assistant only answers from its fixed rulesMost of the usefulness
Pause ingestionNew documents entering the knowledge baseFresh content
Roll back a versionA bad model or a bad indexThe newer features

A rollback is only safe to a version that someone tested. The registry is a file that says, for each model and each index version, whether it is known-good, retired or suspect. The switch refuses any other target. A revoked key stays revoked: the key owner issues a new one, and the lab has no command for that. Recovery is not the moment you switch. It is the moment a test set says that the active version answers correctly again. The answers of the two model versions are recorded in files, so the result is the same on every machine.

The assistant is not part of the lab. The file state/config.json stands for the switch that it reads (in a real system: a config service, a feature flag or a gateway rule). Every change is also written as a line in state/changes.jsonl: the time, the person, the action, the target, the value before and the value after.

The incident of week 2, from cause to recovery
Tue 13 Octindex kb-v7 is built after an ingestion run took in ext-41Wed 14 Octorbi-1.3 goes live; the PSI jumps and confidence fallsFri 16 Octcontain: disable the tool, revoke the key, safe mode, pause ingestionFri 16 Octroll back to orbi-1.2 and kb-v6, then verify: 19 of 20 correctAfter thatreturn to normal; the key stays revoked until a new one is issuedTue 13 Octindex kb-v7 is built after an ingestion runtook in ext-41Wed 14 Octorbi-1.3 goes live; the PSI jumps andconfidence fallsFri 16 Octcontain: disable the tool, revoke the key,safe mode, pause ingestionFri 16 Octroll back to orbi-1.2 and kb-v6, thenverify: 19 of 20 correctAfter thatreturn to normal; the key stays revokeduntil a new one is issued

Worked example

1. Look at the state

python3 makelogs.py writes the state files again, so that you start where this lesson starts. Then print three of them in one line each.

python3 makelogs.py
python3 -c "
import json
for n in ('config', 'keys', 'registry'):
    print(n, json.dumps(json.load(open(f'state/{n}.json'))))
"
wrote logs/, testset/, state/ and audit/
config {"model": "orbi-1.3", "index": "kb-v7", "mode": "normal", "ingestion": "running", "tools": {"track_parcel": true, "search_kb": true, "issue_refund": true, "send_email_internal": true, "send_email_external": true}}
keys {"key-mail-gateway": "active", "key-refunds": "active", "key-partner-sync": "active"}
registry {"models": {"orbi-1.1": {"status": "retired"}, "orbi-1.2": {"status": "known-good"}, "orbi-1.3": {"status": "suspect", "note": "live since 14 Oct, confidence falls"}}, "indexes": {"kb-v6": {"status": "known-good"}, "kb-v7": {"status": "suspect", "note": "built 13 Oct after an ingestion run that took in ext-41"}}}

The config says that orbi-1.3 and the index kb-v7 are active. The registry calls orbi-1.2 and kb-v6 known-good, orbi-1.3 and kb-v7 suspect, and orbi-1.1 retired. The log of week 2 shows that both injected requests read the document ext-41.

2. Write the switch

respond.py is the only program that changes the state. change sets one value in a state file, and appends one line to the record. rollback reads the registry first and refuses a version that is not known-good. score compares the recorded answers of the active model with the expected answers of the test set. getpass.getuser() gives your user name. A KeyError is the error of a dictionary for a name that it does not hold. The script catches it, and IndexError and ValueError, prints "refused" and exits with 2, so that another program can tell "done" (0) from "refused" (2).

respond.py

"""respond.py: contain, roll back and verify. Every change is written to state/changes.jsonl.

    python3 respond.py status
    python3 respond.py disable-tool NAME | enable-tool NAME | revoke-key NAME | safe-mode on|off
    python3 respond.py pause-ingest | resume-ingest | limit-user USER REQUESTS_A_DAY (0 blocks the user)
    python3 respond.py rollback model|index VERSION
    python3 respond.py verify          the active model must answer 90 percent of the test set
"""
import getpass
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent
STATE = ROOT / "state"
PASS_AT = 0.90
KINDS = {"model": "models", "index": "indexes"}      # the name in config.json, the table in registry.json


def load(path):
    return json.loads(Path(path).read_text())


def change(file, path, new, action, create=False):
    """Set data[path] in a state file, and write one line to the changes file. An unknown name raises KeyError."""
    data = load(STATE / file)
    node = data
    for key in path[:-1]:
        node = node[key]
    before = node.get(path[-1]) if create else node[path[-1]]
    node[path[-1]] = new
    (STATE / file).write_text(json.dumps(data, indent=2) + "\n")
    line = {"at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "by": getpass.getuser(),
            "action": action, "target": "/".join(path), "before": before, "after": new}
    with open(STATE / "changes.jsonl", "a") as f:
        f.write(json.dumps(line) + "\n")
    print(f"{action}: {'/'.join(path)} {before} -> {new}")


def rollback(kind, version):
    """Switch the model or the index to a version that the registry calls known-good, and nothing else."""
    entry = load(STATE / "registry.json")[KINDS[kind]][version]
    if entry["status"] != "known-good":
        raise ValueError(f"{version} is {entry['status']}, not known-good")
    change("config.json", [kind], version, "rollback")


def score():
    """(model, right, total): the recorded answers of the active model against the expected answers."""
    model = load(STATE / "config.json")["model"]
    expected = load(ROOT / "testset" / "expected.json")
    answers = load(ROOT / "testset" / f"answers-{model}.json")
    return model, sum(answers.get(e["id"], "").strip().lower() == e["expected"] for e in expected), len(expected)


def verify():
    model, right, total = score()
    ok = right / total >= PASS_AT
    print(f"verify {model}: {right} of {total} correct, {'PASS' if ok else 'FAIL'}")
    return 0 if ok else 1


def run(command, args):
    cfg = "config.json"
    if command == "status":
        print(json.dumps(load(STATE / cfg), indent=2))
    elif command in ("disable-tool", "enable-tool"):
        change(cfg, ["tools", args[0]], command == "enable-tool", command)
    elif command == "revoke-key":
        change("keys.json", [args[0]], "revoked", command)
    elif command == "safe-mode":
        if args[0] not in ("on", "off"):
            raise ValueError("safe-mode needs on or off")
        change(cfg, ["mode"], "safe" if args[0] == "on" else "normal", command)
    elif command == "limit-user":
        if not args[0].startswith("u_") or not args[1].isdigit():
            raise ValueError("limit-user needs a user id that starts with u_ and a whole number")
        change("limits.json", [args[0]], int(args[1]), command, create=True)
    elif command in ("pause-ingest", "resume-ingest"):
        change(cfg, ["ingestion"], "paused" if command == "pause-ingest" else "running", command)
    elif command == "rollback":
        rollback(args[0], args[1])
    elif command == "verify":
        return verify()
    else:
        raise ValueError("unknown command " + command)
    return 0


if __name__ == "__main__":
    try:
        sys.exit(run(sys.argv[1], sys.argv[2:]))
    except (IndexError, KeyError, ValueError) as err:
        print("refused:", "unknown name or missing argument" if isinstance(err, (IndexError, KeyError)) else err)
        sys.exit(2)

3. Check the active model first

verify passes when at least 90 percent of the 20 test questions are answered correctly.

python3 respond.py verify
echo "exit code $?"
verify orbi-1.3: 13 of 20 correct, FAIL
exit code 1

The live model fails: 13 of 20. This is the evidence that a rollback is needed. Keep it.

4. Contain

Four commands from the playbook of lesson 6. The first one stops the misuse. The key is the one that the mail tool uses. Safe mode and paused ingestion are wider steps: in a real incident you use them only when the smaller steps do not stop the harm. Here you run all four to see each one.

python3 respond.py disable-tool send_email_external
python3 respond.py revoke-key key-mail-gateway
python3 respond.py safe-mode on
python3 respond.py pause-ingest
disable-tool: tools/send_email_external True -> False
revoke-key: key-mail-gateway active -> revoked
safe-mode: mode normal -> safe
pause-ingest: ingestion running -> paused

5. Limit one user

limit-user sets the number of requests that one user may send in a day, and 0 blocks the user. The file state/limits.json stands for the gateway that enforces it. Lesson 4 found the cost attack from the user u_3ca43ca6. A user id must start with u_: the log holds no raw user names, and a raw name is a typing error here.

python3 respond.py limit-user u_3ca43ca6 30
limit-user: u_3ca43ca6 None -> 30

6. Try the bad inputs

The tool must refuse what it cannot do safely: a rollback to a retired or suspect version, a safe mode that is neither on nor off, and a name that is not a user id.

python3 respond.py rollback model orbi-1.1
echo "exit code $?"
python3 respond.py rollback model orbi-1.3
python3 respond.py safe-mode banana
python3 respond.py limit-user cust-0914 30
echo "exit code $?"
refused: orbi-1.1 is retired, not known-good
exit code 2
refused: orbi-1.3 is suspect, not known-good
refused: safe-mode needs on or off
refused: limit-user needs a user id that starts with u_ and a whole number
exit code 2

All four are refused with exit code 2, and nothing was changed.

7. Roll back and verify

python3 respond.py rollback model orbi-1.2
python3 respond.py rollback index kb-v6
python3 respond.py verify
echo "exit code $?"
rollback: model orbi-1.3 -> orbi-1.2
rollback: index kb-v7 -> kb-v6
verify orbi-1.2: 19 of 20 correct, PASS
exit code 0

Now 19 of 20 answers are right and the check passes. The one wrong answer is in the known-good model too, so it is an old problem. The registry note gives the reason for the index rollback: kb-v7 took in ext-41. verify scores the model only. It cannot see the index.

8. Return to normal

A containment ends when the cause is gone. Assume that ext-41 is now removed from the mail queue and from the index (the lab does not model this), and that the test set passes. Undo the wide steps and give the tool back: enable-tool is the opposite of disable-tool. Run verify last. The user limit stays until the owner of the user decides. The revoked key stays revoked, so the mail tool works only when the key owner issues a new key.

python3 respond.py enable-tool send_email_external
python3 respond.py safe-mode off
python3 respond.py resume-ingest
python3 respond.py verify
enable-tool: tools/send_email_external False -> True
safe-mode: mode safe -> normal
resume-ingest: ingestion paused -> running
verify orbi-1.2: 19 of 20 correct, PASS

9. Read the record

Print the lines of state/changes.jsonl without the time and the name.

python3 -c "
import json
for line in open('state/changes.jsonl'):
    c = json.loads(line)
    print(c['action'], c['target'], c['before'], '->', c['after'])
"
disable-tool tools/send_email_external True -> False
revoke-key key-mail-gateway active -> revoked
safe-mode mode normal -> safe
pause-ingest ingestion running -> paused
limit-user u_3ca43ca6 None -> 30
rollback model orbi-1.3 -> orbi-1.2
rollback index kb-v7 -> kb-v6
enable-tool tools/send_email_external False -> True
safe-mode mode safe -> normal
resume-ingest ingestion paused -> running
One line of the change record
rollbackthe actionmodelthe targetorbi-1.3the value beforeorbi-1.2the value afterrollbackthe actionmodelthe targetorbi-1.3the value beforeorbi-1.2the value after

Ten changes, each with its old value, so every one can be undone. The four refused inputs left no line.

Your turn

Files you need: makelogs.py and respond.py (kr-lab.sh for this lesson gives both). Reset the state with python3 makelogs.py. Then use only respond.py and do exactly four things, in this order: disable the tool send_email_external, roll the model back to orbi-1.2, roll the index back to kb-v6, and pause ingestion. Verify the result. Then try one more rollback, to orbi-1.3.

Answer from your own terminal.

Check yourself

Why does the switch refuse a rollback to a version that the registry does not call known-good?

An old version is not always a good version. It may have a known fault, an expired licence, or a hole that was fixed later. The registry records what someone tested, and the refusal puts that check in the tool, so that a person under stress cannot skip it.

You disabled one tool and the alerts stop. Is the incident over?

No. The harm is stopped, but the cause is still there: the injected document must be removed from its source (the mail queue) and, if the ingestion took it in, from the index. Eradication means removing it and checking the rest. Recovery means the test set passes. Only then do you turn the tool back on, with the evidence of what changed.

The test set has 20 questions and the threshold is 90 percent. What does a pass not prove?

It proves that these 20 questions are answered correctly. It does not prove that the model is safe, that the index holds no poisoned text, or that the other answers are right. A test set shows that a known problem is gone, not that no problem is left.

Why does `changes.jsonl` hold the value before as well as the value after?

With the value before, every change can be reversed, and a reviewer can rebuild the order of events. A record of the new value only tells you where you are, not where you came from.

Field notes

  • The change record is an audit trail. Write it to a place that the responder cannot edit, seal it with a digest as in lesson 1, step 7, and add the ticket number. A record that the person who acts can rewrite proves nothing.
  • Test the rollback before the incident. Run verify against the known-good version every month, and set the date in the registry.
  • Prefer a switch with two states and a clear default: safe mode on means no tools. Ten options at 03:10 lead to a mistake.
  • An index rollback is not checked by this model test set. Add a retrieval test: questions whose answers must come from a named document, and documents that must never be returned.
  • After recovery, watch the detectors for a week with a lower threshold: a second try often follows the first. Then write the review.