Autonomous Oracle Incident Triage: Streaming AWR Telemetry to LLM Diagnostic Agents
Content reflects the state as of August 2026. AI tooling and model capabilities in this area change frequently.
Severity-1 Oracle triage stalls on human report navigation rather than missing telemetry, and a bounded MCP triage agent can correlate ASH waits, top SQL, and index visibility into a PII-masked Slack RCA before the on-call engineer finishes logging in.
TL;DR
- Problem: Correlating
V$ACTIVE_SESSION_HISTORY,V$SQL, execution plans, andDBA_INDEXEStakes a DBA 15–25 minutes under alert pressure, while giving an LLM raw SQL access leaks PII literals and risks unboundedDBA_HIST_*scans.- Answer: Insert an 8-call bounded triage agent between the alert webhook and Slack that queries curated MCP tools, masks SQL literals before they reach the model, and enforces a 5% CPU,
DOP=1, 10-secondSWITCH_TIME_IN_CALLOracle Resource Manager cap.- Watch out: Autonomous triage is strictly read-only advisory—ambiguous telemetry or missing hourly AWR snapshots require explicit confidence tagging and human verification before running any remediation DDL.
Situation
Oracle Database emits granular wait and SQL telemetry continuously. Active Session History (V$ACTIVE_SESSION_HISTORY) samples active sessions every 1 second in an SGA circular buffer, and the Automatic Workload Repository (DBA_HIST_ACTIVE_SESS_HISTORY) flushes 1 in 10 of those samples (10-second granularity) into hourly snapshots alongside DBA_HIST_SQLSTAT and plan history. For cloud deployments, OCI Performance Hub, Compare Period ADDM, and Operations Insights AWR Hub surface these metrics in dashboards—and Oracle AI Database 26ai extends native AWR support to Active Data Guard standbys.
For self-managed Oracle fleets across VMs, EC2, or on-premises hosts, incident response still starts with an OEM or Datadog webhook waking an on-call DBA. Three recurring Sev-1 patterns—row lock contention (enq: TX - row lock contention), invisible or unusable index regressions (TABLE ACCESS FULL on large fact tables), and sudden plan flips—leave unambiguous signatures across four views: V$ACTIVE_SESSION_HISTORY identifies the dominant non-idle wait class, V$SQL surfaces the top elapsed-time SQL_ID and CHILD_NUMBER, V$SQL_PLAN reveals whether the optimizer switched to a full table scan, and DBA_INDEXES confirms whether a deployment left an index INVISIBLE or UNUSABLE. The engineering gap is connecting the alert webhook to that deterministic four-step correlation without letting an AI agent write arbitrary SQL.
The Problem
Replacing manual AWR navigation with an autonomous LLM triage loop fails under four concrete operational constraints.
1. 1-second ASH vs. 10-second AWR snapshot lag. If an incident fires 10 minutes after the top of the hour, DBA_HIST_SQLSTAT does not yet contain the offending interval. A triage tool that queries only DBA_HIST_* views returns empty rows; conversely, querying DBA_HIST_ACTIVE_SESS_HISTORY without a SAMPLE_TIME predicate triggers a full partition scan across weeks of retained history.
2. PII exposure inside V$SQL.SQL_TEXT. Applications that concatenate user inputs instead of using bind variables leave Social Security Numbers, email addresses, credit card numbers, and JSON payloads inside V$SQL.SQL_TEXT. Passing unmasked SQL text into an external LLM API and posting the resulting RCA to a shared Slack channel creates an immediate compliance breach during an outage.
3. Sev-1 CPU and I/O amplification. When a database is already at 95% CPU or saturated on db file sequential read, an unbounded diagnostic query running in parallel (DOP > 1) competes directly with foreground OLTP sessions. Without database-tier caps (utilization_limit => 5, parallel_degree_limit_p1 => 1, switch_time_in_call => 10), the triage agent worsens the outage it was paged to explain.
4. Tool-call budget and alert-storm arithmetic. Consider a 4-minute (240-second) triage SLA. With MAX_TOOL_CALLS = 8 and MCP_TOOL_TIMEOUT_SECONDS = 10, worst-case database execution takes 8 * 10 = 80 seconds, leaving 160 seconds for LLM reasoning and Slack delivery. Without deduplication during a fleet-wide slowdown, 200 simultaneous alerts spawn 200 * 8 = 1,600 concurrent tool calls, saturating both LLM API rate limits and Slack’s 1-message-per-second channel posting limit.
How do you autonomously correlate Oracle ASH/AWR telemetry into a Slack RCA in under 4 minutes while guaranteeing zero raw PII leakage, a hard 5% database CPU ceiling, and bounded agent tool calls?
Options Considered
| Option | First-RCA Latency | PII Control | DB Load Risk | Why Chosen or Rejected |
|---|---|---|---|---|
| Senior DBA manual AWR review | 15–25 minutes | High (human discretion) | Low | Baseline — bottlenecked by login, report generation, and scrolling |
| Static threshold alerts only | <1 minute | None | None | Rejected — reports symptom (p99 > 500ms), not SQL ID or invisible index |
| Raw SQL LLM agent | 2–4 minutes | Low — logs raw SQL literals | High — unindexed DBA_HIST_* scans | Rejected — join hallucinations and compliance exposure |
| Curated MCP triage agent | 1–4 minutes | High — regex + literal masking | Capped (5% CPU, DOP=1, 10s) | Chosen — deterministic SQL, masked literals, 8-call ceiling |
Static threshold alerts fire fast but leave the engineer staring at an empty dashboard during a lock chain or plan flip. Giving an LLM a generic run_select() tool solves correlation speed at unacceptable risk: V$SQL_PLAN requires (SQL_ID, PLAN_HASH_VALUE, CHILD_NUMBER), DBA_HIST_* scans can stall production, and raw SQL_TEXT leaks customer literals. A curated MCP triage loop keeps the LLM’s pattern recognition while locking SQL execution, PII redaction, and Resource Manager caps inside DBA-controlled code.
The Autonomous Oracle Triage Agent Architecture
The architecture inserts a stateless Python triage orchestrator between the alert webhook and Slack. The orchestrator deduplicates incoming alerts per db_unique_name, runs a bounded MAX_TOOL_CALLS = 8 loop against a curated Diagnostic MCP Server, and forces a confidence-tagged RCA synthesis if the budget is reached.
flowchart TD
A[Monitoring Alert — OEM or Datadog webhook] --> B[Alert Deduplicator — 1 active session per DB]
B --> C[Triage Orchestrator — max 8 tool calls]
C --> D[LLM Reasoning Engine — Anthropic Messages API]
D -->|get_top_waits or get_top_sql| E[Diagnostic MCP Server — PII sanitizer]
E -->|bind SQL| F[Oracle DB — utilization_limit 5pct and DOP 1]
F -->|max 25 rows| E
E -->|masked markdown| D
D -->|confidence-tagged RCA| G[SQS or PubSub Queue — 1 msg per sec]
G --> H[Slack Incident Channel — human verifies DDL]
Alert ingestion and bounded 8-call triage loop. The orchestrator normalizes webhook payloads into a TriageRequest and instructs the model to start with get_top_waits(minutes_back=15), follow only wait classes consuming >15% of DB Time, and stop once three pieces of evidence align:
from dataclasses import dataclass
from datetime import datetime
import json
import os
import anthropic
MAX_TOOL_CALLS = 8
MCP_TOOL_TIMEOUT_SECONDS = 10
TRIAGE_MODEL = os.environ.get("TRIAGE_MODEL", "claude-sonnet-4-5")
@dataclass
class TriageRequest:
db_unique_name: str
alert_type: str
severity: int
triggered_at: datetime
context: dict
async def run_triage_session(request: TriageRequest, mcp_session) -> str:
client = anthropic.AsyncAnthropic()
system_prompt = (
f"You are an Oracle read-only triage agent for {request.db_unique_name} (Sev-{request.severity}).\n"
"1. Always call get_top_waits(minutes_back=15) first.\n"
"2. Investigate only wait classes >15% of DB Time.\n"
"3. Stop after 3 corroborating pieces of evidence (max 8 tool calls).\n"
"Output: **Confidence:** [HIGH|MEDIUM|LOW], **Symptom:**, **Root Cause:**, "
"**Offending Object:**, **Recommended Action:** (human-verified)."
)
messages = [{
"role": "user",
"content": f"Alert {request.alert_type} on {request.db_unique_name}: {json.dumps(request.context)}",
}]
calls = 0
while calls < MAX_TOOL_CALLS:
resp = await client.messages.create(
model=TRIAGE_MODEL, max_tokens=1500, system=system_prompt,
tools=mcp_session.get_tool_definitions(), messages=messages,
)
if resp.stop_reason == "end_turn":
return extract_text(resp.content)
tool_results = []
for block in resp.content:
if block.type == "tool_use":
calls += 1
out = await mcp_session.execute_tool(block.name, block.input, timeout=MCP_TOOL_TIMEOUT_SECONDS)
tool_results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})
messages.extend([{"role": "assistant", "content": resp.content}, {"role": "user", "content": tool_results}])
return await force_synthesis(client, system_prompt, messages)
PII masking inside the MCP server. Before any V$SQL.SQL_TEXT preview leaves the MCP server, mask_sql_pii() scrubs SSNs, emails, credit card numbers, phone numbers, and any remaining single-quoted string literal of 4 or more characters (replacing them with :literal_masked). Over-masking non-sensitive constants is an intentional tradeoff to eliminate false negatives on embedded JSON or custom identifiers:
import re
PII_PATTERNS = [
(re.compile(r"\b\d{3}-?\d{2}-?\d{4}\b"), ":ssn_masked"),
(re.compile(r"'[^']*@[^']*\.[^']{2,4}'"), "':email_masked'"),
(re.compile(r"\b(?:\d{4}[\s-]?){3}\d{4}\b"), ":ccn_masked"),
(re.compile(r"\b(?:\+?1[-.]?)?\(?\d{3}\)?[-.]?\d{3}[-.]?\d{4}\b"), ":phone_masked"),
(re.compile(r"'[^']{4,}'"), "':literal_masked'"),
]
def mask_sql_pii(sql_text: str) -> str:
for pattern, repl in PII_PATTERNS:
sql_text = pattern.sub(repl, sql_text)
return sql_text
Real-time V$SQL and DBA_INDEXES tools. When get_top_sql_by_elapsed runs, it queries V$SQL directly (avoiding hourly AWR snapshot lag) with last_active_time > SYSDATE - :mb/1440, truncates SQL_TEXT to 120 characters, and masks every row before formatting markdown. When a plan shows TABLE ACCESS FULL, get_index_visibility_status checks DBA_INDEXES (VISIBILITY, STATUS, LAST_ANALYZED) to catch accidental INVISIBLE indexes immediately. A companion get_execution_plan(sql_id, child_number) tool queries V$SQL_PLAN using the composite (SQL_ID, CHILD_NUMBER) key so the agent never guesses join columns or triggers cross-child row multiplication, and highlights TABLE ACCESS FULL operations whose COST or CARDINALITY exceeds 100,000 rows.
Alert deduplication, forced synthesis, and queued Slack delivery. During a shared-storage or network brownout, monitoring webhooks frequently fire for 50 to 200 databases within the same 30-second window. The orchestrator maintains a Redis or PostgreSQL lease keyed by db_unique_name with a 5-minute TTL: if a triage session is already active for that database, duplicate webhooks append their alert metadata to the active audit record without spawning a second LLM loop. If the active loop reaches MAX_TOOL_CALLS = 8 without emitting end_turn, force_synthesis() strips tools from the final messages.create() call and instructs the model to summarize only the evidence already gathered, tagging **Confidence:** LOW if fewer than two corroborating signals were found. Completed RCAs are enqueued onto SQS or Pub/Sub and drained by a worker paced at 1 message per second per Slack channel so bursts never hit Slack HTTP 429 throttling, while every tool name, clamped argument, and masked result is written to an immutable audit log for post-incident review.
Database-tier Resource Manager protection. Inside a Resource Manager pending area, the triage consumer group (MCP_TRIAGE_GROUP) uses utilization_limit => 5 (replacing the 11g-deprecated max_utilization_limit), parallel_degree_limit_p1 => 1, and switch_time_in_call => 10 with switch_group => 'CANCEL_SQL':
BEGIN
DBMS_RESOURCE_MANAGER.CLEAR_PENDING_AREA;
DBMS_RESOURCE_MANAGER.CREATE_PENDING_AREA;
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(
plan => 'ORACLE_TRIAGE_PLAN',
group_or_subplan => 'MCP_TRIAGE_GROUP',
comment => 'Cap triage agent CPU, DOP, and per-call runtime',
utilization_limit => 5,
parallel_degree_limit_p1 => 1,
switch_group => 'CANCEL_SQL',
switch_time_in_call => 10
);
DBMS_RESOURCE_MANAGER.VALIDATE_PENDING_AREA;
DBMS_RESOURCE_MANAGER.SUBMIT_PENDING_AREA;
END;
/
For severe instance hangs where normal CREATE SESSION connections block on latches or processes, human DBAs fall back to sqlplus -prelim / as sysdba to capture hang-analysis dumps, rather than relying on the MCP pool.
How It Rolls Out
Autonomous triage rolls out through four gated phases so PII redaction and CPU caps are proven before any RCA reaches a live incident channel.
Phase 1: Synthetic PII Redaction Audit. Replay captured V$SQL.SQL_TEXT samples containing embedded SSNs, emails, phone numbers, and JSON payloads through mask_sql_pii(). Gate: 0 unmasked PII tokens in unit and integration test outputs. Rollback: tighten the catch-all literal regex before enabling live database connections.
Phase 2: Resource Plan Chaos Verification. Run a staging CPU-saturation load test while firing concurrent get_top_waits and get_top_sql_by_elapsed calls under MCP_TRIAGE_GROUP. Gate: DBA_RSRC_PLAN_DIRECTIVES confirms UTILIZATION_LIMIT = 5, PARALLEL_DEGREE_LIMIT_P1 = 1, and a synthetic slow call cancels at 10 seconds via CANCEL_SQL. Rollback: disable MCP_TRIAGE_USER session privileges if foreground latency degrades.
Phase 3: Shadow-Mode RCA Scoring. Route live OEM/Datadog webhooks to the orchestrator, but publish RCAs only to a private #db-triage-shadow Slack channel. Compare agent RCAs against senior DBA post-incident findings over two weeks. Gate: >=85% root-cause agreement on lock, I/O, and index-visibility incidents, with LOW confidence correctly flagged on ambiguous cases. Rollback: tune the system prompt or expand missing MCP tools before promoting.
Phase 4: Live Incident Channel Enrichment. Enable posting to #inc-* channels behind an SQS/PubSub rate-limiting queue (1 message/second/channel) with strict 1-session-per-db_unique_name deduplication. Every Slack post includes the exact SQL_ID, offending wait event, tool-call count, and elapsed triage time alongside a reminder that the agent is strictly read-only advisory—any remediation such as ALTER INDEX ... VISIBLE or ALTER SYSTEM KILL SESSION requires explicit human verification by the on-call DBA. Keep all remediation human-executed. Rollback: disable the webhook subscription; existing PagerDuty/OEM paging continues unchanged.
For severe instance hangs where normal CREATE SESSION connections block on latches or SESSIONS exhaustion, the MCP server cannot acquire a pooled connection within 10 seconds. In that scenario, the orchestrator posts a DB unreachable — check hang dump notice to Slack so the on-call DBA immediately connects via sqlplus -prelim / as sysdba to capture process-state and hang-analysis dumps rather than waiting on timed-out MCP retries.
In Practice
- ASH 1-second vs. AWR 10-second sampling (Pattern A): Per Oracle Database Concepts and
V$ACTIVE_SESSION_HISTORYreference, ASH captures active session samples every 1 second in SGA, while AWR flushes 1 in 10 samples toDBA_HIST_ACTIVE_SESS_HISTORYat hourly snapshot boundaries. Triage tools targeting active incidents must readV$ACTIVE_SESSION_HISTORYandV$SQLfirst, falling back toDBA_HIST_*only with explicitSAMPLE_TIMEbounds. - Resource Manager
UTILIZATION_LIMITandSWITCH_TIME_IN_CALL(Pattern A): Per Oracle’sDBMS_RESOURCE_MANAGERreference,UTILIZATION_LIMITenforces a hard CPU ceiling even when other consumer groups are idle,PARALLEL_DEGREE_LIMIT_P1 => 1prevents parallel query I/O amplification, andSWITCH_TIME_IN_CALLbounds single-call duration on pooled connections. - MCP Resources for full AWR reports (Pattern A): Under the MCP 2025-03-26 specification, exposing the latest AWR text report as an MCP Resource (
oracle://PROD-DB/awr/latest) lets an interactive DBA assistant inspect holistic AWR sections on demand, complementing the 8-call automated Sev-1 loop. - Cloud-managed vs. self-managed scope (Pattern B): Managed OCI services (Autonomous AI Database, Performance Hub, and Operations Insights AWR Hub) provide built-in Compare Period ADDM and fleet SQL Warehouse analytics; the custom MCP triage orchestrator fills the gap for self-managed Oracle fleets on VMs, EC2, or on-premises hardware.
Where It Breaks
| Failure Mode | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Rabbit-hole wait fixation | Agent spends 6 of 8 calls on an 8% wait, missing a 65% TX lock | Incomplete RCA hits forced synthesis at call 8 | Mandate >15% DB Time threshold and top-wait-first order in prompt |
| Novel SQL literal PII leak | Embedded JSON string bypasses narrow SSN/email regex | DLP scan or human review spots raw literal in Slack | Mask all single-quoted literals >=4 chars before returning to LLM |
| 200-alert fleet storm | Mass slowdown spawns 200 concurrent LLM + Slack calls, hitting 429s | Anthropic/Slack HTTP 429 metrics spike | Deduplicate 1 active session per db_unique_name; queue Slack at 1 msg/sec |
| Confabulated root cause | Ambiguous telemetry produces confident wrong remediation | Shadow-mode audit or wrong-session kill | Prefix every RCA with Confidence: HIGH/MEDIUM/LOW; escalate LOW |
| Severe DB hang blocks sessions | CPU/latch exhaustion stalls even 10s MCP queries | MCP_TOOL_TIMEOUT fires across all tools | Report DB unreachable to Slack; DBA uses sqlplus -prelim / as sysdba |
| First-hour AWR snapshot gap | Incident fires before hourly AWR flush; DBA_HIST_* returns 0 rows | Empty tool output on historical SQL lookup | Query V$SQL and V$ACTIVE_SESSION_HISTORY first for recent windows |
Key Takeaways
- Bound the agent before it touches production: An 8-call limit,
>15%DB Time focus rule, and forced synthesis guarantee an RCA within the 4-minute triage window without runaway loops. - Mask SQL literals in the MCP server, never in the prompt: Scrubbing SSNs, emails, card numbers, and long string literals in Python before the LLM sees
V$SQL.SQL_TEXTprevents PII from entering model logs or Slack. - Use current
DBMS_RESOURCE_MANAGERdirectives: Enforceutilization_limit => 5,parallel_degree_limit_p1 => 1, andswitch_time_in_call => 10withCANCEL_SQLinside a pending area so triage queries cannot amplify a Sev-1 outage. - Read
V$ASHandV$SQLfor live incidents, notDBA_HIST_*: Real-time SGA views have 1-second resolution and avoid hourly AWR snapshot lag. - Keep autonomous triage strictly read-only advisory: Tag every Slack RCA with a
Confidencelevel and require human DBA verification before anyALTER INDEXorKILL SESSIONaction.
What to Do Next
- Problem: Manual AWR correlation delays Sev-1 root-cause identification by 15–25 minutes, while unconstrained LLM SQL access risks PII leaks and database load amplification.
- Solution: Deploy a deduplicated, 8-call-bounded triage orchestrator over a PII-masking Diagnostic MCP Server governed by a 5% CPU,
DOP=1, 10-secondSWITCH_TIME_IN_CALLOracle Resource Manager plan. - Proof: Verify
mask_sql_pii()redacts synthetic literals in tests, confirmDBA_RSRC_PLAN_DIRECTIVESenforcesUTILIZATION_LIMIT = 5, and score shadow-mode RCAs against human post-mortems for two weeks. - Action: Export a recent 30-minute AWR/ASH summary from a non-production database, run it through your
mask_sql_pii()filter, and benchmark how accurately an 8-call prompt identifies the top wait and offendingSQL_ID.
Sources
- Oracle Database Concepts — Active Session History and AWR Architecture: https://docs.oracle.com/en/database/oracle/oracle-database/19/cncpt/memory-architecture.html
- Oracle Database PL/SQL Packages —
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE: https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_RESOURCE_MANAGER.html - Oracle Database Reference —
V$ACTIVE_SESSION_HISTORY: https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/V-ACTIVE_SESSION_HISTORY.html - Anthropic Documentation — Tool Use and Messages API: https://docs.anthropic.com/en/docs/tool-use
- Model Context Protocol Specification (2025-03-26) — Tools and Resources: https://spec.modelcontextprotocol.io/specification/2025-03-26/
- Oracle Database 26ai Performance Tuning / Operations Insights & Performance Hub: https://docs.oracle.com/en/database/oracle/oracle-database/26/tdppt/
Interactive tools for this topic