It’s 3:14 AM. Your phone shatters the silence with a high-severity PagerDuty alert: Deployment/checkout-service is in a CrashLoopBackOff.
You stumble to your laptop, open a terminal, and begin the manual, mechanical triage ritual:
kubectl logs -n prod deployment/checkout-service --previous
kubectl describe pod -n prod checkout-service-7f998d-x82lq
kubectl top pod -n prod checkout-service-7f998d-x82lq
Minutes tick by as you parse obfuscated stack traces, track down a silently failing upstream dependency, and realize the container died due to a combination of kernel-level file descriptor exhaustion and misconfigured cgroup memory limits. You bump the limit, patch the manifest, apply it, and head back to bed—exhausted, frustrated, and knowing this exact sequence will repeat next week under a slightly different name.
Standard Kubernetes primitives (LivenessProbes, ReadinessProbes, and HorizontalPodAutoscalers) are blunt, reactive instruments. They know that something is wrong, but they lack the reasoning capacity to understand why or how to fix it intelligently.
On the other side of the spectrum, sending your cluster’s live system logs, environment variables, and telemetry to public LLM APIs (like OpenAI or Anthropic) introduces unacceptable latency, skyrocketing API costs, and massive data privacy compliance violations (GDPR, SOC2, HIPAA).
The solution? Local LLM Incident Response Agents running directly inside your Kubernetes control plane.
In this technical deep dive, we will architect a zero-cloud-dependency, self-healing Kubernetes control loop that pairs eBPF (Extended Berkeley Packet Filter) kernel telemetry with a lightweight Local LLM Agent (Qwen2.5-Coder / Llama-3.1-8B) bounded by deterministic guardrails.
High-Level Architecture Overview
A naive implementation of an "AI SRE" gives an LLM access to a terminal with kubectl cluster-admin permissions. This is dangerous and irresponsible. LLMs are non-deterministic reasoning engines; they must never act directly on your infrastructure without a deterministic safety boundary.
Our architecture decouples Diagnosis (Reasoning Engine) from Execution (Deterministic Guardrail Engine).
┌────────────────────────────────────────────────────────────────────────┐
│ KUBERNETES NODE (KERNEL) │
│ │
│ ┌───────────────────┐ ┌────────────────────────────┐ │
│ │ Application Pod │ │ Tetragon eBPF Sensor │ │
│ └─────────┬─────────┘ └─────────────┬──────────────┘ │
└─────────────┼───────────────────────────────────────┼──────────────────┘
│ Events/Logs │ Kernel Traces
▼ ▼
┌────────────────────────────────────────────────────────────────────────┐
│ REMEDIATION CONTROL PLANE │
│ │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ Context Aggregator │ │
│ │ (K8s Event Stream + Log Tailer + eBPF Metric Engine) │ │
│ └──────────────────────────────┬─────────────────────────────────┘ │
│ │ Enriched Incident Context │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ Local Inference Engine (vLLM) │ │
│ │ [ Qwen2.5-Coder-7B-Instruct ] │ │
│ └──────────────────────────────┬─────────────────────────────────┘ │
│ │ Structured Action (JSON Tool Call) │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ Deterministic Guardrail Engine │ │
│ │ (Action Allowlist + RBAC Boundary + Schema Validation) │ │
│ └──────────────────────────────┬─────────────────────────────────┘ │
│ │ Validated Action Request │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ K8s API Executor / Controller │ │
│ └──────────────────────────────┬─────────────────────────────────┘ │
└──────────────────────────────────┼─────────────────────────────────────┘
│ K8s API Calls
▼
┌──────────────────────┐
│ Kubernetes API Server│
└──────────────────────┘
The System Pipeline
- eBPF Observation Layer: Cilium Tetragon monitors low-level kernel calls (syscalls, process executions, network socket opens, OOM kills) and streams them alongside K8s control plane events.
- Context Aggregator: Listens for abnormal events (
OOMKilled, high exit codes, broken pipes) and constructs a structured "Incident Context Document". - Local Inference Engine: Runs a quantized model locally on a dedicated control plane node (or GPU worker) via
vLLMorllama.cpp. - Deterministic Guardrails: The LLM outputs a Structured Tool Call (JSON schema). The Guardrail Engine validates the action against explicit bounds (e.g., maximum memory bump limits, allowed namespace actions).
- K8s API Executor: The controller executes the validated mutation via client-go / Python K8s SDK and posts an audit log to Slack/Teams.
1. Capturing Deep Observability with eBPF (Tetragon)
Standard kubectl logs don't show you kernel-level drops, socket leaks, or silent binary panics. We use Tetragon to intercept kernel functions directly via eBPF.
Below is a TracingPolicy that monitors process executions, sys_enter_write errors, and oom_kill_process events across target application namespaces.
apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
name: monitor-pod-failures
namespace: kube-system
spec:
kprobes:
- call: "oom_kill_process"
syscall: false
args:
- index: 0
type: "int"
selectors:
- matchArgs:
- index: 0
operator: "GreaterThan"
values: ["0"]
- call: "sys_enter_exit_group"
syscall: true
args:
- index: 0
type: "int" # Exit Code
When an application fails, Tetragon outputs rich JSON to standard stdout, capturing the exact PID, command, file descriptors, and kernel signals preceding the crash:
{
"process_kprobe": {
"process": {
"exec_id": "YWJjZGVmZ2hpams6MTIzNDU6MA==",
"binary": "/app/checkout-bin",
"arguments": "--port=8080",
"pod": {
"namespace": "prod",
"name": "checkout-service-7f998d-x82lq",
"container": { "id": "containerd://a1b2c3...", "name": "checkout" }
}
},
"function_name": "oom_kill_process",
"args": [{ "int_arg": 137 }]
}
}
2. Deploying the Local LLM Agent via vLLM
To maintain real-time sub-second inference speeds and absolute privacy, we deploy Qwen2.5-Coder-7B-Instruct (or Llama-3.1-8B-Instruct) using vLLM inside the cluster. We request dedicated GPU acceleration (e.g., a single NVIDIA A10G or T4 node).
apiVersion: apps/v1
kind: Deployment
metadata:
name: local-llm-engine
namespace: auto-heal
spec:
replicas: 1
selector:
matchLabels:
app: local-llm-engine
template:
metadata:
labels:
app: local-llm-engine
spec:
tolerations:
- key: "nvidia.com/gpu"
operator: "Exists"
effect: "NoSchedule"
containers:
- name: vllm-server
image: vllm/vllm-openai:v0.6.2
args:
- "--model"
- "Qwen/Qwen2.5-Coder-7B-Instruct"
- "--port"
- "8000"
- "--max-model-len"
- "8192"
- "--gpu-memory-utilization"
- "0.90"
ports:
- containerPort: 8000
resources:
limits:
nvidia.com/gpu: "1"
memory: "16Gi"
cpu: "4"
requests:
nvidia.com/gpu: "1"
memory: "12Gi"
cpu: "2"
---
apiVersion: v1
kind: Service
metadata:
name: llm-service
namespace: auto-heal
spec:
ports:
- port: 8000
targetPort: 8000
selector:
app: local-llm-engine
3. Designing the Guardrail & Remediation Engine
This is where architectural rigor matters most. We use Instructor and Pydantic in Python to enforce rigid schema responses. The LLM cannot return freeform English markdown; it must produce a valid schema match that maps directly to allowlisted cluster mutations.
Permitted Actions (Allowlist Architecture)
┌──────────────────────────────┐
│ Structured LLM Response JSON │
└──────────────┬───────────────┘
│
▼
┌──────────────────────────────────────────────────┐
│ Validation Engine (Enforce Boundaries) │
└────────────────────────┬─────────────────────────┘
│
┌─────────────────────────────┼──────────────────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Scale Replica│ │ Patch Memory │ │ Restart Pod │
│ Limits [1-10]│ │ Bump (+50%) │ │ (Delete) │
└──────────────┘ └──────────────┘ └──────────────┘
If the agent recommends deleting a namespace, scaling replicas to 1,000, or executing arbitrary bash commands—the system throws a validation error and defaults to human notification.
The Remediation Controller Code
Below is the complete, runnable Python controller engine that orchestrates the detection, context assembly, local LLM invocation, schema enforcement, and Kubernetes remediation execution.
import os
import json
import logging
from typing import Literal, Optional, Union
from pydantic import BaseModel, Field, SecretStr
from kubernetes import client, config
from openai import OpenAI
import instructor
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("AutoHealController")
# ------------------------------------------------------------------
# 1. Structured Output Schemas (Deterministic Guardrails)
# ------------------------------------------------------------------
class ScaleDeploymentAction(BaseModel):
action_type: Literal["ScaleDeployment"]
namespace: str
deployment_name: str
target_replicas: int = Field(
..., ge=1, le=10, description="New replica count. Must be between 1 and 10."
)
reasoning: str
class BumpMemoryLimitAction(BaseModel):
action_type: Literal["BumpMemoryLimit"]
namespace: str
deployment_name: str
container_name: str
memory_increase_mb: int = Field(
..., ge=128, le=2048, description="Memory increase in MB. Max bump is 2048MB."
)
reasoning: str
class RestartPodAction(BaseModel):
action_type: Literal["RestartPod"]
namespace: str
pod_name: str
reasoning: str
class UnhandledIncidentAction(BaseModel):
action_type: Literal["EscalateToHuman"]
reasoning: str
confidence_score: float
# Discriminated Union for strict validation
RemediationPlan = Union[
ScaleDeploymentAction,
BumpMemoryLimitAction,
RestartPodAction,
UnhandledIncidentAction
]
# ------------------------------------------------------------------
# 2. Reconciler Engine Class
# ------------------------------------------------------------------
class SelfHealingReconciler:
def __init__(self, llm_endpoint: str):
# Initialize K8s Client
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()
self.k8s_apps = client.AppsV1Api()
self.k8s_core = client.CoreV1Api()
# Initialize Local OpenAI-Compatible LLM Client via Instructor
self.llm_client = instructor.from_openai(
OpenAI(
base_url=f"{llm_endpoint}/v1",
api_key="none-local-vllm"
),
mode=instructor.Mode.JSON
)
def analyze_and_remediate(self, incident_context: dict) -> None:
logger.info(f"Analyzing incident for target: {incident_context.get('pod_name')}")
system_prompt = (
"You are a Kubernetes SRE Agent embedded in the control plane. "
"Analyze the following telemetry, container logs, and eBPF events. "
"Select the single most appropriate remediation plan based on the available tools. "
"Never attempt actions outside the defined schema. If uncertain, escalate to human."
)
try:
# Enforce schema constraint during local LLM completion
response: RemediationPlan = self.llm_client.chat.completions.create(
model="Qwen/Qwen2.5-Coder-7B-Instruct",
response_model=RemediationPlan,
max_retries=2,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": json.dumps(incident_context, indent=2)}
]
)
logger.info(f"LLM Agent Recommendation: {response.action_type}")
logger.info(f"Reasoning: {response.reasoning}")
# Execute guardrail validation and action dispatch
self.execute_remediation(response)
except Exception as e:
logger.error(f"Failed to generate or validate safe action plan: {str(e)}")
self.escalate_to_human("Schema validation failure or LLM timeout.", incident_context)
def execute_remediation(self, plan: RemediationPlan) -> None:
"""Executes actual K8s mutations bounded strictly by safety logic."""
if isinstance(plan, ScaleDeploymentAction):
logger.info(f"MUTATION: Scaling deployment {plan.deployment_name} in {plan.namespace} to {plan.target_replicas}")
body = {"spec": {"replicas": plan.target_replicas}}
self.k8s_apps.patch_namespaced_deployment_scale(
name=plan.deployment_name, namespace=plan.namespace, body=body
)
elif isinstance(plan, BumpMemoryLimitAction):
logger.info(f"MUTATION: Bumping memory for container {plan.container_name} in {plan.deployment_name} by {plan.memory_increase_mb}MB")
# Fetch current deployment limits
dep = self.k8s_apps.read_namespaced_deployment(name=plan.deployment_name, namespace=plan.namespace)
for container in dep.spec.template.spec.containers:
if container.name == plan.container_name:
current_mem = container.resources.limits.get("memory", "512Mi")
# Simple parse assuming Mi suffix
current_val = int(current_mem.replace("Mi", "").replace("Gi", "0024"))
new_val = f"{current_val + plan.memory_increase_mb}Mi"
container.resources.limits["memory"] = new_val
container.resources.requests["memory"] = new_val
self.k8s_apps.patch_namespaced_deployment(
name=plan.deployment_name, namespace=plan.namespace, body=dep
)
elif isinstance(plan, RestartPodAction):
logger.info(f"MUTATION: Restarting pod {plan.pod_name} in {plan.namespace}")
self.k8s_core.delete_namespaced_pod(name=plan.pod_name, namespace=plan.namespace)
elif isinstance(plan, UnhandledIncidentAction):
logger.warning(f"ACTION SKIPPED: Escalating to human. Reason: {plan.reasoning}")
self.escalate_to_human(plan.reasoning, {})
def escalate_to_human(self, reason: str, context: dict) -> None:
"""Webhook dispatcher for PagerDuty/Slack fallback."""
logger.info(f"[HUMAN NOTIFICATION SENT]: {reason}")
# ------------------------------------------------------------------
# Simulation Run
# ------------------------------------------------------------------
if __name__ == "__main__":
reconciler = SelfHealingReconciler(llm_endpoint="http://llm-service.auto-heal.svc.cluster.local:8000")
# Mocked Context provided by eBPF + Event Watcher Pipeline
mock_oom_incident = {
"namespace": "prod",
"pod_name": "checkout-service-7f998d-x82lq",
"deployment_name": "checkout-service",
"container_name": "checkout",
"exit_code": 137,
"k8s_event_message": "OOMKilled: Process terminated by kernel.",
"ebpf_telemetry": {
"kernel_signal": "SIGKILL",
"last_sys_call": "sys_enter_brk",
"memory_usage_bytes": 536870912,
"memory_limit_bytes": 536870912
},
"recent_logs": [
"2023-10-27T03:14:01Z [INFO] Processing batch payload of size 120MB...",
"2023-10-27T03:14:02Z [WARN] Allocating object buffer array...",
"2023-10-27T03:14:02Z [FATAL] java.lang.OutOfMemoryError: Java heap space"
]
}
reconciler.analyze_and_remediate(mock_oom_incident)
Step-by-Step Walkthrough: An Automated Incident Remediation
Let’s step through what happens when an incident occurs under this architecture:
1. Detection Phase
The checkout-service receives a spike in traffic containing unusually large JSON payloads. Memory usage explodes. The Linux kernel invokes oom_kill_process, sending a SIGKILL (Exit Code 137) to the process.
2. Aggregation & Context Assembly Phase
The Tetragon eBPF probe intercepts the oom_kill_process event at zero CPU overhead and maps the PID back to container checkout inside pod checkout-service-7f998d-x82lq. The Context Aggregator grabs the last 20 lines of logs, fetches current CPU/Memory resource constraints from the K8s API, and builds a JSON payload.
3. Inference Phase
The payload is dispatched to the local vLLM service inside the cluster. The local Qwen2.5-Coder-7B model parses the telemetry. It observes:
- Exit Code
137(OOM) - Log message explicitly indicating
OutOfMemoryError - The payload size causing allocation spikes
4. Structured Output Generation
The LLM selects the schema matching BumpMemoryLimitAction. It emits the following structured JSON response:
{
"action_type": "BumpMemoryLimit",
"namespace": "prod",
"deployment_name": "checkout-service",
"container_name": "checkout",
"memory_increase_mb": 512,
"reasoning": "eBPF telemetry confirms OOM (exit code 137) paired with Java Heap space crash logs. Temporarily increasing memory limit by 512MB to restore deployment stability."
}
5. Deterministic Guardrail Check
The response passes through the Python Pydantic engine:
action_typematches the allowlisted enum? Yes.memory_increase_mb(512) is withinge=128, le=2048limits? Yes.deployment_nameexists in namespaceprod? Yes.
6. Execution & Auto-Healing
The controller issues a patch command to the Kubernetes API server, increasing the container's memory limit from 512Mi to 1024Mi. The Deployment performs a rolling update. The service stabilizes.
Total time elapsed from crash to fix: 1.4 seconds. No humans were woken up.
Production Security & Safety Considerations
While running local LLMs removes external data leakage, running remediation code requires strict operational guardrails:
-
Least-Privilege RBAC: The service account running your remediator controller must never hold
cluster-adminprivileges. Scope itsClusterRolespecifically to allowed resource verbs (patchdeployments,deletepods in specific namespaces). Never permit dynamic execution verbs likeexecor deletingNamespaces/CRDs. -
Cooldown Rates & Circuit Breakers: Prevent action loops (e.g., the LLM constantly bumping memory every 10 seconds up to infinity). Implement local caching (Redis/In-Memory) to lock remediation on a per-deployment basis (e.g., maximum 2 automated fixes per deployment per 24-hour window).
-
Fallback to Human-in-the-Loop: If the LLM’s confidence score is low, or if the deterministic Pydantic validation throws a
ValidationError, the system must immediately trigger a standard pager alert with the pre-assembled context attached.
Conclusion
The future of cloud infrastructure management isn't about staring at dashboards or writing massive, brittle, non-maintainable Bash scripts filled with edge-case if-else blocks.
By combining eBPF for transparent kernel observation, Local Quantized LLMs for context-aware reasoning, and Pydantic/K8s Operators for strict deterministic execution boundaries, we can build truly autonomous self-healing systems.
You keep your data strictly on-premises, keep your cloud bill flat, and—most importantly—get a full night’s sleep.