Platform Engineering · Lesson 334

Explainable Automation: Action Records, Reasons, and Replay Sets for Evaluating AIOps Changes

When automation changes production, someone will ask why, often in the middle of an incident, and the answer has to be on record rather than reconstructed. Every automated action writes an action record: the trigger, the evidence it used (stored with a hash), the rule or model and prompt version that decided, a reason that cites that evidence, the alternatives it rejected, what it ran under which identity, and how to undo it. Every change to the automation is then tested against a replay set of labelled past cases, including cases where the right action was to do nothing, before it ships. This lesson follows one automated restart and shows two failures: an action nobody can explain, and a prompt change that shipped without a replay.

Difficulty: Advanced · Know this first: Lesson 332, Lesson 333

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from an automated action to a person who knows what it did and why. It is a worked example, not a measurement. The reason, action record, and replay hops decide whether an action can be explained, and whether a change was safe to ship.

Try it: can you explain your automation, and trust its next version?

Pick what each action leaves behind, whether changes are replayed, and what happens to overrides.

3minutes to explain an action
9 of 10regressions caught before release
1,400cases in the set after a year

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Explainable automation grows in four levels: recording actions, explaining them, gating changes, and closing the loop.

Basic — Record every action

At the basic level every action can be traced to an automation.

  • One identity per automation.
  • An action record with trigger, call, result, and undo.
  • A link to the record in the incident channel.

Where it breaks: a log line from a shared account as the only trace.

Try it: Basic

Something scaled a deployment down. What is the first question the record must answer?

Now do it: List your automations and the identity each acts as.

Intermediate — Explain it

At the intermediate level every action carries its reasons.

  • Evidence stored with hashes; rule, model, and prompt versions.
  • A reason with evidence IDs, checked for valid citations.
  • Rejected alternatives and the confidence.

Try it: Intermediate

Why hash the evidence instead of linking to the dashboard?

Now do it: Add stored query results to one automation's records.

Advanced — Gate every change

At the advanced level no change ships without a replay.

  • A versioned replay set with hard negatives, covering every alert type the automation handles.
  • Precision, recall, wrong actions on hard negatives, and citation validity, against the current version.
  • The replay as a required step in the pipeline for rules, models, prompts, and tool lists.

Try it: Advanced

A candidate has higher recall and lower precision than the current version. Ship it?

Now do it: Write the gate rule for your next prompt change.

Master — Close the loop

At the master level the automation learns from its own mistakes, measurably.

  • Every override and rejected recommendation labelled and added to the set.
  • Published precision, override rate, and time-to-explain per automation.
  • Records kept and searchable for audits and post-incident reviews.

Trade-off: records, replays, and reviews add work to every change; without them, each change is a bet you find out about from the people approving its mistakes.

Try it: Master

An automation's override rate rises from 5% to 40% in a week. What do you do?

Now do it: Alert on override rate per automation.

Go deeper

An action record, as one JSON document (the fields matter more than the format; store it append-only and link it from the incident):

{"id": "act-0412", "at": "2026-11-28T14:05:12Z",
 "automation": "remediator-search", "identity": "sa-remediator-search",
 "trigger": {"alert": "7f3a", "name": "JvmHeapHigh", "service": "search"},
 "decision": {"rule": "R-12", "version": 3, "score": 0.97, "threshold": 0.95},
 "reason": "Heap at or above 95% on 3 of 3 pods for 10 minutes (q-118); runbook R-12 step 2: restart.",
 "alternatives": [{"option": "scale out", "rejected": "at maximum replicas"},
                  {"option": "roll back", "rejected": "no deploy in 24 hours"}],
 "evidence": [{"id": "q-118", "query": "max_over_time(jvm_heap_used_ratio[10m])", "sha256": "9c1e..."}],
 "call": "kubectl rollout restart deployment/search", "approval": null,
 "result": "heap 41% after restart", "undo": "none needed: stateless pods"}

The replay gate, in outline: for each case in the set, run the candidate and the current version on the stored evidence; compare each decision with the label; compute precision, recall, and wrong actions on hard negatives; fail the change if the candidate is worse on any of them or makes a new wrong action anywhere. Store the scored comparison with the change.

For model-based automation, the same records feed tracing: OpenTelemetry's generative AI semantic conventions name the model and token attributes, and the action record ID can be a span attribute that joins the trace to the record.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The least disruptive action.

Timeline

  • MondayThe triage assistant's prompt gains a line: "prefer the least disruptive action". It ships with the weekly configuration change, without a replay.
  • Monday to ThursdayFor disk-full alerts it now recommends restarting the pod, which frees nothing. Each recommendation is well formatted and cites the disk metric; on-call engineers approve 31 of them, and the disks are then cleaned up by hand.
  • ThursdayThe weekly review sees the override rate on disk alerts jump to 60%. The replay set, run after the fact, shows version 14 recommends a restart for 35 of its 38 disk cases.
  • ThursdayVersion 13 is restored.

What changed after

The replay gate became a required step for rule, model, prompt, and tool-list changes; precision on hard negatives must not fall; and overrides are added to the replay set every week.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Linux with jq (sudo apt install jq), sha256sum (coreutils), and Python 3.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Store one piece of evidence, then write an action record that cites it by ID and SHA-256 hash, plus three more records.

    mkdir -p ~/labs/explain && cd ~/labs/explain
    printf '%s\n' '{"id":"q-118","query":"max_over_time(jvm_heap_used_ratio[10m])","result":[0.97,0.98,0.97]}' > ev-q118.json
    H=$(sha256sum ev-q118.json | cut -d " " -f 1)
    jq -n -c --arg h "$H" '{id: "act-0412", automation: "remediator-search", rule: "R-12", version: 3, call: "kubectl rollout restart deployment/search", reason: "heap at or above 95% on 3 of 3 pods for 10 minutes (q-118)", alternatives: [{option: "scale out", rejected: "at maximum replicas"}, {option: "roll back", rejected: "no deploy in 24 hours"}], evidence: [{id: "q-118", file: "ev-q118.json", sha256: $h}], undo: "none needed", overridden: false}' > actions.jsonl
    for r in '{"id":"act-0413","automation":"remediator-search","rule":"R-12","version":3,"call":"kubectl rollout restart deployment/search","overridden":false}' '{"id":"act-0414","automation":"remediator-disk","rule":"D-4","version":2,"call":"kubectl rollout restart deployment/orders-api","overridden":true}' '{"id":"act-0415","automation":"remediator-disk","rule":"D-4","version":2,"call":"kubectl rollout restart deployment/orders-api","overridden":true}'; do echo "$r" >> actions.jsonl; done
    wc -l actions.jsonl

    Options: jq -n builds JSON from nothing; --arg h passes the hash in as a string, so it is quoted correctly.

    Expect: 4 actions.jsonl.

    Clean up: rm -rf ~/labs/explain.

  2. Answer "why were the search pods restarted?" from the record alone.

    jq -r 'select(.id == "act-0412") | "\(.id) by \(.automation), rule \(.rule) v\(.version)\n  ran: \(.call)\n  why: \(.reason)\n  not: \(.alternatives | map(.option + " (" + .rejected + ")") | join(", "))\n  undo: \(.undo)"' actions.jsonl

    Options: \(...) inside a jq string inserts a value; map and join turn the alternatives into one line.

    Expect: Five lines: the automation and rule version, the command, the reason with its evidence ID, the two rejected alternatives, and the undo.

  3. Check that the cited evidence is unchanged since the action.

    jq -r '.evidence[]? | "\(.sha256)  \(.file)"' actions.jsonl | sha256sum -c

    Options: .evidence[]? skips records without evidence; sha256sum -c reads hash and file name pairs and checks each one.

    Expect: ev-q118.json: OK.

  4. Change the evidence by one character and check again.

    Changes a real system: Keep evidence and records in append-only storage (object lock or a write-once log), so a mismatch means tampering or a bug, never routine editing.

    sed -i 's/0.98/0.88/' ev-q118.json
    jq -r '.evidence[]? | "\(.sha256)  \(.file)"' actions.jsonl | sha256sum -c || echo "evidence no longer matches the action record"

    Expect: ev-q118.json: FAILED, a warning that one checksum did not match, and the message. The record still shows what the automation saw; the stored file no longer does.

  5. Count actions and overrides per automation: the automation people keep overriding is the one to replay first.

    jq -s -c 'group_by(.automation)[] | {automation: .[0].automation, actions: length, overridden: (map(select(.overridden)) | length)}' actions.jsonl

    Options: -s reads every record into one array; group_by groups them per automation.

    Expect: remediator-disk: 2 actions, 2 overridden; remediator-search: 2 actions, 0 overridden.

2. Python: replay_gate.py

This program replays a labelled set of twelve past alerts, including hard negatives where the right action was nothing, through the current decision rules (version 13) and a candidate (version 14), scores both on precision, recall, and wrong actions on hard negatives, lists what the candidate fixed and broke, applies the release gate, and then checks the evidence citations in two reasons, one of which cites evidence that does not exist. Save it as replay_gate.py, then run it.

# replay_gate.py
CASES = [  # past alerts with their evidence and the action people agreed was right
    ("c01", {"alert": "heap", "heap": 0.97, "mins": 12}, "restart"),
    ("c02", {"alert": "heap", "heap": 0.96, "mins": 4}, "none"),          # too short: hard negative
    ("c03", {"alert": "disk", "disk": 0.95}, "expand_volume"),
    ("c04", {"alert": "disk", "disk": 0.97}, "expand_volume"),
    ("c05", {"alert": "crashloop", "deploy_age": 8}, "rollback"),
    ("c06", {"alert": "crashloop", "deploy_age": None}, "page"),
    ("c07", {"alert": "latency", "cpu": 0.40, "dependency_down": True}, "none"),  # upstream: hard negative
    ("c08", {"alert": "heap", "heap": 0.98, "mins": 15}, "restart"),
    ("c09", {"alert": "disk", "disk": 0.92}, "expand_volume"),
    ("c10", {"alert": "cert", "cert_days": 5}, "page"),
    ("c11", {"alert": "crashloop", "deploy_age": 20}, "rollback"),
    ("c12", {"alert": "latency", "cpu": 0.95}, "scale_out"),
]

def v13(e):                                       # current version
    if e["alert"] == "crashloop":
        return "rollback" if e["deploy_age"] is not None and e["deploy_age"] <= 30 else "page"
    if e.get("heap", 0) >= 0.95 and e.get("mins", 0) >= 10:
        return "restart"
    if e.get("disk", 0) >= 0.90:
        return "expand_volume"
    if e.get("cpu", 0) >= 0.90:
        return "scale_out"
    return "none"

def v14(e):                                       # candidate: "prefer the least disruptive action"
    if e["alert"] == "crashloop":
        return "rollback" if e["deploy_age"] is not None and e["deploy_age"] <= 30 else "page"
    if e.get("heap", 0) >= 0.95 and e.get("mins", 0) >= 10:
        return "restart"
    if e.get("disk", 0) >= 0.90:
        return "restart"                          # changed: a restart is less disruptive than a resize
    if e.get("cert_days") is not None and e["cert_days"] <= 7:
        return "page"                             # added
    if e.get("cpu", 0) >= 0.90:
        return "scale_out"
    if e["alert"] == "latency":
        return "restart"                          # added
    return "none"

def score(decide):
    acted = [(c, decide(e), want) for c, e, want in CASES if decide(e) != "none"]
    right = sum(1 for _, got, want in acted if got == want)
    needed = sum(1 for _, _, want in CASES if want != "none")
    wrong_neg = [c for c, got, want in acted if want == "none"]
    return {"precision": right / len(acted), "recall": right / needed, "wrong_on_negatives": wrong_neg}

current, candidate = score(v13), score(v14)
for name, s in (("v13 (current)", current), ("v14 (candidate)", candidate)):
    print(f"{name:<16} precision {s['precision']:.2f}  recall {s['recall']:.2f}  "
          f"wrong actions on hard negatives: {s['wrong_on_negatives'] or 'none'}")
print()
for c, e, want in CASES:
    a, b = v13(e), v14(e)
    if a != b:
        verdict = "fixed" if b == want else "BROKE" if a == want else "changed"
        print(f"  {c} {e['alert']:<9} label {want:<13} v13 {a:<13} v14 {b:<13} {verdict}")
print()
reasons = []
if candidate["precision"] < 0.90:
    reasons.append("precision below 0.90")
if candidate["precision"] < current["precision"]:
    reasons.append("precision worse than current")
if set(candidate["wrong_on_negatives"]) - set(current["wrong_on_negatives"]):
    reasons.append("new wrong action on a hard negative")
print("gate:", "PASS" if not reasons else "FAIL (" + "; ".join(reasons) + ")")
print()

EVIDENCE = {"q-118": "max heap 0.97, 0.98, 0.97", "q-119": "restarts in 24 h: 0"}
for rid, reason, cites in (("act-0412", "heap at or above 95% for 10 minutes; no recent restarts", ["q-118", "q-119"]),
                           ("act-0420", "heap leak confirmed by profiler", ["q-118", "q-999"])):
    missing = [c for c in cites if c not in EVIDENCE]
    print(f"{rid}: {'supported' if not missing else 'UNSUPPORTED, cites ' + ', '.join(missing) + ': do not act'}")

Run it, and you should see this output:

$ python3 replay_gate.py
v13 (current)    precision 1.00  recall 0.90  wrong actions on hard negatives: none
v14 (candidate)  precision 0.64  recall 0.70  wrong actions on hard negatives: ['c07']

  c03 disk      label expand_volume v13 expand_volume v14 restart       BROKE
  c04 disk      label expand_volume v13 expand_volume v14 restart       BROKE
  c07 latency   label none          v13 none          v14 restart       BROKE
  c09 disk      label expand_volume v13 expand_volume v14 restart       BROKE
  c10 cert      label page          v13 none          v14 page          fixed

gate: FAIL (precision below 0.90; precision worse than current; new wrong action on a hard negative)

act-0412: supported
act-0420: UNSUPPORTED, cites q-999: do not act

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/explainable-automation-action-records-and-replay-sets && cd ~/labs/explainable-automation-action-records-and-replay-sets) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Explainable Automation: Action Records, Reasons, and Replay Sets for Evaluating AIOps Changes", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Store one piece of evidence, then write an action record that cites it by ID and SHA-256 hash, plus three more records.'
  'Answer "why were the search pods restarted?" from the record alone.'
  'Check that the cited evidence is unchanged since the action.'
  'Change the evidence by one character and check again.'
  'Count actions and overrides per automation: the automation people keep overriding is the one to replay first.'
)

step_1() {
mkdir -p ~/labs/explain && cd ~/labs/explain
printf '%s\n' '{"id":"q-118","query":"max_over_time(jvm_heap_used_ratio[10m])","result":[0.97,0.98,0.97]}' > ev-q118.json
H=$(sha256sum ev-q118.json | cut -d " " -f 1)
jq -n -c --arg h "$H" '{id: "act-0412", automation: "remediator-search", rule: "R-12", version: 3, call: "kubectl rollout restart deployment/search", reason: "heap at or above 95% on 3 of 3 pods for 10 minutes (q-118)", alternatives: [{option: "scale out", rejected: "at maximum replicas"}, {option: "roll back", rejected: "no deploy in 24 hours"}], evidence: [{id: "q-118", file: "ev-q118.json", sha256: $h}], undo: "none needed", overridden: false}' > actions.jsonl
for r in '{"id":"act-0413","automation":"remediator-search","rule":"R-12","version":3,"call":"kubectl rollout restart deployment/search","overridden":false}' '{"id":"act-0414","automation":"remediator-disk","rule":"D-4","version":2,"call":"kubectl rollout restart deployment/orders-api","overridden":true}' '{"id":"act-0415","automation":"remediator-disk","rule":"D-4","version":2,"call":"kubectl rollout restart deployment/orders-api","overridden":true}'; do echo "$r" >> actions.jsonl; done
wc -l actions.jsonl
}

step_2() {
jq -r 'select(.id == "act-0412") | "\(.id) by \(.automation), rule \(.rule) v\(.version)\n  ran: \(.call)\n  why: \(.reason)\n  not: \(.alternatives | map(.option + " (" + .rejected + ")") | join(", "))\n  undo: \(.undo)"' actions.jsonl
}

step_3() {
jq -r '.evidence[]? | "\(.sha256)  \(.file)"' actions.jsonl | sha256sum -c
}

step_4() {
sed -i 's/0.98/0.88/' ev-q118.json
jq -r '.evidence[]? | "\(.sha256)  \(.file)"' actions.jsonl | sha256sum -c || echo "evidence no longer matches the action record"
}

step_5() {
jq -s -c 'group_by(.automation)[] | {automation: .[0].automation, actions: length, overridden: (map(select(.overridden)) | length)}' actions.jsonl
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your team runs six remediation automations and an LLM triage assistant. An auditor and your incident commanders both want to know why automation acted. Design action records and a replay gate.

Clarifying questions to ask

Which identity does each automation use? What does an action record contain, and where is it stored and linked? How are evidence and versions captured? How are model reasons checked? What is in the replay set, and who labels it? What does the gate measure and block on? How do overrides feed back?

Rough sizing

Say 2,000 automated actions a month, records kept for two years, a replay set of 400 cases growing by 80 a month, and a change to some rule or prompt every week.

Shape of the answer

One service account per automation; action records as JSON in an object-locked bucket and in the incident timeline; evidence bundles with SHA-256 hashes; rule IDs, model IDs, and prompt versions in every record; structured reasons with evidence IDs checked before acting; a replay set with hard negatives labelled by the reviewing on-call; a pipeline gate on precision, recall, and new wrong actions against the current version; a weekly review of overrides that adds cases; dashboards of override rate and time-to-explain per automation.

Trade-offs to name

Records and replays add storage and a step to every change; small prompt edits feel too minor to replay, and they are exactly the changes that slip through.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
No action recordHop 1: TriggerDegradesActed as sa-automation, shared by four automations.
No action recordHop 2: EvidenceDegradesNothing kept.
No action recordHop 3: DecisionDegradesNot recorded.
No action recordHop 4: ReasonBreaksNo reason was recorded. The automation's log says "scaled deployment checkout replicas=6", and nothing else. Nobody can tell what it saw or which rule fired.
No action recordHop 5: AlternativesDegradesNot recorded.
No action recordHop 6: Action recordBreaksNo record. Engineers search the Kubernetes audit log, find the shared account, check four automations' logs and configurations, and find the one whose CPU rule saw a brief dip. 95 minutes.
Change without a replayHop 3: DecisionDegradesPrompt version 14, deployed on Monday.
Change without a replayHop 7: Replay setBreaksThe prompt change is small ("prefer the least disruptive action") and ships on Monday without a replay. The replay set has 38 disk cases labelled "expand the volume or page"; version 14 would have recommended a restart for 35 of them.
Change without a replayHop 8: ScoringBreaksNo score, so no gate.
Change without a replayHop 9: ReviewDegradesThe weekly review sees the disk override rate jump to 60% and 31 approved restarts that freed nothing. Version 13 is restored; the 35 cases are already in the set, and the replay becomes mandatory in the pipeline.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Trigger → Evidence → Decision → Reason → Alternatives → Action record → Replay set → Scoring → Review. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 335
AI on AWS: Bedrock, SageMaker, and the Bill for Thinking

Your team asks the same questions every day. How do I reset the VPN. Where is the deploy runbook. Why did the bill jump. A support assistant that answers from your own runbooks would save hours a week, and AWS has the parts to…

Go to Lesson 335 →

Or browse the full course from the Lessons index.