RAG over Post-Mortems: Learn from Every Incident

Every incident teaches your team something, then the lesson sits in a document nobody opens during the next page. RAG over post-mortems fixes that. You will index post-mortems, Slack timelines and tickets in one vector store, ask “have we seen this before?” mid-incident, and cluster contributing factors to decide which reliability work to fund.
How RAG over post-mortems works
Retrieval-augmented generation (RAG) searches your own documents first, then lets a large language model (LLM) answer only from what it found. This post extends RAG 101 over runbooks to incidents: three sources, one index and two consumers.
The incident ID on every record is the join key: a match in a Slack timeline pulls in the full post-mortem and its tickets. Chroma computes the embeddings (vectors that place similar text close together) locally, so only matched excerpts ever reach the LLM API.
You need Python 3.10 or newer, pip install chromadb anthropic scikit-learn and an Anthropic API key. Post-mortems are Markdown files named like 2026-11-24_INC-2291_checkout.md. Timelines come from the AI post-mortem pipeline, and tickets are GitHub issues that mention incident IDs.
Step 1: Index post-mortems, Slack timelines and tickets
Indexed naively, each source fails differently. One record per post-mortem blurs the timeline with the action items, raw Slack drowns in chatter, and a ticket means little without its incident. So cut each source along its natural seams and tag every record with its incident, as the diagram shows.
Save this as ingest_incidents.py:
import json, pathlib, re, chromadb
col = chromadb.PersistentClient(path=".chroma").get_or_create_collection(
name="incidents", configuration={"hnsw": {"space": "cosine"}})
def add(inc, rid, text, **meta):
col.upsert(ids=[f"{inc}:{rid}"], documents=[text], metadatas=[{"incident": inc, **meta}])
for pm in pathlib.Path("postmortems").glob("*_INC-*.md"): # 2026-11-24_INC-2291_checkout.md
_, inc, svc = pm.stem.split("_")
text = pm.read_text()
m = re.search(r"impact_minutes: (\d+)", text)
meta = {"minutes": int(m[1]) if m else 0}
for n, sec in enumerate(re.split(r"\n(?=## )", text)): # one record per section
add(inc, f"pm:{n}", f"{inc} {svc}: {sec}", kind="postmortem", **meta)
if sec.startswith("## Contributing factors"):
for k, factor in enumerate(re.findall(r"^- (.+)", sec, re.M)):
add(inc, f"factor:{k}", factor, kind="factor", **meta)
for tl in pathlib.Path("timelines").glob("INC-*.jsonl"):
lines = tl.read_text().splitlines()
for n in range(0, len(lines), 20): # 20-event windows
add(tl.stem, f"tl:{n}", "\n".join(lines[n:n + 20]), kind="timeline")
for t in json.loads(pathlib.Path("tickets.json").read_text()):
body = f"[{t['state']}] {t['title']}\n{t['body']}"
for inc in set(re.findall(r"INC-\d+", body)):
add(inc, f"ticket:{t['number']}", body, kind="ticket")
print(col.count(), "records")
The post-mortem loop splits on level-two headings, so Summary, Impact and Action items each become a record prefixed with the incident and service. Contributing factors are also stored once per bullet, for step 3. Impact minutes come from an impact_minutes: 42 line, so add one to your template. Windows of 20 timeline events keep an alert, the first reaction and the rollback together.
Each ticket is stored once per incident it cites. Export the tickets with the GitHub CLI, then run the script:
gh issue list --label incident --state all --limit 1000 \
--json number,title,body,state > tickets.json
python3 ingest_incidents.py
# 2487 records
Without --state all you get only open issues, and closed follow-ups are the history you want. The default limit is 30, so raise it. If the count looks low, check your file names: anything the glob does not match is skipped silently.
Step 2: Ask “have we seen this before?”
The most valuable minute of an incident is when someone says “this looks like the June checkout outage”. That memory usually lives in one senior engineer. This query hands it to whoever holds the pager, and refuses when nothing is close.
Both “no” branches feed back into the index or the evals, so every miss improves the next answer. Save this as seen_before.py:
import sys, anthropic, chromadb
MAX_DISTANCE = 0.55 # tune on known repeats
symptom = " ".join(sys.argv[1:])
col = chromadb.PersistentClient(path=".chroma").get_collection(name="incidents")
hits = col.query(query_texts=[symptom], n_results=20)
best = {} # incident -> nearest record
for rid, meta, dist in zip(hits["ids"][0], hits["metadatas"][0], hits["distances"][0]):
if dist <= MAX_DISTANCE:
best.setdefault(meta["incident"], (rid, dist))
if not best:
sys.exit("No similar incident on record.")
context = ""
for inc, (rid, dist) in list(best.items())[:3]: # read the whole incident
print(f"{inc} {dist:.2f} {rid}")
docs = col.get(where={"$and": [{"incident": inc}, {"kind": {"$in": ["postmortem", "ticket"]}}]})
context += f"\n## {inc}\n" + "\n".join(docs["documents"])
reply = anthropic.Anthropic().messages.create(model="claude-sonnet-5-5", max_tokens=400,
system="Using only these past incidents: what matches, what fixed it, open follow-ups. Cite IDs.",
messages=[{"role": "user", "content": f"{context}\n\nLive symptom: {symptom}"}])
print(reply.content[0].text)
Results arrive sorted by distance, so setdefault keeps each incident's best record and one long incident cannot fill every slot. The script then reads every post-mortem section and ticket of the top three. This is parent-document retrieval: match on small records, answer from the whole incident. With no match under the threshold, it exits before spending a token. Illustrative output:
$ python3 seen_before.py "checkout 5xx, DB pool timeouts after deploy"
INC-2291 0.29 INC-2291:tl:0
INC-1987 0.41 INC-1987:factor:0
INC-2291: 5xx began after v142 shipped; rollback fixed it. Follow-up
#812 (canary) is OPEN. INC-1987: same pool timeouts, fixed by raising
max connections.
Check the matched IDs and open the cited post-mortem before acting. Most bad answers come from a loose threshold, so tune it on a dozen known repeats. Alert names and error codes embed poorly, so add keyword search as in hybrid search done right.
Step 3: Cluster recurring themes to decide what to fund
Lookups help the on-call engineer; clusters help whoever sets the roadmap. A factor that recurs in fourteen post-mortems is a funding case, not bad luck. Clustering groups factors by meaning, so “pool exhausted after scale-up” and “max connections too low” share a theme.
import collections, chromadb, numpy as np
from sklearn.cluster import HDBSCAN
from sklearn.preprocessing import normalize
col = chromadb.PersistentClient(path=".chroma").get_collection(name="incidents")
got = col.get(where={"kind": "factor"}, include=["embeddings", "documents", "metadatas"])
labels = HDBSCAN(min_cluster_size=4).fit_predict(normalize(np.array(got["embeddings"])))
themes, sample = collections.defaultdict(dict), dict(zip(labels, got["documents"]))
for label, meta in zip(labels, got["metadatas"]):
themes[label][meta["incident"]] = meta["minutes"] # an incident counts once
for label, incs in sorted(themes.items(), key=lambda kv: -sum(kv[1].values())):
print(f"theme {label}: {len(incs)} incidents, {sum(incs.values())} min, e.g. {sample[label][:50]}")
Chroma's get omits embeddings unless you ask for them. Normalising them to unit length lets Euclidean distance rank like cosine. HDBSCAN, in scikit-learn since 1.3, chooses the number of themes itself and labels one-off factors -1. Each line prints a theme's incident count, impact minutes and an example factor.
Clustering gives numbers, not names. Read a few factors per theme in the reliability review and name it together. Once named, the ranking looks like this:
Take the top two or three themes into planning, each with an owner and a goal, then re-run monthly. A funded theme should shrink. If themes reshuffle between runs, raise min_cluster_size or wait for more post-mortems.
Run it as a service: freshness, evals and cost
- Freshness. Rebuild from scratch nightly or on every merge to the post-mortem repository.
- Evals. Query each known repeat with its first alert and check the earlier incident ranks in the top three. Re-run after any chunking, model, prompt or threshold change; see RAG in production.
- Cost and latency. Retrieval is local, so the LLM call is the only per-query cost. Log tokens, model ID and prompt version per answer, and set a latency SLO.
- Access. Post-mortems name customers and hosts, so the index needs the same access controls.
I built a Slack bot that investigates incidents using documentation search, metric plugins and log APIs. A “seen before” lookup fits naturally beside those tools.
Common pitfalls
- No shared incident ID. If tickets and chats never mention it, nothing joins.
- Whole documents as records. Every incident looks vaguely similar.
- Stale records. Upserts never remove deleted sections, so rebuild.
- Blame in the source. The model repeats it, so keep post-mortems blameless.
- Clusters as verdicts. Themes inform the funding debate; people decide.
Key takeaways
- Tag every section, timeline window and ticket with its incident ID.
- Match on small records, then answer from the whole incident.
- Refuse when nothing is close, and tune the threshold on known repeats.
- Rank clustered contributing factors by impact to decide what to fund.
- Rebuild nightly and evaluate retrieval like any production model.
Related articles

RAG in Production: Evals, Observability, Cost, Freshness
Take a runbook RAG bot from demo to production: gate changes on recall@k and faithfulness evals, trace retrieval and generation with OpenTelemetry, set latency and groundedness SLOs, and cut cost with caching and incremental re-indexing.

AI Agents for SRE: Agentic Ops for Routine Work, Safely
Which SRE chores can an AI agent take on today? A task matrix, a read-only MCP server in Python, one scoped write behind human approval, an audit log, and a trust ladder for promoting agents safely.

AI Post-Mortems: Faster Drafts That Stay Blameless
Let an LLM draft the post-mortem without letting it assign blame: build the timeline in code from Slack, Prometheus alerts and GitHub deploys, draft with a blameless prompt, lint the wording in CI, and keep causes and action items human.