We are designing a graph-based incident response assistant that learns from postmortems. The system should have four main components:
- Knowledge Extraction: Extract structured information (entities, relations, events, etc.) from postmortem documents.
- Graph Construction: Build a knowledge graph (KG) from the extracted information.
- Retrieval and Ranking: Given an incident, retrieve relevant past incidents and suggest actions.
- Continuous Learning: Update the graph and models based on new postmortems and feedback.
Let's break down each component and then design the overall system.
1. Knowledge Extraction
-
Input: Postmortem documents (text, possibly with diagrams, logs, etc.)
-
Process:
- Use NLP techniques (NER, relation extraction, event extraction) to extract:
- Entities: services, components, teams, errors, alerts, etc.
- Relations: causal (X caused Y), temporal (before, after), ownership (team X owns service Y), etc.
- Events: incidents, actions taken, fixes, mitigations, etc.
- Extract metadata: timestamp, severity, incident duration, involved teams, etc.
- Possibly use pre-trained models (like BERT, spaCy) or custom models trained on postmortem data.
- For structured data (like logs, metrics) we might have additional parsers.
-
Output: A set of triples (subject, predicate, object) and event structures, along with metadata.
2. Graph Construction
-
We'll build a knowledge graph where:
- Nodes: entities (services, teams, errors, etc.) and events (incidents, actions).
- Edges: relations between nodes (causal, temporal, ownership, etc.).
- Each node and edge can have attributes (e.g., time, severity, confidence).
-
Steps:
- Normalize and canonicalize entities (e.g., "db cluster 1" and "database-1" might be the same).
- Resolve coreferences (e.g., "the service" refers to a previously mentioned service).
- Link to existing nodes in the graph (if we are updating) or create new ones.
- Consider multiple types of edges and nodes, possibly using RDF or a property graph model.
-
Graph Database: We can use a graph database (Neo4j, Amazon Neptune) or an in-memory graph (NetworkX) for prototyping.
3. Retrieval and Ranking
4. Continuous Learning
System Architecture
Let's outline the components and data flow:
-
Input Module:
- Accepts new postmortem documents (text, structured data, etc.)
- Preprocesses and sends to extraction.
-
Extraction Module:
- Runs NLP pipelines to extract structured data.
- Outputs: list of triples and event structures.
-
Graph Update Module:
- Takes extracted data and updates the knowledge graph.
- Performs entity resolution and graph merging.
-
Graph Storage:
- A graph database (or in-memory for small scale) that holds the knowledge graph.
-
Incident Processing Module:
- For a new incident, extract the same structured data (as in extraction) and then:
a. Retrieval: Use the graph to find similar past incidents.
b. Ranking: Rank the retrieved incidents and their actions.
c. Suggestion Generation: Compile a list of suggested actions with explanations (e.g., "In 3 similar incidents, restarting service X resolved the issue").
-
Feedback Loop:
- The incident responder can rate the suggestions (e.g., thumbs up/down, or a score).
- This feedback is stored and used to update the ranking model and possibly adjust graph edge weights.
-
Model Training:
- A separate module that periodically retrains the extraction models (if needed) and the ranking model.
Implementation Considerations
- Scalability: The graph can become large. We need efficient retrieval (indexing, approximate nearest neighbors for embeddings).
- Real-time: We want low-latency suggestions during an incident. So retrieval and ranking must be fast.
- Evaluation: We need to measure the quality of suggestions (e.g., precision@k, recall, user satisfaction).
Example Workflow
-
Postmortem Ingestion:
- Read a postmortem document.
- Extract:
- Entities: [Service: user-api, Team: platform, Error: timeout, Alert: high latency]
- Events: [Incident I1: user-api timeout, Action A1: restart user-api, Result: resolved]
- Relations: [I1 caused by Error: timeout, I1 fixed by A1, Team: platform owns user-api]
-
Graph Update:
- Add nodes for user-api, platform, timeout, high latency, I1, A1 (if not exists).
- Add edges: (I1)-[caused_by]->(timeout), (I1)-[fixed_by]->(A1), (user-api)-[owned_by]->(platform), etc.
-
New Incident:
- New incident: user-api timeout, high latency.
- Extract: [Service: user-api, Error: timeout, Alert: high latency]
- Retrieval: Find subgraphs where a node with label "Service: user-api" and an error "timeout" and an incident node connected by "caused_by". Also, look for actions that fixed such incidents.
- Ranking: Among the retrieved incidents (say I1, I2, I3), rank by:
- Similarity: exact match on service and error? (high for I1)
- Recency: I1 is 1 month old, I2 is 1 year old -> I1 higher.
- Success: I1 had a successful fix (resolved), I2 had a recurrence -> I1 higher.
- Suggestion: "Restart user-api (as in incident I1)".
-
Feedback:
- Responder tries the suggestion and it works -> feedback positive.
- We record that for incident similar to this one, the action "restart user-api" was helpful.
-
Continuous Learning:
- After many feedbacks, we adjust the ranking model so that for incidents with user-api timeout, restart is ranked higher.
Challenges
- Noisy extraction: NLP extraction is imperfect. We might have false positives and negatives.
- Graph evolution: The system changes (services deprecated, new services added). The graph must reflect that.
- Sparse data: Some services or error types might have few incidents.
- Causal inference: The graph might not capture true causality (just correlation). We need to be careful.
Possible Extensions
- Root cause analysis: Not just suggest actions from past incidents, but also suggest possible root causes by traversing the graph.
- What-if analysis: Simulate the effect of an action based on past similar incidents.
- Team awareness: Suggest which team to involve based on ownership in the graph.
This is a high-level design. Implementation details would depend on the specific tools, data, and requirements.
I'll design a comprehensive Graph-Based Incident Response Assistant that continuously learns from postmortems. This system combines knowledge graph construction with retrieval-augmented generation and active learning.
System Architecture
1. Knowledge Extraction Pipeline
class PostmortemExtractor:
def __init__(self):
self.ner_model = load_ner_model() # Fine-tuned on SRE/incident data
self.relation_extractor = RelationExtractor()
self.event_detector = EventDetector()
def extract(self, postmortem_text):
# Multi-layer extraction:
entities = self.ner_model.extract(
text=postmortem_text,
labels=['SERVICE', 'COMPONENT', 'TEAM', 'ERROR',
'INCIDENT', 'ACTION', 'ROOT_CAUSE', 'IMPACT']
)
relations = self.relation_extractor.extract(
entities,
patterns=['CAUSED_BY', 'FIXED_BY', 'OWNED_BY',
'DEPENDS_ON', 'MITIGATED_BY']
)
events = self.event_detector.detect(
text=postmortem_text,
event_types=['INCIDENT_START', 'DETECTION',
'RESPONSE_ACTION', 'RESOLUTION']
)
timeline = self.timeline_builder(events)
return {
'entities': entities,
'relations': relations,
'events': events,
'timeline': timeline,
'metadata': extract_metadata(postmortem_text)
}
2. Dynamic Knowledge Graph Construction
class IncidentKnowledgeGraph:
def __init__(self, graph_db='neo4j'):
self.graph = GraphDB(graph_db)
self.schema = self.define_schema()
def define_schema(self):
"""Define node/relationship types with embeddings"""
return {
'nodes': {
'Incident': {'properties': ['severity', 'duration', 'status']},
'Service': {'properties': ['owner', 'slo', 'criticality']},
'Action': {'properties': ['type', 'effectiveness', 'time_to_execute']},
'RootCause': {'properties': ['category', 'complexity']}
},
'relationships': {
'INVOLVED_SERVICE': {'weight': 'impact_score'},
'EXECUTED_ACTION': {'temporal': True},
'CAUSED': {'confidence': 0.8},
'RESOLVED_BY': {'effectiveness': 1.0}
}
}
def upsert_postmortem(self, extracted_data):
"""
Merge new postmortem into graph with conflict resolution
"""
# Entity resolution (canonicalization)
resolved_entities = self.entity_resolver.resolve(
extracted_data['entities']
)
# Create temporal graph with event sequence
incident_node = self.create_incident_node(
extracted_data['metadata']
)
for event in extracted_data['timeline']:
self.link_temporal_event(
incident_node,
event,
extracted_data['relations']
)
# Update effectiveness metrics from resolution outcome
if 'outcome' in extracted_data['metadata']:
self.update_edge_weights(
incident_node,
extracted_data['metadata']['outcome']
)
3. Graph-Based Retrieval System
class GraphRetriever:
def __init__(self, knowledge_graph):
self.kg = knowledge_graph
self.embedder = GraphEmbedder(model='RGCN')
self.index = AnnoyIndex() # For fast similarity search
def retrieve(self, query_incident, top_k=10):
"""
Multi-strategy retrieval with ranking fusion:
1. Graph pattern matching (exact structural similarity)
2. Embedding similarity (semantic + structural)
3. Temporal proximity (recent similar incidents)
4. Team/context similarity
"""
# Strategy 1: Graph pattern match
pattern = self.extract_pattern(query_incident)
pattern_matches = self.graph_pattern_match(pattern)
# Strategy 2: Embedding similarity
query_embedding = self.embedder.embed_incident(query_incident)
embedding_matches = self.index.search(
query_embedding,
k=top_k*2
)
# Strategy 3: Metadata filtering
metadata_filter = {
'service': query_incident['affected_services'],
'severity': query_incident['severity'],
'time_window': '30d'
}
filtered_matches = self.metadata_filter(
pattern_matches + embedding_matches,
metadata_filter
)
# Rank fusion using Reciprocal Rank Fusion (RRF)
ranked_results = self.rrf_fusion([
pattern_matches,
embedding_matches,
filtered_matches
])
# Re-rank by effectiveness and recency
final_ranking = self.rerank_by_effectiveness(
ranked_results[:top_k*3]
)
return final_ranking[:top_k]
4. Suggestion Generation & Ranking
class SuggestionGenerator:
def __init__(self, retriever, llm):
self.retriever = retriever
self.llm = llm # Fine-tuned on incident response
self.ranker = LearningToRankModel()
def generate_suggestions(self, current_incident):
"""
Generate ranked, contextual suggestions:
"""
# Retrieve similar incidents
similar_incidents = self.retriever.retrieve(current_incident)
# Extract action sequences with outcomes
action_sequences = self.extract_action_sequences(
similar_incidents
)
# Cluster and aggregate suggestions
clustered_actions = self.cluster_similar_actions(
action_sequences
)
# Score each suggestion cluster
scored_suggestions = []
for cluster in clustered_actions:
score = self.ranker.score({
'action_cluster': cluster,
'incident_context': current_incident,
'historical_effectiveness': cluster['effectiveness_stats'],
'similarity_to_current': cluster['similarity'],
'recency_weight': self.calculate_recency_weight(
cluster['incidents']
)
})
scored_suggestions.append({
'suggestion': cluster['representative_action'],
'score': score,
'supporting_incidents': cluster['incidents'][:3],
'confidence': cluster['confidence'],
'estimated_impact': cluster['impact_estimate']
})
# Generate natural language explanations
explanations = self.llm.generate_explanations(
current_incident,
scored_suggestions
)
return self.format_response(scored_suggestions, explanations)
5. Continuous Learning Loop
class ContinuousLearningSystem:
def __init__(self, kg, retriever, ranker):
self.kg = kg
self.retriever = retriever
self.ranker = ranker
self.feedback_buffer = FeedbackBuffer()
async def process_feedback(self, incident_id, feedback):
"""
Multi-source feedback processing:
- Explicit: Thumbs up/down, action effectiveness ratings
- Implicit: Time-to-resolution, recurrence indicators
- Expert: SME corrections to suggestions
"""
# Store feedback
self.feedback_buffer.add(incident_id, feedback)
# Update graph edge weights based on effectiveness
if feedback['action_taken']:
self.kg.update_edge_effectiveness(
incident_id,
feedback['action_taken'],
feedback['success_metric']
)
# Update retrieval index if needed
if feedback['suggestion_quality'] < threshold:
self.retrain_embedding_model()
# Periodic batch updates
if self.feedback_buffer.size() > batch_size:
self.retrain_ranker()
self.retrain_extractor()
6. Evaluation & Monitoring
class PerformanceMonitor:
def track_metrics(self):
return {
'retrieval_precision': self.calculate_precision(),
'suggestion_acceptance_rate': self.acceptance_rate(),
'mttr_improvement': self.compare_mttr(),
'knowledge_graph_growth': self.kg.growth_rate(),
'feedback_coverage': self.feedback_coverage()
}
def A_B_test(self, old_vs_new):
"""Run experiments on suggestion strategies"""
# Randomly assign incidents to different ranking strategies
# Compare resolution time, user satisfaction
Core Algorithms
Graph Embedding for Retrieval
class GraphEmbedder:
def __init__(self):
self.model = RGCN(
in_features=128,
hidden_channels=256,
out_features=64,
num_relations=10
)
def embed_incident_subgraph(self, incident_id):
# Extract 2-hop subgraph around incident
subgraph = self.kg.extract_subgraph(
incident_id,
hops=2
)
# Encode with relational GCN
embedding = self.model(subgraph)
# Augment with metadata encoding
metadata_embed = self.metadata_encoder(
subgraph.nodes[incident_id]['properties']
)
return torch.cat([embedding, metadata_embed])
Temporal Pattern Mining
class TemporalPattern Miner:
def mine_temporal_patterns(self, time_window='90d'):
"""
Find common temporal sequences:
e.g., "Service degradation → Alert fires → Cache clear → Recovery"
"""
sequences = self.kg.get_temporal_sequences(
incident_type='outage',
min_support=0.1
)
# Mine frequent episodes using SPADE algorithm
patterns = self.spade_algorithm(sequences)
# Calculate lift and confidence
scored_patterns = self.calculate_pattern_significance(
patterns,
baseline=self.calculate_baseline_patterns()
)
return scored_patterns[:100] # Top 100 patterns
Deployment Considerations
Scalability
- Graph Database: Neo4j/Tigergraph for production, NetworkX for prototyping
- Vector Index: FAISS/Annoy for embedding search
- Caching: Redis for frequent query patterns
- Sharding: By service/team/region
Real-time Requirements
┌─────────────────┐ ┌──────────────┐ ┌──────────────┐
│ Incident JSON │───▶│ Extraction │───▶│ Graph │
│ (current) │ │ (<2s) │ │ Query │
└─────────────────┘ └──────────────┘ └──────┬───────┘
│
┌─────────────────┐ ┌──────────────┐ ┌──────▼───────┐
│ Feedback JSON │◀───│ Ranking │◀───│ Retrieval │
│ (post-incident)│ │ (<1s) │ │ (<3s) │
└─────────────────┘ └──────────────┘ └──────────────┘
Data Privacy & Security
- Sanitization: Automatic PII/secret removal from postmortems
- Access Control: Role-based graph access (SRE vs. developer)
- Audit Trail: Complete log of suggestions given and acted upon
Training Data Requirements
- Labeled Postmortems: 1000+ with structured annotations
- Feedback Data: explicit (ratings) and implicit (resolution time)
- Negative Examples: Incidents where suggestions were wrong
- Ground Truth: Known root causes and effective actions
Implementation Roadmap
Phase 1 (MVP - 4 weeks)
- Basic extraction pipeline (spaCy + rules)
- Simple graph in NetworkX
- Keyword-based retrieval
- Manual feedback collection
Phase 2 (3 months)
- Fine-tuned extraction models
- Neo4j deployment with embeddings
- Graph pattern matching
- Learning-to-rank model
Phase 3 (6 months)
- Full continuous learning loop
- Multi-team deployment
- Automated A/B testing
- Root cause prediction
Phase 4 (12 months)
- Cross-organization graph federation
- Causal inference layer
- Proactive anomaly detection
- Auto-generated runbooks
Key Innovations
- Temporal-Aware Graph: Events have precise timestamps with duration
- Effectiveness-Weighted Edges: Edges update based on outcomes
- Confidence Propagation: Uncertainty flows through the graph
- Counterfactual Learning: "What-if" analysis on past actions
- Explainable Retrieval: Every suggestion traces back to supporting evidence
This system creates a living knowledge base that gets smarter with every incident, transforming postmortems from static documents into an actively consulted decision-support system.