AI SQL Sentinel: A Database Performance Monitoring Tool Built on Operational Knowledge
From the publisher’s feed, collected in the ZeroLabs newsroom.
Most database monitoring tools tell you something is wrong. The harder problem is explaining what is wrong, why it happened, and what to do about it — quickly enough to matter.AI SQL Sentinel is a performance monitoring system for SQL Server and PostgreSQL that automates that diagnostic step. It collects live database evidence, identifies known failure patterns, retrieves matching expert guidance, and produces a structured diagnosis with a root cause, a confidence score, and executable resolution steps. The investigation that would otherwise take 20 to 40 minutes of manual querying happens in under a minute.This article describes what the tool does, how it is structured, and the design decisions behind it.What It ProducesBefore describing the architecture, here is the actual output from a live run against a CDC log pressure incident:Type: cdc_log_pressure Job: CDC_LOG_SCANRoot Cause: CDC scan session stuck for 420s with 0 commands processed. Transaction log held open — WRITELOG cascading to all concurrent DML.Confidence: 87%Evidence: • scan_status=STUCK_ACTIVE, duration=420s, command_count=0 • avg_write_ms=18.3 on OpsInsights (threshold: 5ms) • WRITELOG waits on 4 concurrent sessions during job windowRecommended Actions: 1. EXEC sys.sp_cdc_stop_job 'capture'; EXEC sys.sp_cdc_start_job 'capture'; 2. Tune sp_cdc_change_job @maxtrans=2000, @maxscans=20 3. Verify log disk throughput — avg_write_ms > 10ms indicates disk saturationRecurring: seen 3 times in last 30 days | Blocking co-fired 2 of 3 timesRoot cause is evidence-based, not generic. Confidence reflects actual certainty. Evidence cites measured values from the database. Recommended actions are specific, executable SQL. The recurring pattern and co-occurrence note come from stored incident history, not from inference.Why Traditional Monitoring Wasn’t EnoughTraditional monitoring platforms excel at collecting metrics and generating alerts. They are intentionally conservative about drawing conclusions because diagnosing root cause requires context, history, and operational judgment that a generic alerting system cannot reliably supply.The result is a consistent pattern: the alert fires, a DBA connects, and the manual investigation begins — checking wait stats, examining blocking chains, reviewing execution plans, correlating timing across subsystems. The monitoring tool told you something was wrong. It did not tell you why. That investigation takes 20 to 40 minutes for a familiar failure pattern and longer for anything unusual.AI SQL Sentinel focuses on that diagnostic layer. Rather than asking an operator to manually correlate evidence, it attempts to assemble the evidence, retrieve relevant operational knowledge, and produce a structured diagnosis before a human begins the investigation. The monitoring alert becomes the starting point of a resolved incident rather than the starting point of a manual search.The distinction is not that traditional tools are inadequate — it is that they were designed for a different job. Metric collection and alerting are solved problems. Automated diagnosis from live evidence is not.How It Works — Six StagesEvery run works through the same six stages in sequence, fully automatic.Database Evidence → Expert Reasoning → Actionable Diagnosis1 · Collect — Gathers evidence without touching the monitored database.2 · Detect — Identifies which failure patterns are active.3 · Suppress — Filters noise before any AI call is made.4 · Retrieve — Finds the most relevant expert guide from the knowledge base.5 · Explain — Combines the evidence and guide into a structured diagnosis.6 · Learn — Stores the outcome so future incidents on the same target have more context.Architecture: Three Databases, Two ProcessesThe system uses three distinct database connections, each with a different role.Monitored SQL Server — evidence source only. The tool reads sys.dm_exec_requests, ring buffers, Query Store, job history from msdb, and related system views. It never writes to the monitored server. The login requires VIEW SERVER STATE and SQLAgentReaderRole in msdb — no elevated permissions, no schema changes.Monitored PostgreSQL — evidence source only, read via pg_monitor role. The tool reads pg_stat_activity, pg_stat_bgwriter, pg_replication_slots, pg_class, and related catalog views.PostgreSQL repository on Neon — the only database the tool writes to. All persistent storage lives here: incidents, alert quality records, job history ingested from SQL Server, 5-minute snapshots, and the runbook knowledge base with vector embeddings.Two processes run on a schedule:collect_snapshots.py runs every five minutes. It photographs the current state of the monitored database — blocking chains, deadlock events, memory queues, CPU ring buffer, CDC scan state, replication lag — and writes everything to the Neon repository. This enables historical replay and pattern learning.detect_issues.py runs on demand or on a schedule. It reads those snapshots or queries live views directly, runs all detectors, calls the AI model, and stores validated diagnoses. It can run against today's live data or replay any historical date using the --date flag.The Detection Layer: 25 Failure PatternsEvery detector query fires only when a threshold is crossed. Zero rows returned means nothing to investigate. The AI is never called on normal activity.SQL Server — 13 detectorsJob baseline comparison checks each job’s last 24 hours against its 30-day P50 median. It requires at least 10 baseline runs for statistical stability and fires when a job runs more than twice its normal time.Job trend detection uses linear regression on 14 days of run history to surface slow-burn deterioration before it crosses the 2× threshold. It fires when the trend is clearly upward but the job has not yet doubled — an early warning that arrives 2 to 5 days before the condition becomes an incident.Live blocking checks for active lock waits and blocked sessions in the current DMV snapshot.Deadlock detection parses the SQL Server system health extended events ring buffer for deadlock events in the last two hours. The ring buffer holds approximately 256 events and resets on server restart. The snapshot table in the repository provides durable storage that survives restarts.Memory pressure fires when sessions are queuing for memory grants (RESOURCE_SEMAPHORE wait type) or server RAM exceeds 92%.CPU pressure fires when average SQL Server CPU exceeds 80% across ring buffer samples. The AI prompt contains an explicit diagnostic rule for this: low CPU time combined with high elapsed time is memory starvation, not CPU saturation — a distinction that changes the fix path entirely.CDC log scan pressure checks CDC scan sessions for the stuck state — open more than five minutes with zero commands processed. Also monitors log write latency above 5ms. Completely silent on instances without CDC enabled.Long-running execution with severity scoring scores each active session on 11 compounding signals: elapsed time, being blocked by another session, blocking other sessions, holding an open transaction, critical wait types, high logical reads, write pressure, and CPU time. A backup running alone scores 1 and is ignored. A session running 87 minutes while blocking three others and holding an open transaction scores 9 and fires immediately. Multiple concurrent risk signals are required before a high-severity alert fires.Query intelligence watches for seven structural query problems: missing indexes with cardinality analysis, plan instability across Query Store executions, top resource-consuming queries by logical reads, unused high-cost indexes on write-heavy tables, stale statistics, implicit type conversions forcing table scans, and sampled statistics quality anomalies. The last signal fires when statistics were recently updated but the sample rate was too low to accurately represent the value distribution — auto-update alone does not fix it, and the resolution path differs from stale statistics.tempdb pressure watches four distinct failure modes: session spills over 500MB, version store growth over 10GB, allocation page contention from too few tempdb data files, and file capacity approaching 85%. Each has a different fix. All four cause every query to slow simultaneously with moderate CPU and no blocking — a signature that no other detector catches.Storage I/O saturation fires when data file read or write stall exceeds 20ms per IO, or when five or more sessions are waiting for pages to load from disk simultaneously.Hot page latch contention fires when three or more threads compete simultaneously for an exclusive in-memory page latch on the same user database B-tree page — the pattern caused by clustered indexes with sequentially increasing keys. The fix is at the schema level.Worker thread starvation requires two signals simultaneously: live tasks queued with no worker thread assigned, and non-zero work queue counts on online schedulers. Neither alone is sufficient. Both together confirms the server is failing to hand out workers — new requests queue, SQL Agent jobs fail to start, logins may time out. This condition can develop and cause an outage in 60 to 90 seconds. A session-duration detector with a 30-minute threshold would never catch it.PostgreSQL — 12 detectorsThe PostgreSQL path covers blocking via pg_blocking_pids(), deadlocks, memory pressure via bgwriter statistics, CPU via active session patterns, WAL replication lag including inactive slots retaining WAL on disk, long-running sessions, query performance via pg_stat_statements, I/O pressure via cache miss rate, table bloat from dead tuple accumulation, vacuum lag and XID wraparound risk, and a three-signal visibility horizon blocker for stale replication slot xmin, forgotten prepared transactions, and MultiXact ID exhaustion.Suppression: Keeping the Signal CleanFour rules run before the AI is called, ensuring the AI only runs on issues that are real, new, and worth investigating.Maintenance window — if a configured maintenance window is active, non-critical alerts are suppressed silently. The window is set in the environment file and supports midnight-crossing ranges.Known workload exceptions — jobs listed as expected-slow are permanently skipped. Nightly index rebuilds, end-of-month archival jobs, and similar predictable long-running work do not generate alerts.Duplicate Alert Prevention— if the same issue type fired for the same job in the last four hours, it is suppressed. The same active problem does not flood the team.Severity threshold — for the long-running session detector, only sessions scoring 3 or above proceed. Low-scoring sessions are logged to the alert quality table but do not reach the AI.Eight issue types bypass all four rules regardless: deadlocks, memory pressure, CPU pressure, tempdb pressure, I/O saturation, hot page latch contention, worker thread starvation, and the PostgreSQL visibility horizon blocker. Active failure conditions that can cause immediate data loss or outage are never suppressed.Every suppression decision is written to the alert quality table with its reason. The team can always query what was seen, what score it received, and why it was held back.Runbook Retrieval: Finding the Right Expert GuideBefore the AI sees any evidence, it retrieves the most relevant troubleshooting guide from the knowledge base. The retrieval uses two gates.Hard category filter first. Each detector produces a fixed issue type string that maps to a runbook category. A SQL query restricts the search to only that category. A tempdb runbook cannot compete against a blocking runbook regardless of vocabulary. The category is determined by the detector, not by text similarity.Semantic similarity search second. Within the filtered category, the issue description is encoded into a 384-dimensional vector using all-MiniLM-L6-v2 and compared against pre-computed runbook embeddings using cosine distance via pgvector. Results below a 0.40 similarity score are dropped — an irrelevant runbook is worse than no runbook.The knowledge base contains 37 runbooks — 27 for SQL Server, 10 for PostgreSQL. Each contains four sections: a signal fingerprint written to match the vocabulary the detector produces, ranked root cause paths ordered by likelihood, investigation and resolution steps from least invasive to most disruptive, and an explicit section on what not to do. The wrong-path section exists because an AI model given plausible evidence will sometimes recommend the wrong fix confidently. Encoding the wrong answers prevents that.The runbooks cover every detector type — job slowdown triage, blocking and lock contention, uncommitted transaction blocking, ETL and read contention, all seven query intelligence signals, hot page latch contention, storage I/O saturation, worker thread starvation, plan regression, parameter sniffing, deadlock resolution, memory grant pressure, CPU saturation, CDC log scan lag, long-running session triage, tempdb pressure, and the full PostgreSQL coverage including visibility horizon blockers, table bloat, vacuum lag, WAL replication lag, memory and CPU pressure, query intelligence, I/O saturation, and temporary space pressure.The AI Prompt: Nine SectionsThe prompt the AI receives is assembled from nine sections, each with a specific job.Section 1 assigns the engine-specific persona — SQL Server DBA or PostgreSQL DBA. The PostgreSQL persona contains an explicit prohibition against suggesting SQL Server tools. Without this, the model will occasionally suggest SQL Server-specific commands for PostgreSQL incidents.Section 2 provides a ten-step reasoning framework the AI must work through in sequence: what changed, is blocking present and when did it start, is memory or CPU the constraint, is CDC holding the log, is another database consuming disproportionate resources, is a plan regression visible, is the pattern time-of-day related, what is the safest first action.Section 3 provides the incident summary — issue type, job name, current and baseline values.Section 4 handles temporal validation. Suspected causes must have occurred during the incident window. This prevents a specific wrong diagnosis: a job ran slow, a blocking chain appeared in a snapshot taken after the job completed, and the AI attributes the slowdown to that blocking. With the temporal rule, the AI identifies it as coincident, not causal.Section 5 provides query regression detail from Query Store when available — plan IDs before and after, plan count, execution counts.Section 6 provides blocking evidence sanitised and capped at eight sessions, with cross-database blocking explicitly flagged.Section 7 provides resource pressure evidence formatted specifically for the issue type that fired. The format for a tempdb incident differs from the format for a memory pressure incident.Section 8 provides server-level context — which database is consuming the most CPU, reads, and log write latency, with the monitored job’s database marked.Section 9 injects the retrieved runbook with its similarity score visible to the model. The score signals how heavily to weight the retrieved guidance versus the model’s own evidence reasoning.Historical patterns from stored incidents are also included: whether this issue has recurred in the last 30 days, whether it follows a time-of-day pattern, and which other issue types have co-fired alongside it in past incidents. If blocking has co-fired with deadlocks in 80% of past incidents on this target, the AI is told explicitly and this is treated as a strong signal when forming the root cause.The output is structured JSON — root cause, confidence score as a float between 0 and 1, evidence array citing observed values only, and ranked recommended actions. Schema validation runs before anything is stored. Malformed responses produce a safe fallback rather than a lost incident.SecuritySanitisation is hardcoded on and cannot be disabled. Login names are hashed with SHA-256. Hostnames are replaced entirely. SQL text is truncated at the database level before it leaves the server — enough to identify the operation, not enough to expose literal values from WHERE clauses. Deadlock query text is capped at 80 characters.Five authentication modes are supported for SQL Server: standard SQL login, Windows integrated authentication, Azure Managed Identity, Azure AD password, and Kerberos. In cloud and domain-joined environments the SQL login credential can be eliminated entirely.The monitored SQL Server login requires VIEW SERVER STATE and SQLAgentReaderRole in msdb. No sysadmin. No write access. No schema creation on monitored systems.Alert Quality MeasurementThe system measures its own quality. The alert quality table records every firing decision and every suppression with its reason. Operators can label incidents as true positive, false positive, or noise using a CLI command.python detect_issues.py --quality-reportThe report shows suppression rate, mean AI confidence per issue type, detector activity over the selected period, repeat offenders, and precision once enough operator feedback has been recorded.Current StateThe system has been validated against reproduced failure scenarios — real patterns recreated using sample databases in a controlled environment. It has not yet been deployed against a live production database.What has been built: 25 detectors, 37 runbooks, 532 unit tests requiring zero database connections, read-only access throughout, no agents, no writes to monitored systems, configurable AI provider (Anthropic Claude or OpenAI, switched via a single environment variable).What comes next: a production pilot to measure detection accuracy and diagnostic quality against real workloads, and integration with Slack and email notification so incidents reach the team without requiring manual polling.Limitations and Open QuestionsThe system has been validated against reproduced failure scenarios, but several areas remain intentionally unmeasured until a production pilot is completed.False positive rate is not yet available because no production incident data exists. The alert quality framework and operator feedback workflow have been implemented to measure this during the pilot.Runbook retrieval accuracy has been validated during development through category-gated retrieval and similarity thresholds, but has not yet been benchmarked against a representative production dataset.Runbook maintenance and drift remain a human-reviewed process. Incident history and AI diagnoses are retained to support future refinement, but no automated drift detection currently exists.Detector maintenance is intentionally lightweight, with thresholds externalised from detection logic, though future platform and DMV changes may require periodic updates.AI and runbook disagreements are preserved for review rather than automatically overridden. The runbook serves as guidance, while the final diagnosis remains evidence-driven.The production pilot will focus on answering these questions with real operational data.The tool does one thing: when a database issue occurs, it produces a diagnosis — root cause, evidence, confidence, and specific actions — before a DBA has had time to open a query window. How much of the subsequent investigation that eliminates depends on what the pilot reveals.Technical reference: the complete detector query documentation, DMV and system view matrix, prompt structure, JSON output schema, and runbook content are documented separately in the project repository.AI SQL Sentinel: A Database Performance Monitoring Tool Built on Operational Knowledge was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.