All lessons · Guided routes

Capstone 9 of 10

Capstone 9: Automated incident response with a human in charge

Hundreds of alerts arrive during an incident and the real cause is buried. You build an event pipeline that groups them, proposes a cause with its evidence, asks a human before acting, rolls back a real process, records every step in a tamper-evident log, and can be stopped by a kill switch.

What you build

  1. Ingest and normalise

    Events from several sources become one schema.

    Lessons: Event Normalisation and Alert Enrichment: One Schema, an Owner, and Context Before Correlation

  2. Enrich and deduplicate

    Add owner and recent changes; collapse duplicates.

    Lessons: AIOps Event Correlation and Noise Reduction: From 2,400 Alerts to One Incident

  3. Correlate and propose a cause

    Group by time and topology, start from critical alerts, and propose a hypothesis with evidence and confidence.

    Lessons: Correlation Versus Causation in Incident Analysis: From "Changed at the Same Time" to Proven Cause, AIOps

  4. Approval and safe action

    Nothing runs without a human approval; the action is a rollback of a real local process.

    Lessons: Safe Auto-Remediation and LLM-Assisted Incident Response, Token Use, Cost, and Latency for AI Operations Assistants, and Where Automation Must Not Act

  5. Explain and audit

    Every decision is recorded in a hash-chained audit log that detects tampering.

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

  6. Kill switch and rollback

    A kill switch stops all automated actions; the remediation itself can be undone.

    Lessons: Safe Auto-Remediation and LLM-Assisted Incident Response

Before you start

ToolVersion
python33.10 or later

Ports: 18089 on 127.0.0.1. Resources: Under 100 MB; standard library only, no AI service is called.

What it creates (and the reset removes): one python3 orders.py process; ~/labs/capstones/aiops (events, audit log). Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.

Get the files

One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.

mkdir -p ~/labs && cd ~/labs
curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz
tar -xzf capstones-lab.tar.gz && cd capstones-lab
ls

Run it

All in one, with the reset afterwards even if a step fails:

bash run.sh 09-aiops

Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):

python3 09-aiops/aiops.py setup
python3 09-aiops/aiops.py verify
python3 09-aiops/aiops.py reset

Expected output

This is a real run of run.sh 09-aiops, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.

== 1. orders 1.0.0 runs and serves traffic
   {200: 60}
== 2. orders 2.0.0 is deployed; it fails 40% of requests
   {200: 94, 500: 56}
== 3. The monitoring system fires alerts, several of them repeats
   8 alerts written to alerts.jsonl
== Ingest, normalise, enrich, deduplicate
  PASS  65 events from 3 sources share one schema with an owner
  PASS  8 alerts deduplicate to 3
== Correlate and form a hypothesis
  PASS  one incident across ['orders', 'orders-db', 'web'], rooted at orders (web depends on it)
  PASS  top hypothesis: deploy orders 2.0.0 (56 errors after, 0 before)
== Remediation is gated: kill switch, then approval
  PASS  with the kill switch on, the rollback is refused
  PASS  without a person's approval, the rollback is refused
  PASS  with approval, the rollback runs
  PASS  after the rollback, version 1.0.0 serves {200: 100}
== Explainability and audit
  PASS  the action record has a reason, rejected alternatives, approver, and undo
  PASS  the evidence hash in the record matches the evidence used
  PASS  the audit trail holds 3 entries (2 refusals, 1 action) and its hash chain verifies
  PASS  an edited audit entry breaks the chain and is detected
== Undo the remediation (the record says how)
  PASS  undo restores version 2.0.0, as the record describes

RESULT: all checks passed

The files

09-aiops/aiops.py
#!/usr/bin/env python3
"""Capstone 9, AIOps: event ingestion -> normalisation -> enrichment -> deduplication ->
correlation -> causal hypothesis -> human approval -> safe remediation -> explainability ->
audit trail -> kill switch -> rollback.

Runs against a real local service: setup starts orders.py v1, then "deploys" v2, which fails 40%
of requests. Standard library only; works in ~/labs/capstones/aiops, port 18089.
  python3 aiops.py setup | verify | reset
"""
import hashlib
import json
import os
import shutil
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "..", "app", "orders.py")
WORK = os.path.expanduser("~/labs/capstones/aiops")
PORT = 18089
URL = f"http://127.0.0.1:{PORT}"
CATALOG = {"orders": {"owner": "team-orders", "tier": 1, "runbook": "orders-5xx", "depends_on": ["orders-db"]},
           "orders-db": {"owner": "team-data", "tier": 1, "runbook": "pg", "depends_on": []},
           "web": {"owner": "team-web", "tier": 2, "runbook": "web", "depends_on": ["orders"]}}
FAILS = []


def p(*x): return os.path.join(WORK, *x)
def ok(m): print("  PASS ", m)
def bad(m): FAILS.append(m); print("  FAIL ", m)
def now(): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def start(version, fail_rate):
    env = dict(os.environ, PORT=str(PORT), VERSION=version, FAIL_RATE=str(fail_rate))
    log = open(p(f"orders-{version}.log"), "a")
    proc = subprocess.Popen([sys.executable, APP], env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
    open(p("orders.pid"), "w").write(str(proc.pid))
    open(p("orders.version"), "w").write(version)
    for _ in range(50):
        try:
            urllib.request.urlopen(URL + "/readyz", timeout=1); return
        except OSError:
            time.sleep(0.1)


def stop():
    try:
        os.kill(int(open(p("orders.pid")).read()), signal.SIGTERM); time.sleep(0.5)
    except (OSError, ValueError):
        pass


def traffic(n):
    codes = {}
    for _ in range(n):
        try:
            c = urllib.request.urlopen(URL + "/orders", timeout=2).status
        except urllib.error.HTTPError as e:
            c = e.code; e.close()
        except OSError:
            c = 0
        codes[c] = codes.get(c, 0) + 1
    return codes


# ---------- the pipeline
def ingest():
    """Events from three sources in their own formats: the service's JSON logs, a deploy log, and
    alerts from a monitoring system (some repeated)."""
    events = []
    for f in sorted(x for x in os.listdir(WORK) if x.startswith("orders-") and x.endswith(".log")):
        for line in open(p(f)):
            try:
                e = json.loads(line)
            except json.JSONDecodeError:
                continue
            if e.get("msg") == "request" and e.get("status", 0) >= 500:
                events.append({"src": "app-log", "ts": e["ts"], "svc": "orders", "res": "orders", "sev": "error", "name": "http_5xx", "version": e.get("version")})
    for line in open(p("deploys.log")):
        ts, svc, ver = line.split()
        events.append({"src": "deploy", "ts": ts, "svc": svc, "res": svc, "sev": "info", "name": "deploy", "version": ver})
    for line in open(p("alerts.jsonl")):
        a = json.loads(line)
        events.append({"src": "monitoring", "ts": a["startsAt"], "svc": a["labels"].get("service"), "res": a["labels"].get("service"),
                       "sev": {"critical": "critical", "warning": "warning"}.get(a["labels"]["severity"], "high"), "name": a["labels"]["alertname"]})
    return events


def enrich(e):
    c = CATALOG.get(e["svc"], {})
    return dict(e, owner=c.get("owner", "unowned"), tier=c.get("tier"), runbook=c.get("runbook"))


def fingerprint(e): return hashlib.sha256(f"{e['svc']}|{e['res']}|{e['name']}".encode()).hexdigest()[:12]


def correlate(alerts):
    """Group alerts whose services are connected in the dependency graph into one incident, rooted at
    the service everything else depends on."""
    svcs = {a["svc"] for a in alerts}
    # the root: the service with its own critical alerts, then the one most others depend on
    crit = lambda s: sum(1 for a in alerts if a["svc"] == s and a["sev"] == "critical")
    dependents = lambda s: sum(s in CATALOG.get(o, {}).get("depends_on", []) for o in svcs)
    root = sorted(svcs, key=lambda s: (-crit(s), -dependents(s), s))[0]
    return {"root": root, "services": sorted(svcs), "alerts": len(alerts)}


def hypothesis(events):
    """Rank candidate causes by how well they line up in time with the error rise."""
    errors = sorted(e["ts"] for e in events if e["name"] == "http_5xx")
    deploys = [e for e in events if e["name"] == "deploy"]
    first_err = errors[0] if errors else None
    ranked = []
    for d in deploys:
        before = sum(1 for t in errors if t < d["ts"]); after = sum(1 for t in errors if t >= d["ts"])
        ranked.append({"cause": f"deploy {d['svc']} {d['version']}", "errors_before": before, "errors_after": after, "score": after - before * 5})
    ranked.sort(key=lambda x: -x["score"])
    return {"first_error": first_err, "ranked": ranked}


# ---------- audit trail: an append-only, hash-chained log
def audit(entry):
    prev = "0" * 64
    if os.path.exists(p("audit.jsonl")):
        lines = open(p("audit.jsonl")).read().splitlines()
        if lines:
            prev = json.loads(lines[-1])["hash"]
    body = dict(entry, ts=now(), prev=prev)
    body["hash"] = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
    with open(p("audit.jsonl"), "a") as f:
        f.write(json.dumps(body, sort_keys=True) + "\n")


def audit_ok():
    prev = "0" * 64
    for line in open(p("audit.jsonl")):
        e = json.loads(line); h = e.pop("hash")
        if e["prev"] != prev or hashlib.sha256(json.dumps(e, sort_keys=True).encode()).hexdigest() != h:
            return False
        prev = h
    return True


def remediate(action, evidence, approved_by):
    """Roll back to the previous version, only with an approval, never with the kill switch on, and
    always with an action record and an undo."""
    if os.path.exists(p("KILL_SWITCH")):
        audit({"event": "refused", "action": action, "reason": "kill switch is on"}); return "refused: kill switch"
    if not approved_by:
        audit({"event": "refused", "action": action, "reason": "no human approval"}); return "refused: needs approval"
    prev_version = "1.0.0"
    record = {"id": "act-0001", "action": action, "approved_by": approved_by, "identity": "sa-remediator-orders",
              "reason": f"5xx rose after {evidence['hypothesis']['ranked'][0]['cause']}; no 5xx before it",
              "evidence_sha256": hashlib.sha256(json.dumps(evidence, sort_keys=True).encode()).hexdigest(),
              "alternatives": [{"option": "restart v2", "rejected": "the errors follow the version, not the process"},
                               {"option": "scale out", "rejected": "errors are a share of requests, not saturation"}],
              "undo": "start version 2.0.0 again", "from_version": open(p("orders.version")).read(), "to_version": prev_version}
    stop(); start(prev_version, 0)
    json.dump(record, open(p("action-act-0001.json"), "w"), indent=1)
    audit({"event": "action", "id": record["id"], "action": action, "approved_by": approved_by, "evidence_sha256": record["evidence_sha256"]})
    return "done"


# ---------- commands
def setup():
    os.makedirs(WORK, exist_ok=True)
    for f in os.listdir(WORK):
        os.remove(p(f)) if os.path.isfile(p(f)) else None
    print("== 1. orders 1.0.0 runs and serves traffic")
    start("1.0.0", 0); print("  ", traffic(60))
    print("== 2. orders 2.0.0 is deployed; it fails 40% of requests")
    time.sleep(1.1)
    open(p("deploys.log"), "w").write(f"{now()} orders 2.0.0\n")
    stop(); start("2.0.0", 0.4); print("  ", traffic(150))
    print("== 3. The monitoring system fires alerts, several of them repeats")
    t = now()
    alerts = [{"labels": {"alertname": "HighErrorRate", "service": "orders", "severity": "critical"}, "startsAt": t}] * 4 + \
             [{"labels": {"alertname": "UpstreamErrors", "service": "web", "severity": "warning"}, "startsAt": t}] * 3 + \
             [{"labels": {"alertname": "SlowQueries", "service": "orders-db", "severity": "warning"}, "startsAt": t}]
    with open(p("alerts.jsonl"), "w") as f:
        for a in alerts:
            f.write(json.dumps(a) + "\n")
    print(f"   {len(alerts)} alerts written to alerts.jsonl")


def verify():
    print("== Ingest, normalise, enrich, deduplicate")
    raw = ingest()
    norm = [enrich(e) for e in raw]
    (ok if all({"src", "ts", "svc", "sev", "name", "owner"} <= set(e) for e in norm) else bad)(f"{len(norm)} events from 3 sources share one schema with an owner")
    alerts = [e for e in norm if e["src"] == "monitoring"]
    uniq = {fingerprint(e): e for e in alerts}
    (ok if len(alerts) == 8 and len(uniq) == 3 else bad)(f"{len(alerts)} alerts deduplicate to {len(uniq)}")
    print("== Correlate and form a hypothesis")
    inc = correlate(list(uniq.values()))
    (ok if inc["root"] == "orders" else bad)(f"one incident across {inc['services']}, rooted at {inc['root']} (web depends on it)")
    hyp = hypothesis(norm)
    top = hyp["ranked"][0] if hyp["ranked"] else {}
    (ok if top.get("cause") == "deploy orders 2.0.0" and top["errors_before"] == 0 and top["errors_after"] > 30 else bad)(f"top hypothesis: {top.get('cause')} ({top.get('errors_after')} errors after, {top.get('errors_before')} before)")
    evidence = {"incident": inc, "hypothesis": hyp, "alerts": len(alerts)}
    print("== Remediation is gated: kill switch, then approval")
    open(p("KILL_SWITCH"), "w").write("on")
    (ok if remediate("rollback orders", evidence, "on-call") == "refused: kill switch" else bad)("with the kill switch on, the rollback is refused")
    os.remove(p("KILL_SWITCH"))
    (ok if remediate("rollback orders", evidence, None) == "refused: needs approval" else bad)("without a person's approval, the rollback is refused")
    (ok if remediate("rollback orders", evidence, "on-call: asha") == "done" else bad)("with approval, the rollback runs")
    codes = traffic(100)
    (ok if codes.get(200, 0) == 100 and open(p("orders.version")).read() == "1.0.0" else bad)(f"after the rollback, version 1.0.0 serves {codes}")
    print("== Explainability and audit")
    rec = json.load(open(p("action-act-0001.json")))
    (ok if rec["reason"] and rec["alternatives"] and rec["undo"] and rec["approved_by"] else bad)("the action record has a reason, rejected alternatives, approver, and undo")
    (ok if rec["evidence_sha256"] == hashlib.sha256(json.dumps(evidence, sort_keys=True).encode()).hexdigest() else bad)("the evidence hash in the record matches the evidence used")
    (ok if audit_ok() and sum(1 for _ in open(p("audit.jsonl"))) == 3 else bad)("the audit trail holds 3 entries (2 refusals, 1 action) and its hash chain verifies")
    lines = open(p("audit.jsonl")).read().splitlines(); t = json.loads(lines[0]); t["reason"] = "edited later"
    open(p("audit-tampered.jsonl"), "w").write("\n".join([json.dumps(t, sort_keys=True)] + lines[1:]) + "\n")
    os.replace(p("audit.jsonl"), p("audit-good.jsonl")); os.replace(p("audit-tampered.jsonl"), p("audit.jsonl"))
    (ok if not audit_ok() else bad)("an edited audit entry breaks the chain and is detected")
    os.replace(p("audit-good.jsonl"), p("audit.jsonl"))
    print("== Undo the remediation (the record says how)")
    stop(); start(rec["from_version"], 0.4)
    (ok if open(p("orders.version")).read() == "2.0.0" else bad)("undo restores version 2.0.0, as the record describes")
    print("\nRESULT:", "all checks passed" if not FAILS else f"{len(FAILS)} check(s) failed")
    sys.exit(1 if FAILS else 0)


def reset():
    if os.path.exists(p("orders.pid")):
        stop()
    shutil.rmtree(WORK, ignore_errors=True)
    print(f"capstone 9 reset: service stopped, {WORK} removed")


if __name__ == "__main__":
    {"setup": setup, "verify": verify, "reset": reset}.get(sys.argv[1] if len(sys.argv) > 1 else "", lambda: sys.exit(__doc__))()

If it fails

SymptomCauseFix
"audit chain broken"The audit file was edited, which is what the check is for.Reset and run again to start a new chain.
The remediation is refusedThe kill switch file exists, or approval was not given.That is the guard working; see the stage on approval.

Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.

Clean up

python3 09-aiops/aiops.py reset

It removes: one python3 orders.py process; ~/labs/capstones/aiops (events, audit log). Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.

In the cloud

Not run by this course. The local capstone above is the tested part. These are the managed services that do the same jobs on each provider; they cost money while they exist, and their names and prices change, so check the provider's current documentation before you build them. Use a separate learning account with a budget alert, as Start here explains.
ProviderEquivalent
AWSEventBridge for events, DevOps Guru for anomaly grouping, and Systems Manager Automation with change approvals.
AzureAzure Monitor alert processing rules, smart groups, and Automation runbooks with approvals.
Google CloudCloud Monitoring incidents, Eventarc, and Workflows with a manual approval step.

How it is assessed

verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.

CriterionMeetsExceeds
NoiseDuplicate and related alerts become one incident.You can show the reduction ratio and what was kept.
ReasoningThe proposed cause lists its evidence.It also says what would prove it wrong.
ControlNo action runs without approval, and the kill switch works.Actions have a blast-radius limit and a time limit.
AccountabilityEvery step is in the audit log.Tampering is detected, and the log can replay the decision.

Take it further

Then test what you know with the assessments.

Next capstone: Review a cloud landing zone like an architecture board. All capstones · Guided routes