How AI SRE Agents Safely Self-Heal: Evidence-Driven Design for Recoverable Execution
This article details the engineering design of a safe AI SRE self-healing system, covering evidence collection, hypothesis diagnosis, plan authorization, conditional execution with concurrency control, persistent state recovery, and validation with compensation, using Kubernetes and Java microservices as the primary context.
Reading font

Introduction
Making a large model analyze alerts is easy; the hard part is ensuring the system still knows which actions can execute and which must stop when evidence is incomplete, approvals have expired, API calls time out, or execution processes restart. This article builds a closed loop—evidence collection, hypothesis diagnosis, plan generation, authorization, execution, verification—around Kubernetes and Java microservices, focusing on action boundaries, concurrency control, persistent recovery, and conditional compensation. The core principle: the model proposes candidate plans, the platform verifies facts, and the executor only performs currently authorized concrete changes.
Scope and Assumptions
Applicable to teams with existing metrics, logs, change records, and basic runbooks. The first phase covers only a few stateless workloads and explicit business switches. Database failover, data repair, and cluster-level network changes are excluded from automatic execution. All incidents, numbers, and policy thresholds are fictional teaching examples, not real production cases or universal standards. YAML shows a platform-specific protocol; Go snippets demonstrate single conditional writes and are not production-ready executors.
1. Counterexample: Database Overload — Why Not Scale the Application First?
At 03:15, order API P99 rises from 45 ms to 3.2 s, gateway returns 504, and application requests waiting for database connections increase. If the agent scales the order service based solely on "thread pool full, connection pool waiting", it may amplify the failure. Assuming each instance has a connection pool limit of 50, scaling from 6 to 12 instances raises the theoretical connection limit from 300 to 600. Connections may not all be established, and database throughput won't double, but the potential connection and concurrency pressure on the database changes.
A better diagnostic path verifies separately:
Application CPU, run queue, GC — is compute capacity insufficient?
Database query latency, lock waits, slow SQL fingerprints, execution plans — have they changed?
Feature flags, releases, config changes — did they precede the anomaly?
Traffic growth — which interface, tenant, or business branch?
"Connection pool full" is an observed fact; "database execution capacity insufficient" is a hypothesis to validate; "missing index" needs direct SQL evidence. The three must not be merged into a single definitive root cause.
If later evidence supports: a campaign entry triggers high-cost queries, saturating the database, and the core order path suffers collateral impact. The priority candidate should be closing the pre-registered campaign entry, rate-limiting that traffic branch, or enabling existing degradation strategies. SQL optimization follows the normal change process.
Closing a campaign also impacts business and requires explicit authorization. Downstream backpressure blocking scale-out does not automatically grant permission to rate-limit or close the campaign. Alternative actions need their own plan, risk assessment, and approval.
The AI SRE goal: shorten recovery time within authorized scope while controlling new damage; "number of automatic repairs executed" is only a process metric.
Fault Drill: From Alert to Conditional Recovery
The following fictional drill record uses numbers to explain decisions, not measured results or universal thresholds. Assume the order core interface and campaign entry share a database; the campaign switch config service supports versioned compare-and-update; closing the campaign affects promotions but not normal ordering. All times are Beijing time.
03:15 : Order P99 rises from 45 ms to 3.2 s; connection pool waits increase. Decision: Establish incident; connection pool wait is a symptom, insufficient to prove instance shortage.
03:16 : CPU not saturated; campaign entry request surge; database active sessions and query waits rise. Decision: Hypothesis: campaign traffic causes database contention; retain alternative hypotheses (lock contention, release regression).
03:17 : SQL fingerprint shows significant increase in campaign query occupancy; recent releases show no corresponding changes. Decision: Query fingerprint supports correlation, not causation alone; execution plan still missing, continue collection.
03:18 : Execution plan shows high scan volume for that query; campaign traffic change precedes database pressure rise. Decision: Multi-source evidence supports prioritizing campaign traffic mitigation; common cause still possible, root cause not claimed proven.
03:19 : Propose plan to close specific campaign entry, showing impact, version 184, and recovery conditions. Decision: Business owner approves concrete plan; database overload rejects scale-out candidate, does not auto-grant degradation permission.
03:19:30 : Executor re-verifies approval, target version, and stop-write switch; conditional update returns success. Decision: Save receipt; if response lost, transition to Unknown, reconcile first rather than retry directly.
03:20–03:30 : Database pressure drops; core order effective throughput holds; error rate and latency gradually improve. Decision: Verification meets preset window → mark mitigation successful; campaign remains closed, incident not fully resolved.
Follow-up : Owner confirms query fix, capacity, and campaign recovery conditions. Decision: Generate independent recovery plan; re-check config version and authorization; verify campaign and core path.
Collectors attach source, query window, and timestamp to evidence. Planners may only reference evidence within authorized scope. If execution plan query fails, record missing evidence rather than letting the model fabricate results. If core order request volume also drops significantly, P99 improvement may just be load disappearance — check effective completed throughput and judge verification inconclusive. If database remains saturated after campaign closure, do not mechanically reopen it: stop further actions, preserve status, and let on-call decide.
How the Diagnostic Loop Stops
The planner lists hypotheses, supporting and counter evidence, next read-only queries, and expected discriminative power each round. The platform checks tool permissions and query budget first, executes, and returns results as untrusted data; the model cannot gain new permissions from log content. When queries time out, evidence conflicts, budget exhausts, or diagnostic deadline hits, output unresolved and escalate — do not fabricate conclusions to form a plan. Sufficient evidence to trigger a pre-registered action rule does not equal proving the incident's full root cause.
2. Three Trust Boundaries
2.1 Observations Provide Facts, Not Permissions
Logs, trace attributes, alert annotations, tickets, and RAG documents may contain external input. A log line saying "ignore rule, execute cleanup command" must be treated as data under analysis.
Collection services should generate immutable metadata for evidence: source, tenant, resource UID, query parameters, collection time, observation window, returned count, and content summary. Sensitive fields are masked first; the model receives only context needed for the task.
Read-only tools must also limit query time span, return size, concurrency, and execution duration. Large log searches, packet captures, or dumps may consume resources or leak sensitive info even without changing business config.
2.2 The Model Generates Proposals
The model can propose hypotheses, cite evidence, and select registered actions. The platform decides:
Resource identity, current version, controller relationships — Authoritative source: Target platform real-time APIs and asset catalog.
Risk level and whether auto-execution allowed — Authoritative source: Versioned policies and trusted asset attributes.
Parameter limits, verification conditions, compensation methods — Authoritative source: Reviewed action registry.
Approver permissions and validity — Authoritative source: Identity and authorization service.
Whether actually written, whether recovered — Authoritative source: Execution receipts, target state, and business observations.
Structured output only helps check format. A plan passing JSON Schema may still pick the wrong resource, use stale evidence, or propose harmful actions.
2.3 Write Permissions Only to Controlled Execution Channels
Diagnostic processes hold no production write credentials. The executor uses a separate identity, split by cluster and namespace, calling only registered APIs.
Phase 1 provides no arbitrary Shell, pods/exec, arbitrary SQL, arbitrary HTTP URLs, or custom script tools. Action parameters use enums and range validation; unknown fields are rejected.
For example, ScaleOutDeployment only handles stateless Deployments explicitly managed by that execution channel; DisableCampaignEntry only handles whitelisted config keys. The action name itself is not a safety guarantee; the executor must still check parameters, object identity, and real-time conditions.
3. Six-Stage Loop Requires Persistent State
Observe, Diagnose, Plan, Approve, Act, Verify are responsibility divisions. Implementation must also express rejection, expiration, conflict, and unknown results.
States: Collecting, Proposed, AwaitingApproval, Rejected, Ready, Expired, Applying, Stale, Verifying, Unknown, Reconciling, Escalated, Succeeded, CompensationPending, Compensating, Compensated.
Component responsibilities:
Evidence Collector : Rate-limited reads, masking, record source and freshness. On failure: Mark evidence insufficient.
Diagnosis & Planner : Generate hypotheses and candidate actions. On failure: Retryable, no production write permission.
Policy & Approval Service : Compute risk, bind plan, check budget. On failure: Reject new write operations.
Persistent Coordinator : State transitions, task claiming, recovery reconciliation. On failure: Restart and continue from persisted state.
Cluster Execution Gateway : Real-time re-verification, conditional write, receipt. On failure: Conflict stops, timeout enters unknown.
Verifier : Check business effect and side effects. On failure: Distinguish failure and indeterminate.
LangGraph can be used for model reasoning flows, Temporal for persistent workflows; their responsibilities should not be conflated. A database state machine with workers can also work but must bear the cost of recovery, deduplication, timeouts, and concurrency coordination. Regardless of orchestrator, external API side effects need separate handling.
Suggested minimum persistent records:
incident : Affected services, time interval, alert aggregation key, evidence references.
plan : Immutable plan body, normalized summary, target UID, policy version.
approval : Plan summary, approver, authorization scope, expiry, revocation status.
execution : State, row version, lease, fencing token, execution deadline.
action_attempt : Idempotency key, pre-snapshot, request summary, result, reconciliation conclusion.
budget_reservation : Scope, quota, reserved and consumed status.
outbox : Pending events, retry and acknowledgment status.
Commit task state and outbox first, then deliver asynchronously to avoid "task persisted but message lost". This only connects database and message delivery; cannot make Kubernetes writes part of the same transaction.
3.1 State Transition Constraints and Takeover
The state diagram describes main paths; production implementation must write state, necessary budget records, and outbox in the same transaction using row-version CAS. Below are minimum transition constraints; each action still needs its own timeout and reconciliation protocol.
Collecting → Event: Evidence sufficient to form candidate. Transition: Planner saves immutable plan → Proposed; insufficient or timeout → record reason, escalate to human.
Proposed → Event: Policy reject / needs authorization. Transition: Policy service → Rejected / AwaitingApproval; rejection reason auditable.
AwaitingApproval → Event: Valid approval / expiry or revocation. Transition: Auth service binds plan summary → Ready; expiry → Expired, revocation rejects subsequent writes.
Ready → Event: Lease, budget, authorization, and real-time conditions all satisfied. Transition: Coordinator persists intent, attempt record, pre-snapshot → Applying; condition change → Stale.
Applying → Event: Trusted success receipt / explicit not sent / result unknown. Transition: → Verifying / end or retry per policy / Unknown; unknown retains budget.
Unknown / Reconciling → Event: Target and audit sufficient to confirm applied or not. Transition: Applied → Verifying; confirmed not applied and auth valid → retry; cannot confirm → Escalated.
Verifying → Event: Pass / Fail / deadline still Inconclusive. Transition: Record mitigation success / evaluate compensation / Escalated; Fail ≠ must compensate.
CompensationPending / Compensating → Event: Valid compensation auth obtained and re-verified / result unknown. Transition: Compensation uses independent attempt and idempotency key; unknown also reconcile first, cannot confirm → Escalated.
Cancel, approval revocation, and stop-write switches forbid new writes not yet sent; they cannot recall requests already accepted by the target. In-flight or unknown operations still require reconciliation. Terminal states include Rejected, Expired, Stale, Succeeded, Compensated, Escalated; Succeeded means this action's verification passed, not that the whole incident is resolved. In-flight compensation unknown can be modeled as independent action instance's Unknown, not discarding the original execution record.
On takeover, new worker obtains a new monotonic fencing token, then identifies whether old requests are in-flight and reconciles. Gateway rejects subsequent expired tokens, but that doesn't mean it can revoke requests that already passed checks. If target doesn't support atomic token verification, list this window as a system limitation; stop related writes and escalate when result cannot be confirmed.
4. Evidence Chain Must Allow "Don't Know"
Recommend separating facts, hypotheses, counter-evidence, and missing evidence:
{
"incidentId": "INC-20261127-0315",
"hypotheses": [
{
"id": "H1",
"summary": "Campaign query causes insufficient database execution capacity",
"supportingEvidence": ["EV-traffic", "EV-sql", "EV-db-wait"],
"counterEvidence": [],
"missingEvidence": ["Execution plan of affected SQL fingerprint"],
"status": "needs_validation"
}
],
"nextReadOnlyActions": ["FetchQueryPlan", "CompareEndpointTraffic"]
}Evidence objects are stored independently by the collection layer. The model can only reference existing IDs belonging to the current tenant and incident; the platform validates reference existence, tenant ownership, permissions, source, and time range — these checks alone cannot prove evidence supports a causal conclusion. Rules can only verify pre-defined computable conditions; causal explanation still requires counter-evidence, domain rules, or human review; additional model review cannot serve as independent proof.
Model output confidence: 0.92 does not equal 92% probability of correct root cause. Without calibration data, do not use it to approve production actions. Evidence freshness, coverage, cross-validation results, and counter-evidence are better suited for approval cards.
Call topology only provides candidate ranking. A calls B, B calls C does not imply C is necessarily the root cause; upstream retry amplification, shared database, network faults, and incomplete sampling produce similar phenomena. Alerts can be aggregated, but do not directly forbid diagnosis of A or B.
5. Action Protocol: Bind Approval to Concrete Change
The main example uses a pre-registered campaign switch action, not scaling the application during database overload:
# Platform internal protocol; not a Kubernetes built-in resource.
apiVersion: sre.example.io/v1alpha1
kind: RemediationPlan
metadata:
planId: PLAN-20261127-001
incidentId: INC-20261127-0315
spec:
action:
type: DisableCampaignEntry
version: v1
target:
environment: production
tenant: trade
namespace: prod-trade
configId: campaign-entry
key: promo.flash_sale.enabled
expected:
configRevision: "184"
currentValue: true
desired:
value: false
evidenceRefs: [EV-traffic, EV-sql, EV-db-wait]
verificationProfile: order-campaign-mitigation-v1
compensationProfile: conditional-restore-campaign-v1
expiresAt: "2026-11-26T19:20:00Z"The example incident is narrated at Beijing time Nov 27 03:15; the UTC expiry above corresponds to Beijing 03:20; unified storage timezone avoids approval expiry judgment errors.
Two implementation constraints: the target config service must provide matching conditional update semantics; the adapter cannot assume a configRevision CAS exists. If no native conditional update, a unified config gateway must serialize and forbid other write channels bypassing it; otherwise equivalent concurrency safety cannot be promised.
The platform-supplemented and signed approval payload must include at least: plan normalized summary, target identity, action version, preconditions, parameters, verification and compensation config versions, policy version, approver, and validity. Summary uses a well-defined normalized serialization, not arbitrary JSON field order.
Approval page should show "which entry closed, who impacted, which core paths retained, under what conditions to recover". If model modifies action or parameters, original approval invalidates.
Approval usually precedes execution lease. Human wait does not long-hold resource locks; before execution, acquire lease, reserve budget, read latest state, re-verify approval and policy. If state already changed → Stale, cannot silently modify plan and reuse old approval.
6. Risk Grading: "Read-Only" ≠ "No Risk"
Starting template; final grading must consider asset criticality, operation cost, data sensitivity, and blast radius:
R0: Restricted Observation — Examples: Time- and count-limited metric, log, event queries. Default execution mode: Auto-execute, query budget constrained.
R1: Rehearsed Limited Changes — Examples: Verified single-workload small step scale-out. Default execution mode: Auto within whitelist, real-time pre-checks.
R2: Business-Impacting or High Runtime Cost — Examples: Close campaign, rate-limit, rolling restart, heap dump, adjust log level. Default execution mode: Human approval or explicit scenario pre-authorization.
R3: High Impact or Stateful — Examples: Failover, data repair, cross-cluster network adjust. Default execution mode: Phase 1 only generates suggestions, hand to existing ops process.
Packet capture, heap dump may cause performance overhead and sensitive data exposure; debug logs change runtime state and may amplify disk pressure; cordoning pods reduces service capacity. These must not be classified as "no side-effect R0".
Similarly, "scale-out not exceeding 50%" is just a parameter limit. When database saturated, node unschedulable, connection budget insufficient, or object managed by another controller, adding one replica may still be unsuitable.
Operation budgets should cover call frequency, concurrent changes, resource increments, downstream connections, and model cost. Related to SRE Error Budget but not the same concept.
Budget deduction needs atomic reservation: two workers must not both read remaining 1 quota and both get approved. Explicitly unsent request failures can be refunded per rule; unknown results retain quota until reconciliation completes.
7. Concurrency Control: Locks, Versions, Fencing — What Each Solves
Database CAS state transition — Problem solved: Same task not claimed by two workers simultaneously. Cannot guarantee: Does not protect external resource writes.
Lease and renewal — Problem solved: Crash allows another worker to take over. Cannot guarantee: Old worker won't resume running.
Fencing token — Problem solved: Reject new requests from old owner. Cannot guarantee: No protection if target system doesn't verify.
Resource UID and version condition — Problem solved: Prevent same-name recreation and stale state overwrite. Cannot guarantee: Does not express execution task ownership.
Idempotency key and operation receipt — Problem solved: Deduplicate retries and reconcile results. Cannot guarantee: Does not automatically achieve cross-system exactly-once.
Using Redis SET NX EX alone is insufficient: lease expiry doesn't stop old worker from continuing. Releasing lock must verify owner, not delete new holder's lock.
Fencing must be enforced at the actual write-receiving channel. Writing token into annotation won't make Kubernetes automatically understand or reject old token. Can use a single cluster execution gateway to verify task ownership and serialize target conflicts; higher safety needs target-side admission or controller mechanisms so all relevant writes accept same verification, and explicitly define in-flight request handling boundaries.
Cannot claim "gateway checked token once" as atomic guarantee under arbitrary failures: between check and target write, lease may change. Takeover must first reconcile in-flight ops; high-risk ops need stronger target-side execution protocols.
Conflict scope should not be crudely set to "only one action per entire call chain". Suggest at least combining target resource lock with shared bottleneck budget: same Deployment serializes; scaling contending for same database shares connection budget; unrelated services can run in parallel. Use more conservative scope when topology unknown.
8. Go Implementation: One Conditional Scale-Out Write
To demonstrate Kubernetes native concurrency semantics, the following uses a single scale-out scenario with healthy database, no HPA/KEDA, and replica count managed by this execution channel . It is not used for the database overload incident above.
Kubernetes uses resourceVersion to detect stale updates; version conflict means re-read and re-evaluate, not unconditional overwrite. [1]
package executor
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
)
// Frozen by platform after approval; not directly deserialized from model output.
type ApprovedScale struct {
Namespace string
Name string
DeploymentUID types.UID
ScaleResourceVersion string
Before int32
After int32
}
// Only shows one conditionally protected write; excludes auth, lease, recovery coordination.
func ApplyScaleOnce(
ctx context.Context,
client kubernetes.Interface,
p ApprovedScale,
) error {
if p.DeploymentUID == "" || p.ScaleResourceVersion == "" {
return fmt.Errorf("missing approved identity or version")
}
// Example action only allows small step scale-out with 2+ replicas, no scale-down.
if p.Before < 2 || p.After <= p.Before || int64(p.After)-int64(p.Before) > int64(p.Before)/2 {
return fmt.Errorf("outside scale-out bounds")
}
api := client.AppsV1().Deployments(p.Namespace)
dep, err := api.Get(ctx, p.Name, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("read deployment: %w", err)
}
if dep.UID != p.DeploymentUID {
return fmt.Errorf("deployment identity changed")
}
scale, err := api.GetScale(ctx, p.Name, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("read scale: %w", err)
}
if scale.UID != p.DeploymentUID ||
scale.ResourceVersion != p.ScaleResourceVersion ||
scale.Spec.Replicas != p.Before {
return fmt.Errorf("approved preconditions are stale")
}
next := scale.DeepCopy()
next.Spec.Replicas = p.After
_, err = api.UpdateScale(ctx, p.Name, next, metav1.UpdateOptions{})
if err != nil {
// Conflict should invalidate plan; timeout should enter Unknown, coordinator reads target to reconcile.
return fmt.Errorf("conditional scale update: %w", err)
}
return nil
}This retains GetScale returned metadata to avoid constructing a new Scale object missing version. On conflict, do not force old target by continuously refreshing version in RetryOnConflict; only re-verify approval conditions still satisfied, then form new execution attempt per platform rules.
This snippet has clear boundaries: controller relationships, budget, approval revocation, downstream capacity, and fencing are checked by outer execution gateway. It does not implement full error classification, idempotent receipts, persistent recovery, nor prove arbitrary external writes are isolated.
8.1 HPA, KEDA, and GitOps: One Field Needs Clear Control
HPA periodically adjusts target workload replica count, so cannot assume Agent gains continuous control after writing replica count. [2]
Phase 1 recommends rejecting direct scale-out if HPA/KEDA management detected. Later may add independent action to temporarily adjust HPA minReplicas, but must separately handle maxReplicas, scheduling capacity, GitOps write-back, KEDA's management of generated HPA, and recovery condition checks.
No universal "detect HPA then patch minReplicas" patch fits all environments. Restoring minReplicas cannot casually write actual replica count back to old value.
8.2 PDB Is Not Insurance for All Scale-Down and Restarts
PDB constrains eviction flows matching its mechanism; cannot assume direct pod deletion, replica count change, or Deployment rolling update automatically obey same availability boundaries. Rolling update needs to check workload's own maxUnavailable and maxSurge. [3]
Similarly, preStop sleep 10 is not a universal graceful shutdown guarantee. Should verify stop accepting traffic, endpoint/registry propagation, in-flight request and long-lived connection draining, process exit, and termination grace period as a whole.
8.3 Minimum Verification Environment and Permissions
Steps to verify execution behavior in isolated environment. Pin Kubernetes cluster and client-go versions; refer to client-go compatibility notes, run integration tests on actual target versions. Use isolated test cluster and dedicated namespace, create test Deployment with at least 2 replicas, ensure no HPA, KEDA, or GitOps competing for replica control.
Execution identity needs at least apps API group
deploymentsget, and
deployments/scaleget, update in target namespace. Restrict with Role and RoleBinding to namespace and resource name; verify unrelated resources and other namespaces writes rejected; actual gateway also needs its own identity, policy, and audit. Read-only permissions to check controller relationships granted per implementation, not cluster-admin because example needs it.
Read UID, Scale resourceVersion, current replicas; construct approved object within bounds; call update once; check desired replicas and controller final state.
After approval, another client modifies target; submit old version; assert new state not overwritten; record actual conflict or precondition failure.
Delete and recreate test Deployment with same name; assert old UID plan rejected.
Use controlled proxy to simulate request sent but response lost; reconcile via target state and audit records; current value equality alone cannot prove write ownership.
Cover approval revocation, budget contention, process crash before/after write, monitoring unavailable. These belong to outer coordinator tests; cannot be replaced by running ApplyScaleOnce alone.
Test report should record cluster and client versions, injection points, requests and receipts, final object state, and uncovered windows. When simulation proxy or audit info insufficient, explicitly mark as indeterminate, not treat test pass as exactly-once proof.
9. API Timeout Is Not Failure: Recovery Must Reconcile First
The most easily missed failure window: target API accepted change, but executor crashes before saving receipt. On restart, if Applying is treated as failure and retried, duplicate side effects may occur.
Recommended flow:
Database records execution intent, action idempotency key, approval summary, pre-snapshot.
After real-time gate, call target API.
Request success → record receipt; request timeout or connection break → enter Unknown.
Recovery coordinator reads target state and audit records, judges whether applied.
If confirmed applied → verification; if confirmed not applied and auth still valid → allow retry; if cannot confirm → pause writes and escalate to human.
For "set absolute replica count", duplicate requests usually converge easier than "add 3 more replicas" if no other writes; but same target value doesn't prove it was this plan's write. Must combine execution record, resource identity, and trusted audit info for attribution.
For notifications, restart triggers, failover, each must define deduplication and reconciliation individually. Without common transaction or target-side idempotency protocol, do not claim cross-system exactly-once.
10. Verification Needs Three Outcomes; Compensation Needs Re-Authorization
10.1 Verify Action Effect, Then Business Recovery
Kubernetes update success only means API accepted desired state. Still need to observe controller progress, available replicas, scheduling failures, startup failures, then enter business observation.
Don't fixed-wait 30 seconds and assume JVM warmup done. Configure verification window based on app startup, traffic admission, cache and connection pool warmup characteristics, and set total deadline.
Using classic Histogram, service-level P99 should aggregate buckets then compute quantile, not average per-instance P99: [4]
histogram_quantile(
0.99,
sum by (le) (
rate(http_request_duration_seconds_bucket{
cluster="prod-a", namespace="prod-trade",
app="order-service", route="create-order"
}[5m])
)
)Labels and metric names must match actual instrumentation. Above metric unit is seconds; 0.2 means 200 ms. Verification config should also include error rate, effective completed throughput, queue wait, and database pressure.
Closing campaign reduces traffic; P99 improving doesn't mean order business recovered. Therefore must distinguish "core path recovered", "campaign still degraded", and "incident fully resolved".
10.2 Return Pass, Fail, Inconclusive
Pass — Typical conditions: Data valid, samples sufficient, target metrics continuously met, side effects controlled. Subsequent behavior: Record this mitigation success, continue observing.
Fail — Typical conditions: Availability drops, error rate clearly worsens, explicit failure. Subsequent behavior: Stop subsequent steps, evaluate compensation.
Inconclusive — Typical conditions: Query failure, stale data, NaN, no traffic, insufficient samples. Subsequent behavior: Limited wait, timeout then escalate.
Adjacent five-minute sliding windows highly overlap; three consecutive samples cannot count as three independent evidences. Window and duration should match business traffic, decided by fixed verification config; model cannot relax success conditions.
"Exceeds SLO 2x" ≠ action caused worsening. If pre-execution P99 3.2 s, post-execution 1.0 s, target 0.2 s, action may have already mitigated. Verification should combine pre-execution baseline, absolute safety floor, traffic changes, and control group; not attribute by single threshold.
10.3 Compensation Is Not Mechanical Snapshot Restore
Scale-out not meeting target doesn't mean immediate scale-down is safer; campaign closure effect unclear doesn't mean reopen entry.
Before compensation, at least check: object identity unchanged, current field still this plan's written value, no human takeover, approval and policy allow compensation, current capacity and downstream pressure support recovery. Check failure → stop auto changes, preserve evidence, escalate.
Compensation is independent controlled action with its own idempotency key, execution record, and verification result. Successful config restore ≠ business damage undone; state naming should be Compensated, not counted as self-healing success.
User cancel request or HTTP context timeout cannot delete execution record. Persistent coordinator completes reconciliation and necessary handling in independent, time-bounded, still-authorized context.
11. Evaluation: Test Diagnosis, Execution Safety, and Recovery Together
11.1 Fault Matrix Covers Normal Demo Blind Spots
Logs contain malicious instructions or forged evidence IDs — Must observe: No tool permission expansion, no trust in non-existent evidence.
Target changes or same-name resource recreated after approval — Must observe: Plan invalidated, old approval rejected.
Two workers claim simultaneously — Must observe: Only one succeeds state transition, budget not double-reserved.
Old worker sends new request after lease expiry — Must observe: Write channel verifies and rejects expired owner, records reason.
Old request passed gateway check and in-flight during takeover — Must observe: New owner reconciles first; unless target provides stronger protocol, cannot assert in-flight request will be rejected.
Write succeeded but response lost — Must observe: Enter Unknown, reconcile first.
Process crashes after change, before recording — Must observe: Restart recovers reconciliation, no blind replay.
HPA/GitOps/human modify simultaneously — Must observe: Detect conflict and pause, no mutual overwrite.
Monitoring fails during verification — Must observe: Inconclusive, do not declare success.
Human already took over target field — Must observe: Compensation does not overwrite human change.
Downstream database overloaded — Must observe: Reject scale-out; alternative action independently authorized.
Do offline alert replay, desensitized sample evaluation, and staging drills before limited production canary. Chaos Mesh and similar fault injection tools for authorized drill environments; should not gain production injection rights just because included in Agent architecture.
11.2 Metrics Must Explain Denominator and Uncertainty
RCA Top-1 — Suggested definition: Among events with confirmable root cause labels, proportion where first hypothesis hits.
Auto Mitigation Success Rate — Suggested definition: Among pre-defined automation-applicable events, proportion achieving recovery conditions without human help.
Automation Coverage — Suggested definition: Events matching automation scope / total events.
Harmful Action Rate — Suggested definition: Reviewed actions causing new damage / total executed actions.
Unknown Result Convergence Rate — Suggested definition: Unknown attempts completing definitive reconciliation within specified time limit.
Recovery Time — Suggested definition: Median and P90 by fault type, with start/end points explained.
Human Burden — Suggested definition: Approvals per event, takeovers, effective handling time.
Don't count all "triggered compensation" as harmful: harmless but ineffective actions, monitoring unavailable, and true secondary faults are different outcomes. Conversely, no compensation triggered doesn't prove harmless.
85% localization accuracy, 75% auto recovery, 60% MTTR improvement, 1% harmful action rate should not be used as sourceless universal admission standards. Thresholds must be set per business loss tolerance, fault type, and sample size.
Example: under i.i.d. binomial approximation, 300 executions with zero harmful events gives one-sided 95% upper bound ~1% via "3/n" rule. Real incidents have correlation and distribution drift; cannot prove production harmful rate necessarily below 1%. High-damage actions cannot be approved by low-frequency stats alone.
12. Phased Rollout: Every Step Must Be Able to Stop New Writes
Read-Only Diagnosis — Open scope: Aggregate evidence, generate hypotheses, give candidate plans. Evidence to enter next phase: References traceable, permissions and query budgets effective.
Human-Approved Execution — Open scope: Single service, few actions, explicit approvers. Evidence to enter next phase: State drift, unknown results, crash recovery drills pass.
Whitelist Auto Execution — Open scope: Repeatedly rehearsed low-impact scenarios. Evidence to enter next phase: Sufficient samples, online side-effect monitoring, human can take over anytime.
Expand Scenarios — Open scope: Gradually add actions and asset scope. Evidence to enter next phase: Each action independently reviewed and rehearsed, continuously observe drift.
The first loop can implement just two actions: one limited scale-out, one approved business degradation switch. Database state machine, single-cluster execution gateway, versioned registry, and Prometheus verifier are enough to start; no need for multi-agent, vector DB, complex topology platform initially.
Global, cluster, action, target resource four-level stop-write switches must be enforced by execution channel, recording policy version and decision time. Stop-write defaults to forbid new changes; in-flight or unknown tasks still continue reconciliation. Human takeover must leave explicit ownership to prevent recovered Agent from overwriting on-call operations.
Conclusion
A reliable AI SRE Agent must be able to explain: which evidence the conclusion comes from, which change the approval covers, whether state still satisfies conditions at execution time, and how to confirm real result after call timeout.
When evidence insufficient, authorization expired, monitoring failed, or resource taken over by human, stopping automatic writes is itself the correct outcome. Only by grounding these boundaries in persistent state and real write channels does automatic self-healing have a verifiable engineering foundation.
Technical Verification References
Following official docs verify base platform semantics; this article's risk grading, state machine, budget model, and action protocol are design suggestions, not complete solutions provided by these projects.
Kubernetes API Concepts: version conditions, concurrent updates, conflicts
Kubernetes Horizontal Pod Autoscaling: replica control loop
Kubernetes Disruptions: PDB scope; Deployments: rolling update strategy
Prometheus Query Functions: histogram_quantile; Histograms and Summaries
For questions about attribution, corrections or content rights, please contactand we will review it promptly.