# Culprit SQL: full documentation
Source: https://github.com/culpritsql/culprit-sql-studio · Website: https://culpritsql.com
---
Culprit SQL Studio
Find database bottlenecks, with the evidence to fix them.
A desktop app and CLI for database performance analysis on macOS, Linux and Windows.
Download ·
Quick start ·
Features ·
Providers ·
Collector & Fleet ·
Agents & CI ·
Guide
culpritsql.com ·
Live Fleet Demo ·
Live Plan & .xel Analyzer
English ·
简体中文 ·
日本語 ·
한국어 ·
Русский ·
Deutsch ·
Español ·
Français ·
Português
Culprit brings query statistics, execution plans, waits and schema context into one workflow. It ranks findings by impact and connects each one to evidence, a suggested fix and verification steps. Use it from the desktop app, terminal or a coding agent.
## Get started
[Download the desktop app or standalone CLI](https://github.com/culpritsql/culprit-sql-studio/releases/latest). In the app, add a connection or open a SQLite file to see its dashboard.
From the terminal:
```sh
culprit conn add shop --env staging --url 'postgres://app@db.example.com:5432/shop'
culprit scan shop
culprit dashboard shop
```
Reopening a connection shows its saved report while a fresh scan runs in the background. The desktop app offers signed updates; update the standalone CLI with `culprit update`.
Try the interface with demo data
With [Bun](https://bun.sh) installed:
```sh
git clone https://github.com/culpritsql/culprit-sql-studio.git
cd culprit-sql-studio/app
bun install --frozen-lockfile
bun run dev
```
The browser demo uses included snapshots and needs no database connection.
## Supported databases
| Provider | Sources and capabilities |
|---|---|
| [**SQL Server / Azure SQL**](/docs/providers/mssql.md) | Query Store, plan cache, DMVs and retained deadlock events |
| [**PostgreSQL / Amazon RDS**](/docs/providers/postgres.md) | `pg_stat_statements`, catalog/statistics views, EXPLAIN and hypothetical indexes through HypoPG |
| [**TimescaleDB**](/docs/providers/timescale.md) | PostgreSQL sources plus hypertable sizes and managed/compressed chunks |
| [**YugabyteDB**](/docs/providers/yugabyte.md) | Native YSQL/DocDB counters, DIST plans, sharding and scoped activity sources |
| [**MySQL**](/docs/providers/mysql.md) | `performance_schema`, `sys`, EXPLAIN and the slow query log |
| [**MariaDB**](/docs/providers/mariadb.md) | Performance schema, slow log, user statistics, MariaDB plans and lock views |
| [**ClickHouse**](/docs/providers/clickhouse.md) | Logged initial queries (`system.query_log`), MergeTree parts/merges, mutations, replication and `EXPLAIN PLAN` |
| [**SQLite**](/docs/providers/sqlite.md) | Read-only file inspection, `EXPLAIN QUERY PLAN` and framework query logs |
Features depend on the engine, enabled sources and your login’s permissions. Missing sources appear with a reason and setup guidance. See [Engine parity](/docs/parity.md) for the feature comparison and verified versions.
## What you get
### Findings with evidence, fixes and verification
Each finding identifies the affected queries, the measurement window and the evidence behind its severity. Open it for a suggested change, SQL to copy when applicable, verification steps and a brief to share with a teammate or coding agent.
| Area | Examples of what Culprit checks |
|---|---|
| Query performance | Expensive joins, plan regressions, parameter-sensitive plans, index-blocking type conversions, N+1 patterns, failures, timeouts and spills |
| Indexes and schema | Missing, unused, duplicate and overlapping indexes; unindexed foreign keys; partition hazards |
| Maintenance and capacity | Stale statistics, dead tuples, table bloat, large rows, sequence exhaustion and transaction-ID wraparound risk |
| Database health | Hot rows, table-lock escalation, storage latency, page checksum corruption, connection churn, replication lag and settings |
For example, the SQL Server demo includes a plan making **1.5 billion row comparisons**. The affected query accounts for **27% of database time** over five hours. Culprit identifies its forced loop-join hint, suggests removing it, and gives steps to compare the new plan and verify the result.
Run `culprit checks` for the complete check list and required capabilities.
### Execution plans and runtime evidence
Explore plans as a diagram, an indented tree or an operations table. Insights explain expensive lookups, row-estimate errors, inefficient joins, spills, conversions, memory grants and parallelism, with links to the relevant operators.
Inspect estimated and actual rows, operator properties and raw XML or JSON. Measure supported read statements explicitly. On SQL Server, inspect the retained last actual plan without re-running a query, or watch a running query’s operator progress when that evidence is available.
### What changed after a deploy
Drag across the database-time chart to compare two periods: queries that got slower, new queries, improvements and statements that stopped running. See plan switches, schema or setting changes, restarts and deploy marks alongside those changes.
Cloud metrics add context such as Amazon RDS CPU credits, I/O limits and Azure tier limits, using your existing `aws` or `az` sign-in.
### Compare and share plans
Paste, drop or open a plan or event capture from another tool—or inspect it in the browser at [explain.culpritsql.com](https://explain.culpritsql.com): SQL Server `.sqlplan` and `.xel`, PostgreSQL EXPLAIN text or JSON, YugabyteDB DIST output, MySQL/MariaDB plans or ClickHouse `EXPLAIN PLAN json=1`. Compare two versions with synchronized diagrams and highlighted changes in operators, access paths, row estimates and cost.
Comparisons also explain differences in captured parameters, statistics, parallelism and memory where the plans retain them. Share findings and plans as Markdown, a self-contained HTML page or a native plan file, with literal-value redaction enabled by default.
### Live sessions, blocking and deadlocks
Follow blocking chains back to the session holding them up. Inspect waits, long-running statements and transactions left open by the application. Recorded deadlocks include the participating statements, the pattern and suggested next steps.
Live activity refreshes automatically and can be paused. On non-production connections, cancel a statement or end a session from the app or CLI.
### SQL editing and database tooling
| Feature | What it includes |
|---|---|
| **Index advisor** | Workload-based index candidates, duplicate/overlapping/unused indexes, and the write cost of keeping them |
| **SQL editor** | Persistent tabs, schema-aware completion, saved queries, estimated and measured plans, and inline migration warnings with quick fixes |
| **Migration linter** | Offline checks against saved snapshots; supported DDL rewrites for concurrent or online operations |
| **Where time goes** | Wait categories connected to queries, plus a live sample to compare with the recorded workload |
| **Health signals** | Memory, compiles, connections, row locks, per-file storage latency, replication and cloud limits |
| **Schema explorer** | Table sizes, indexes and usage; compare columns, indexes, foreign keys, triggers, constraints and partition bounds across environments, with SQL to reconcile differences |
| **Connections** | Connection strings and imports from Azure Data Studio, VS Code, DBeaver and DataGrip |
| **Discovery and SSH** | Find Azure and AWS databases with your CLI login; connect through an [SSH jump host](/docs/ssh.md) |
| **Offline reports** | Saved scans, trends, historical comparisons and shared snapshots you can inspect without a database connection |
| **Archives** | Read-only incident, time-window and execution-plan investigation over published Azure Data Explorer (ADX) and ClickHouse telemetry warehouses |
| **Keyboard navigation** | A command palette (⌘K / Ctrl+K), view shortcuts, query tabs and actions |
| **Languages** | English, Simplified Chinese (简体中文), Japanese (日本語), Korean (한국어), Russian (Русский), German (Deutsch), Spanish (Español), French (Français) and Portuguese (Português) |
## Collector and Culprit Fleet
Run `culprit collect` as a bounded, read-only background collector to monitor databases continuously without connecting interactive users or agents to production. The collector writes sealed captures to a durable local outbox, backs up raw evidence in private **Azure Blob Storage** or **Amazon S3**, runs Culprit's pure diagnostic engine locally, and publishes incidents (`CulpritIncidentsV1`), findings (`CulpritFindingsV1`), schema/setting changes (`CulpritChangesV1`) and 13 raw evidence tables to **Azure Data Explorer (ADX)** or **ClickHouse**.
### 1. Capture locally or generate warehouse DDL
```sh
# Capture a bounded snapshot into a local outbox (no warehouse required)
culprit collect outbox init ./outbox
culprit collect once shop --collection activity --outbox ./outbox
# Or generate warehouse table and helper-view DDL directly from the container image
docker run --rm ghcr.io/culpritsql/culprit-collector:v0.6.4 \
collect schema --store clickhouse --format sql > clickhouse-schema.sql
```
### 2. Deploy a hardened collector shard on Kubernetes
Multi-arch images (`linux/amd64` and `linux/arm64`) ship at `ghcr.io/culpritsql/culprit-collector`, paired with an OCI Helm chart that defaults to zero replicas, enforces single-writer `StatefulSet` ownership (`65532:65532`, read-only root filesystem) and separates source, recovery and warehouse credentials:
```sh
helm upgrade --install culprit-collector \
oci://ghcr.io/culpritsql/charts/culprit-collector \
--version 0.6.4 \
--namespace db-monitoring \
--create-namespace \
-f values.yaml
```
### 3. Investigate in Culprit Fleet, SQL Studio or CLI
Explore fleet-wide incidents, time windows, query timelines, execution plans and configuration drift directly from ADX or ClickHouse—with zero live connections to your production databases:
- **Web console:** **[fleet.culpritsql.com](https://fleet.culpritsql.com)** (or self-host **[culprit-fleet](https://github.com/culpritsql/culprit-fleet)**)
- **Desktop app:** open **Archives** in the Culprit SQL Studio sidebar
- **CLI & MCP:** `culprit resources`, `culprit window`, `culprit incident`, `culprit collect queries` (Grafana dashboards & alert rules) and `culprit mcp --warehouse-evidence`
[Collector & warehouse architecture →](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md) · [Kubernetes Helm chart →](https://github.com/culpritsql/culprit-sql-studio/blob/main/deploy/helm/culprit-collector/README.md)
## Coding agents and CI
### MCP and repository setup
The MCP server gives Claude Code, Cursor, Codex and other MCP clients access to findings, query plans, schema, migrations, blocking, waits, index advice and verification. Agents use saved connection names; credentials stay in Culprit.
```sh
claude mcp add culprit -- culprit mcp
culprit agent init --connection shop
```
The second command adds repository instructions and MCP configuration. Other clients can register `culprit` with the argument `mcp` directly. When query comments contain `file:line` references, including Marginalia and SqlCommenter annotations, finding briefs can point back to the application code.
Print a finding’s brief or test a proposed PostgreSQL index through HypoPG without creating the real index:
```sh
culprit show shop 'filtered-scan:public.orders'
culprit explain shop --sql "SELECT * FROM orders WHERE status = 'open'" \
--with-index "CREATE INDEX ON orders (status ASC)"
```
Access is set per connection: off, statistics and estimated plans (the default), or approved read-only queries. Query approval shows the exact statement; tool calls are recorded in a local audit log.
[Agent setup, permissions and audit details →](/docs/agents.md)
### Migration checks and deploy workflows
Check migration files against a saved snapshot’s table sizes, column types, indexes and recorded workload. Findings cover blocking `CREATE INDEX` and `ALTER TABLE` operations, missing or mismatched foreign-key indexes, and `DROP` or `RENAME` changes that affect recorded queries.
```sh
culprit lint-sql prod-snapshot.json --file migrations/ --fail-on high
culprit lint-sql prod-snapshot.json --file migrations/ --format sarif > culprit.sarif
```
Use `--fail-on high` to fail CI on high-severity findings. `--write` applies supported rewrites to migration files. JSON supports scripts, SARIF supports code-review tooling, and stable finding IDs let you track the same problem across scans.
After deployment, mark the timeline, verify a finding or generate a redacted summary:
```sh
culprit mark shop deploy v2.4.0
culprit verify shop 'filtered-scan:public.orders'
culprit digest shop > digest.json
```
## Production use
- **Scans read statistics and catalog views**, with provider-specific timeouts and planning guards.
- **Database fixes are suggestions** for you to review and apply.
- **Production execution requires confirmation** for statements Culprit cannot classify as reads; destructive operations require an additional confirmation.
- **Agent query access is opt-in**, with approval for each read-only statement and a local audit trail.
- **Saved passwords use the OS keychain.** Entra ID can use your Azure sign-in; shareable exports redact literal values by default.
Use a database login with the permissions your workflow needs. The [safety guide](/docs/guide.md#safety) and [provider documentation](/docs/parity.md) explain the collection, planning and execution boundaries.
## Development
Culprit is built with Rust, Tauri and React. The app, CLI and MCP server share one analysis engine. Add custom checks or database providers through the Rust API without forking; [language catalogs](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/localization.md) supply the user-facing text.
Build from source
Install [Rust stable](https://rustup.rs) and [Bun](https://bun.sh). Linux also needs the [platform dependencies](/docs/guide.md#platforms).
```sh
git clone https://github.com/culpritsql/culprit-sql-studio.git
cd culprit-sql-studio
# CLI
cargo build --locked --release -p culprit-cli
# Desktop app
cd app
bun install --frozen-lockfile
bunx tauri build
```
## Learn more
- **[Guide](/docs/guide.md):** every check and command, the agent setup, measured speed, safety details and how to extend Culprit
- **[Collector and warehouses](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md):** background collection, ADX and ClickHouse schemas, Azure Blob/S3 recovery and [Culprit Fleet](https://fleet.culpritsql.com)
- **[Architecture](/docs/architecture.md):** the analysis pipeline, the evidence rules every check follows and the crate map
- **[Design](/docs/design.md):** how the product behaves and why
- **[Coding agents](/docs/agents.md):** MCP tools, permissions, approvals and the audit log
- **[Engine parity](/docs/parity.md):** feature comparison, provider guides, setup and verified versions
Culprit is open source under the [MIT license](https://github.com/culpritsql/culprit-sql-studio/blob/main/LICENSE).
Made for the people who get paged when the database is slow.
---
# Culprit guide
The reference for the Culprit desktop app and the `culprit` CLI: what it checks, every command, how coding agents use it, what it guarantees on production, and how to build it. For the overview, see the [README](/docs/readme.md). For database-specific setup, sources and verified features, see [Engine parity](/docs/parity.md).
Culprit reads the statistics, catalog or file evidence described by each provider, ranks findings by measured impact,
and gives each finding the evidence, fix and a way to verify it. Scans do not apply fixes or run the application's
queries. The editor runs what you ask with production confirmations. The desktop app, CLI and coding-agent tools
share one Rust core.
## Contents
- [What it finds](#what-it-finds)
- [Quick start](#quick-start)
- [Coding agents](#coding-agents)
- [Speed](#speed)
- [Extending](#extending)
- [Safety](#safety)
- [Building](#building)
- [Layout](#layout)
## What it finds
These are examples; `culprit checks` lists the current checks. [Engine parity](/docs/parity.md) explains provider applicability.
| Check | What it means |
|---|---|
| `missing-index` | Index suggestions from the optimizer, merged, de-duplicated against existing indexes and linked to the queries that asked |
| `filtered-scan` | Heavy queries that read a whole table to keep a few rows, with the index that would avoid it |
| `plan-warnings` | Type mismatches that block index seeks, spills to disk, missing join predicates, missing statistics |
| `chatty-query` | Repeated small queries that may indicate polling or an N+1 pattern; request-level evidence is needed to confirm the cause |
| `heavy-query` | Single statements that dominate database time, and what their plan spends it on |
| `plan-regression` | Query Store saw a query get much slower after its plan changed |
| `regression` | A query got much slower at a point in the window: when it started, by how much, and whether a plan change coincides |
| `unstable-query` | The same statement has widely varying durations; source evidence guides the possible causes |
| `temp-spill` | Sorts and hashes exceeding `work_mem` |
| `unindexed-fk` | Foreign keys with no index on the referencing columns |
| `unused-index` | Indexes maintained on every write but never read |
| `duplicate-index` | Identical or left-prefix-redundant indexes |
| `stale-stats` | Optimizer statistics far behind the data |
| `heap-table` | Large tables without a clustered index |
| `dead-rows` | Dead tuples and lagging autovacuum |
| `xid-age` | Transaction ID wraparound risk |
| `config` | Source-backed settings advice, such as unavailable statement statistics or disabled automatic statistics |
Trends use the source's recorded intervals or differences between Culprit's saved scans. The [provider guides](/docs/parity.md)
explain which periods can be compared. `culprit drift ` (Schema → Compare with…) lists the schema differences
between two connections, with the SQL to close the gap.
`culprit checks` lists them with the capabilities each needs. Checks that can't run with your login show up as locked, with the exact grant or setting that unlocks them.
## Quick start
```sh
# Save a connection. Secrets go to the OS keychain; Azure SQL can use your `az login` instead of a password.
culprit conn add shop-staging --env staging \
--url 'Server=tcp:shop-staging.database.windows.net,1433;Database=shop;Authentication=Active Directory Default'
culprit conn discover --match shop --match stg --save # or find Azure SQL, PostgreSQL and MySQL databases your az login can see
culprit conn import --dry-run # or bring in connections from Azure Data Studio, VS Code, DBeaver, DataGrip
culprit conn add app --url db/production.sqlite3 # a SQLite 3 file, opened read-only
culprit conn set app --query-log log/production.log # its framework's log, when it isn't found beside the file (docs/providers/sqlite.md)
culprit scan shop-staging # findings, ranked
culprit scan shop-staging --window 6h # the same over the last 6 hours (90m, 2d, 1d12h; up to 90 days)
culprit dashboard shop-staging # the database at a glance: what needs a look first
culprit changes shop-staging --recent 2h # what got slower, and what changed around it
culprit mark shop-staging deploy v1.4.2 # put a deploy on the timeline (from CI, after a migration)
culprit cloud shop-staging # RDS / Azure metrics against their limits, via your aws or az sign-in
culprit show shop-staging '' # evidence, fix, verification, and a brief for your coding agent
culprit top shop-staging --by cpu -n 10 # heaviest queries
culprit explain shop-staging --sql 'SELECT …' # estimated plan, never executes (--with-index tests virtual indexes on Postgres)
culprit lint-sql shop-staging --file migrations/ --format sarif # lint migration DDL offline against the snapshot (--write rewrites in place)
culprit plan show slow.sqlplan # read a plan from another tool: .sqlplan, EXPLAIN JSON or text, MySQL JSON or tree, SQLite EXPLAIN QUERY PLAN
culprit plan diff shop-staging:42:7 shop-staging:42:9 # compare two Query Store plans of query 42 (or two files)
culprit update --check # is there a newer release? `culprit update` installs it
```
Shared-resource profiling is an explicit option on supported SQL Server/Managed Instance and PostgreSQL scans:
`culprit scan CONNECTION --collect-shared-resources`. It defaults off while the new native allocation/scheduler
readers await production load qualification. Leaving it off sends no SQL from those readers and records that
shared collection was not requested. The captured facts retain broader scope; size or fullness alone does not
create a database pressure warning. See [shared resource collection](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#shared-allocation-and-scheduler-facts).
SQL Server family scans can also request current execution-memory observations with
`culprit scan CONNECTION --collect-request-memory`. This separate opt-in retains waiting and granted requests,
exact native counters and generation-checked request context. A current statement is context, not proof that it
acquired the grant. The default sends no SQL from this reader. See
[current memory collection](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#current-execution-memory-requests) for limits and attribution boundaries.
Or open the desktop app: saved connections are listed in the sidebar, grouped by environment. A connection opens on its **dashboard**: one sentence that says what needs a look first, then fourteen tiles (database time and its trend, findings, top queries, where time goes, sessions right now, health, deadlocks, indexes, plans, storage, connections, replication, failing queries, query statistics), each a plain takeaway, a small picture and a click into the view that explains it. Every engine gets every tile; one it can't fill says why. The ranked findings are one key away (`2`). Pick the engine and paste its connection string, or pick **SQLite** and choose the file (then **Add query log** if its framework's log isn't found beside it), use **Find Azure databases** / **Find AWS databases**, or **Import from other tools** (names, hosts and user names only; passwords are asked for once), and the first scan appears in seconds. Reopening a connection shows its last report instantly while a fresh scan runs. Rename a connection's alias with the pencil on its card or `culprit conn rename`.
Entra ID connections use your `az login`. Without the Azure CLI (or when it's signed out), Culprit signs in with a device code instead: the app shows the code, the CLI prints it when you're at a terminal. Access tokens stay in memory, the refresh token in the OS keychain; `culprit auth logout` forgets it. Scripts and agents never block on a sign-in: they get an error with a hint.
On non-production connections, Live can request cancellation of an observed request or termination of its whole session. Culprit rechecks the original native identity before signalling; the database's numeric signalling API still allows a concurrent-change race. Success confirms signal acceptance, not completed cancellation, exit or rollback. Production connections refuse both actions.
The CLI requires the original JSON observation. Capture it before selecting a session, then pass the same file with `--cancel` or `--kill`:
```sh
culprit live shop-staging --json > /tmp/culprit-live.json
culprit live shop-staging --cancel 42 --observation /tmp/culprit-live.json
```
### SSH jump hosts
Enable **SSH jump host** when adding a server connection, or open **SSH** on a saved connection's card. Enter a host such as `reader@bastion` or an alias from your OpenSSH configuration. The same settings work on connections added through Azure or AWS discovery. **Test connection** checks a draft with the saved database credentials before you save it.
```sh
culprit conn add shop --url 'postgres://app@db.internal:5432/shop' --ssh prod-bastion
culprit conn set shop --ssh reader@bastion --ssh-port 2222 --ssh-key ~/.ssh/id_ed25519
culprit conn set shop --no-ssh
```
Keep the real database hostname and port in the connection string. Culprit forwards the network connection while preserving that identity for certificate verification, AWS IAM, Entra ID and cloud metrics. It uses the system OpenSSH client, your SSH configuration and agent; host keys must already be trusted, and encrypted keys must be unlocked in the agent. See [SSH connections](/docs/ssh.md) for setup, supported authentication and lifecycle details.
### Plans: paste, compare
The **Plans** view (`7`, also without a connection) draws any plan you paste (⌘V anywhere), drop or open: SQL Server .sqlplan or showplan XML, Postgres `EXPLAIN` as text or `FORMAT JSON` (psql output included), MySQL `EXPLAIN FORMAT=JSON` or `EXPLAIN ANALYZE`. **Compare** puts two plans side by side and says what changed in plain words ("Plan 9 scans orders where Plan 7 seeks ix_orders_customer"), with every changed, added or removed operator marked in both diagrams. On a query with several Query Store plans, **Compare** in the Queries view opens the fastest and the slowest plan; **Open in Plans** keeps any plan to save it (.sqlplan opens again in SSMS) or compare it with another environment's.
### Editor and saved queries
The **Editor** keeps your query tabs across restarts (⌘T new, ⌘⇧W close, ⌘⇧[ / ⌘⇧] switch), completes schemas, tables and columns as you type, read live from the connection (aliases included: after `o.` it offers only that table's columns, with their types), and lints DDL and migration statements inline against the latest snapshot with one-click quick fixes. ⌘↵ runs the selection or the whole tab, ⌘E shows the plan without running it, ⌘S saves the tab as a named query.
**Saved queries** live in the editor's side rail, the command palette (⌘K, "Run saved: …") and the CLI (`culprit saved list | add | show | run | rm`); each remembers the connection it was saved for and can run on any other.
**What runs without asking:** a statement Culprit's classifier proves only reads runs anywhere, in a read-only transaction (rolled back on SQL Server, which has none). Anything else commits; on a **production** connection only after a confirmation that names what it does ("This UPDATE has no WHERE clause, so it changes every row in the table"), and statements that touch every row or drop objects need the connection's name typed. In the CLI, `--yes-execute-on-production` is that confirmation. `culprit catalog ` prints what completion sees.
Findings whose queries stopped running well before the end of the data window (relative to how often they used to run) move to a "Stopped running" group: usually a deploy changed or fixed them.
**One thing per tab:** while a tab runs, plans or waits for a production confirmation, another run there waits its turn (open another tab to run in parallel). Closing a tab stops its batch: nothing after the statement in flight is sent, and that statement finishes on the database.
### Collect native telemetry to files
For a durable background service with private recovery storage and analytical delivery, see the
[collector deployment and recovery guide](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md).
`collect once` exports runtime and wait measurements with their referenced query and plan definitions for one retained, completed Query Store interval on Azure SQL Database. Use its exact native boundaries:
```sh
culprit collect once shop-staging \
--from 2026-11-09T06:00:00Z --until 2026-11-09T07:00:00Z \
--output ./telemetry-observation --json
```
The output directory must be new and its parent must exist. It contains `runtime.ndjson`, `waits.ndjson`, `queries.ndjson`, `plans.ndjson` and `manifest.json`. The manifest records database identity, interval, replica groups, capture policy, file hashes, each stream's completion and reference coverage. Integer counters and native identifiers are decimal strings to retain their precision. A failed or interrupted stream remains incomplete, with a `.part` file when applicable. Missing query/plan references keep the observation incomplete even when metric files finished. Exit status is 0 for complete reads and resolved references, 2 for an incomplete observation, and 1 for an error. Existing exports are never overwritten or resumed.
Defaults are 500 records and 4 MiB per page, 64 MiB total, 32 page attempts, 128 native reads, 5 seconds per statement and 60 seconds overall. The corresponding `--page-rows`, `--page-bytes`, `--max-bytes`, `--max-pages`, `--max-queries`, `--statement-timeout-ms` and `--timeout-ms` flags set these budgets. Small intervals use one data read per metric stream; oversized ranges split by replica and plan ID. Definition payloads are packed into bounded batches after their lengths are read. Missing or high pressure signals stop collection conservatively. These limits do not guarantee a fixed database CPU or I/O cost.
The command uses statistics sessions, parameterized tagged queries and the connection's existing credentials. It reads no application tables, changes no database settings, and never prompts for a device-code sign-in. Definitions are fetched only for referenced native IDs. Their lengths are read before payloads: `--max-sql-bytes` defaults to 256 KiB and `--max-plan-bytes` to 2 MiB of native UTF-16 bytes. The effective limit can be smaller to fit one complete encoded record within the page budget; increasing a payload cap may also require increasing `--page-bytes`. Oversized, restricted, encrypted, missing or unsafe payloads have explicit availability states; definitions are never truncated. SQL literals/comments and plan parameter values are redacted before files are written. Object names remain visible, so exports still require access controls. Monitoring permissions must already exist; reading native identity in an elastic pool can require server state access. Ctrl+C cancels owned work before returning. Unconfirmed cancellation blocks further collection in that workspace; verify server activity before creating another collector. Admission is local to one workspace, so run one collector for the pilot.
Each line is a versioned envelope with `capture`, `batch_id`, `record_id`, `representation_version` and the typed `record`. `capture` contains an `observation_id` and an optional outbox `revision`. Definition IDs use native compilation identity, context, hashes and the database/source namespace, independently of redacted payload bytes. Metric IDs additionally include the native interval, row, replica and execution outcome; waits include their category. An unresolved native definition leaves `record_id` absent. Replaying the same export preserves its IDs; a new collection has a new observation ID. Native database identity keeps IDs stable across connection alias and endpoint changes. The export retains native statistics rows; resolve complete observation revisions before aggregating them, and never sum repeated captures of the same interval.
Live activity retains native client application, login and host metadata. It excludes the observing session by native session ID while keeping other Culprit sessions when they are active or hold relevant transactions. Query Store and cached aggregate statistics do not retain the originating client's application name; SQL comments identify Culprit's historical statements without treating a marker inside a string or quoted name as ownership. A local connection alias is not sent as a server-side session identity. [Native session metadata](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-exec-sessions-transact-sql), [Query Store identity](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-query-store-query-transact-sql).
Culprit's own queries remain in the raw history so monitoring overhead can be investigated. Query definitions identify application, Culprit monitoring, other tagged Culprit, engine-internal and unknown statements before SQL redaction removes comments. Monitoring definitions also retain a template ID, which excludes bound arguments. Application recommendations leave Culprit's queries out. Native runtime rows retain duration, CPU, reads, writes, rows, memory, parallelism, CLR, log and tempdb measurements with their units and explicit unknown values.
Query Store can omit monitoring statements under its capture policy, so native history alone does not establish total collector cost. Each capture's `manifest.json` also contains `read_metrics`: bounded per-template client elapsed time, decoded rows, charged decoded-value bytes, failures, timeouts, cancellations and unconfirmed cancellations. These measurements require no extra SQL, persist no bound argument values, and correlate with native history through the template ID. Client elapsed time is not database CPU; charged bytes are not disk or network I/O. Metrics unavailable from a source remain `null`; `active_tasks` and `untracked_tasks` make unfinished or capacity-limited accounting explicit.
“Complete” describes the native reads and reference closure. Unavailable payloads remain visible separately. Source-generation continuity is unverified, and pages are reconcilable observations rather than an atomic snapshot. Definition discriminators reduce native ID reuse collisions but do not prove that Query Store was never cleared. Files are flushed before completion; `directory_synced` states whether directory entries were also flushed on this platform.
`--collection resource-history` selects retained Azure SQL resource samples instead of Query Store. Its half-open window selects native sample timestamps and needs no Query Store interval boundary:
```sh
culprit collect once shop-staging --collection resource-history \
--from 2026-11-09T14:00:00Z --until 2026-11-09T14:05:00Z \
--outbox ./telemetry-outbox --json
```
Choose a recent past window within the source's retained history. The capture contains `resources.ndjson` and `manifest.json`, using the same budgets, cancellation ownership, outbox and replay commands. The native view retains approximately one hour of samples at 15-second intervals, shortened by failover. The description records the retained timestamp bounds, expected native row count and nominal period. A window outside those bounds remains incomplete with `retention-gap`, even when the retained subset was read successfully; it cannot advance the outbox's captured-range head. Successful reads do not prove uninterrupted sampling between native timestamps. [Native resource statistics](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-db-resource-stats-azure-sql-database?view=azuresqldb-current).
Each resource row contains typed metric samples with stable keys, units, scope, aggregation, measurement period, limit basis and an optional value. The Azure adapter exports database CPU, data I/O, log writes, memory, maximum workers/sessions, In-Memory OLTP storage and DTU/vCore limits. Instance CPU/memory remain shared server measurements; instance CPU has native one-minute granularity. NULL stays unknown. This reader currently supports Azure SQL primary replicas. It reads bounded statistics views independently of Query Store, including when workload collection is suppressed by pressure; it shares native read deadlines and confirmed cancellation. It reads no application tables and makes no fixed CPU-overhead claim.
The source does not establish a stable shared-instance identity. Shared measurements observed through different databases cannot be summed or assumed to refer to different instances.
The scan and background collector share the same native resource reader. The scan derives its timeline and pressure summary from one history read; NULL metrics stay unknown, and native fractional timestamps are preserved. Workload admission uses a latest-sample request through that reader.
Overlapping resource windows preserve the native sample's record ID. Repeated observations must not be counted as additional measurements.
Collection profiles and stream metadata are independent of database-provider and destination identities. The engine validates and persists the selected streams rather than manufacturing empty files for every known family. File metadata declares whether a stream contains intervals, samples, events, checkpoints or definitions. Native wait counters use cumulative-counter semantics, independently of interval-based Query Store waits. Exports use the current draft format only; older draft outboxes are rejected without migration.
`--collection query-compilation` captures retained Query Store compilation facts into `operations.ndjson`, without a historical window. Counts remain exact decimal strings; average duration is in microseconds. Native first/last compile timestamps and the clock comparison remain separate facts. The profile includes Culprit's own retained queries and uses the same decoder as scan diagnostics. A query ID and its initial compile time identify the retained lifetime; these totals must not be assigned to a runtime interval or summed across repeated captures. Unknown reset continuity remains explicit.
`--collection operational` on the default Azure SQL database subject captures current log space, writable
filegroup capacity, sequence/identity limits, database file I/O and database-attributed queues, without a historical window:
```sh
culprit collect once shop-staging --collection operational --outbox ./telemetry-outbox --json
```
The capture contains `operations.ndjson` and its manifest. Spaces retain bytes, scope, configured file limits,
growth settings and native reuse reasons. Sequence values remain decimal strings; unknown measurements remain
`null`. Database captures exclude instance performance counters, processor topology, compiler gateways and shared
tempdb capacity. Shared resources have their own explicit owner, rather than repeating their readings per database.
File I/O facts preserve native database/file IDs, logical names and type when visible, exact read/write counts, bytes and stall milliseconds, on-disk bytes and native uptime ticks. An unavailable name or type does not remove the native counter row. Reset history stays unknown; uptime ticks do not establish a reset epoch. The export keeps zero-I/O files and the complete bounded native file set; the app separately ranks its display. Both use the same targeted reader. [Native file statistics](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-io-virtual-file-stats-transact-sql).
Read and write accounting travel with each file. On Hyperscale, page-server responses, simulated data writes, primary log-service writes and secondary log bookkeeping remain distinct from conventional storage operations. A separately qualified local-cache read retains server scope; a pool cache is not attributed to the selected database or replica. Unknown deployment or role metadata stays unknown. The app shows these native measurements without applying physical-storage thresholds to them, and it does not combine different replicas, reset periods or operation kinds. Broader tempdb capacity likewise belongs to an explicit shared-resource observation. [Hyperscale I/O accounting](https://learn.microsoft.com/en-us/azure/azure-sql/database/hyperscale-performance-diagnostics#virtual-file-stats-and-io-accounting).
Discover an existing shared resource and save its returned native identity before collecting it:
```sh
culprit collect resources shop-sqlserver --kind instance --json > resources.json
jq -e '.[0].identity' resources.json > instance.json
culprit collect once shop-sqlserver --resource ./instance.json --collection operational \
--output ./instance-capture --json
```
SQL Server and Managed Instance use `--kind instance`. Azure SQL uses `--kind pool` through a writable member
connection for retained `resource-history`; generic instance/host current-state families are unavailable through
that pool route because their ownership is not established. PostgreSQL's `--kind instance` operational route retains the server-wide statistics and
main shared-memory allocations its native version and permissions expose. Unsupported subjects are explicit errors.
| Shared observation | What it retains |
|---|---|
| SQL Server memory clerks | Component type/name/node groups, native clerk counts and separate allocation dimensions; no pointer export or guessed query owner |
| SQL Server schedulers | Scheduler/node/CPU identity, status, workers, runnable tasks, queues, pending I/O and available CPU/delay counters |
| SQL Server performance/topology/compiler admission | Native object/instance/type, unit, scope and meaning, with unknown resets preserved |
| PostgreSQL 13+ memory allocations | Main shared-segment names/offsets, byte sizes and padding; private backend/query memory and dynamic shared memory are outside this source |
These are component and scheduling facts. They do not identify a responsible query or establish memory pressure
from size alone. Missing fields stay unknown, denied families retain their own coverage, and readable sibling
sources survive a restricted allocation view. SQL Server 2022+ uses `VIEW SERVER PERFORMANCE STATE` for memory
clerks and schedulers; earlier SQL Server uses `VIEW SERVER STATE`, with Azure-specific requirements by service
objective. PostgreSQL checks effective statistics privileges and native view/function access. Culprit changes no permissions.
Result limits do not bound every step of native metadata grouping: qualify source cost before production scheduling.
See [the shared-source details](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#shared-allocation-and-scheduler-facts).
Shared performance facts include batches, compilations/recompilations, page-life expectancy, logins and connection
resets. Unknown native counter types retain unknown meaning/unit; missing recompilation counts never become zero
in a compilation ratio. Short samples subtract exact counters only when both matching readings exist. Native
instance rows cannot replace global counters. [Native performance counters](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-os-performance-counters-transact-sql).
Current queue facts count memory grants and worker tasks separately, preserving exact counts, maximum observed waits and the selection threshold (100 ms for worker tasks). Database counts require the native request's database; session defaults are insufficient. Unattributed members of shared native queues remain coverage metadata and cannot be added to a database count or summed across captures. Unknown attribution makes that source partial, with no healthy zero in the app. Native task/request identity prevents MARS requests from multiplying wait rows. App and background reads use the same bounded implementation. [Native waiting tasks](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-os-waiting-tasks-transact-sql), [native task/request identity](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-os-tasks-transact-sql).
The tempdb version-store gauge preserves this database’s reserved space as exact native kibibytes. The app converts the same fact to bytes; an unavailable source never becomes zero. The reader uses aggregated space metadata, with no walk through individual row versions. ADR’s persistent version store requires separate collection. [Native tempdb version-store space](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-tran-version-store-space-usage).
The snapshot description records each native source separately: collected, empty, partial, unavailable or not applicable, its record count and scope completeness. File completion confirms the exported observation; native source availability is reported separately. Restricted metadata cannot establish an empty sequence catalog. Current absence requires a complete source; unavailable or incomplete observations preserve its earlier evidence. Pressure suppresses remaining reads after one failed admission probe. Azure SQL does not expose msdb suspect-page history; that source is explicitly not applicable. The native model carries an offset-free reported timestamp with unknown reset semantics, without assigning a UTC event time or a server-start counter epoch.
Shared instance capture keeps reported host logical CPU metadata, online SQL user schedulers and visible NUMA nodes
separate. Host CPU counts establish neither instance entitlement nor a database CPU quota; Azure
resource history carries the database's native CPU limit separately. When captured, online schedulers provide
parallelism context. [Native scheduler meanings](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-os-schedulers-transact-sql).
On databases with ADR enabled, operational capture also keeps persistent version-store statistics separately: off-row and online-index kibibytes, aborted transaction counts, transaction watermarks and native cleanup timestamps. Off-row size excludes versions stored within data rows. The app displays it as information rather than grading every database by one size threshold. Known disabled ADR or unsupported server versions are not applicable; unreadable or missing measurements are unavailable, never a zero. Tempdb allocation is labelled explicitly and cannot measure ADR's persistent store. See [the native PVS statistics](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-tran-persistent-version-store-stats).
Operational capture also includes the transaction horizon: the oldest transaction with logged work or an explicit snapshot in this database, and separately any oldest candidate whose row-version activity has unknown database attribution. Session and transaction identities, native local begin times, exact log counts/LSNs and distinct transaction/XSN ages remain facts. An unknown age or database attribution is not a healthy zero. This current maximum does not enumerate every transaction or prove one ended when another becomes the maximum. Other Culprit sessions stay in raw telemetry for overhead investigation. Database version-store size is separate context; use the native log-reuse reason when diagnosing log growth, including on ADR-enabled databases.
`--collection wait-counters` captures all nonzero native wait types into `wait-counters.ndjson`, including idle waits that the app leaves out of its performance summary. The app's categories, pressure totals and short samples use this same native reader. Counts and total/signal/maximum wait milliseconds remain exact decimal strings, with database or server scope. The Azure export uses database scope only.
```sh
culprit collect once shop-staging --collection wait-counters --outbox ./telemetry-outbox --json
```
These views expose no reset generation: a restart is not the only way their counters can reset. The export records an unknown reset marker, never an invented startup epoch or a precomputed rate. Omitted zero rows are not independently observed zero measurements. Maximum wait time is a native maximum, not an additive total. Short interactive samples reject detected counter regressions or disappearing rows; a reset that catches up between readings remains undetectable. [Native wait counters](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-os-wait-stats-transact-sql).
Background Azure SQL captures require a confirmed primary connection. Retained/current-state readers recheck it with native database identity during verification; activity checks the replica fact on its observed frame. Read-only replicas require their own validated export profile. Interactive readers retain replica facts independently of export policy. [Replica detection](https://learn.microsoft.com/en-us/azure/azure-sql/database/read-scale-out?view=azuresql#verify-that-a-connection-is-to-a-read-only-replica).
`--collection replication` captures current native geo-replication links into `replication.ndjson`. Link GUIDs, local endpoint roles, partner names, native states and primary-only lag/time measurements remain facts; secondary lag is unknown. The app uses the same bounded native reader. SQL Server and Managed Instance scans also read database-scoped availability replicas, retaining native GUIDs, nullable direction, suspension/health, exact queue sizes and native transfer-rate units. Optional columns are selected from catalog metadata before reading. Failed reads become unavailable coverage, with no schema retry or silent empty result.
```sh
culprit collect once shop-staging --collection replication --outbox ./telemetry-outbox --json
```
Only a complete native read can establish that a replication source is empty. Unknown roles stay in raw telemetry and cannot be assigned an application lag verdict. Native replica state has local relevance and can be out of date; it does not establish cluster-wide freshness. [Availability replicas](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-hadr-database-replica-states-transact-sql), [geo-replication links](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-geo-replication-link-status-azure-sql-database).
`--collection settings` captures current database, scoped configuration and Query Store options into `settings.ndjson`. It has no historical window. Native values, active values, secondary values and default provenance remain separate; a NULL value stays unknown. Server settings are not applicable to this Azure SQL profile. The app uses the same reader and reuses options already read by its probe.
```sh
culprit collect once shop-staging --collection settings --outbox ./telemetry-outbox --json
```
Each native source has its own coverage. Configuration, changing status and usage measurements have distinct types: Query Store storage growth is not a configuration change. A partial or failed read cannot establish that settings stayed unchanged or disappeared.
`--collection plan-cache-summary` records database-filtered cache entry counts and bytes in `operations.ndjson`.
It separates total cache footprint, ad hoc entries with one recorded lookup and prepared entries with one lookup.
These are gauges, not execution counters: parameterized reuse does not increment the native lookup count.
The app's cache advice uses the same reader and excludes prepared entries. This profile scans cache metadata;
use a slow cadence and measure its cost before scheduling it across a fleet. It is excluded from `operational`.
`--collection statement-grants` streams this database's retained statement-cache memory-grant counters into
`operations.ndjson`, including Culprit's own queries for cost investigation. It preserves native handles,
statement byte offsets, compilation generations, exact counters in kibibytes and timestamps without invented
UTC offsets. Query hashes group related statements; they do not identify a cache entry or prove continuity.
The app uses the same native relation and decoder, then summarizes the selected workload separately.
One owned SQL statement supplies bounded pages; a final native completion and identity check establish the
capture's final coverage. Row, byte, query and time limits still apply. Set `--max-snapshot-rows` deliberately
(up to 100,000); the default remains 500. Truncation or a late SQL error cannot establish complete coverage.
Cache eviction or recompilation is not evidence that a query stopped running. Native execution timestamps
record start times, so the app does not use them to order concurrent completions or average unrelated last-grant
values. This metadata scan belongs on a measured slow cadence, outside the fast operational profile.
[Native cache counters](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-exec-query-stats-transact-sql).
`--collection index-operations` streams per-partition index and heap counters into `operations.ndjson`.
It retains native object, index, partition and internal rowset identities; inserts, updates, deletes, page
allocations and merges; forwarding and LOB reads; lock, latch and I/O waits; compression, versioning and
compaction counters where the native columns exist. Counters remain exact decimal strings with their units;
absent columns and native NULL values remain distinct. Hidden names do not discard the native row.
The scan derives heap-forwarding and index-contention summaries from this same relation and decoder.
This is a current metadata-cache observation, outside the fast operational profile. One owned statement supplies
bounded pages, followed by native completion and identity verification. `--max-snapshot-rows` and the other
collection budgets apply; a truncated read cannot establish complete coverage. Counters can reset when metadata
leaves the cache, independently of server startup, so captures do not claim a known reset epoch or a historical
rate. This native source excludes memory-optimized indexes. Measure source cost before fleet scheduling.
[Native index counters](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-db-index-operational-stats-transact-sql).
`--collection tuning` captures automatic tuning options, recommendations, forced-plan failures and Query Store
hints in `tuning.ndjson`. It uses the scan's native readers and reports coverage separately for each source.
Counts remain exact decimal strings, absent measurements remain unknown, and recommendation-time CPU statistics
are separate from current execution costs. Hint payloads are bounded before retrieval; oversized payloads are
explicitly unavailable. Export redacts SQL literals before writing. Query/plan IDs here are native references
within the observation; they do not establish a definition match across captures or Query Store resets.
Configured forcing and hints can still be captured with Query Store OFF. This profile does not enumerate
per-replica plan-forcing locations or establish complete tuning-event history.
### Export retained deadlock events
`--collection deadlock-history` selects a past timestamp window from Azure SQL's explicitly configured,
[database-scoped deadlock session](/docs/providers/mssql.md#azure-sql-deadlock-events), using the same native reader
and graph parser as interactive investigation:
```sh
culprit collect once shop-staging --collection deadlock-history \
--from 2026-11-09T14:00:00Z --until 2026-11-09T14:05:00Z \
--outbox ./telemetry-outbox --json
```
The capture contains `deadlocks.ndjson` and `manifest.json`. Events retain native session generation and event sequence, precise time,
victims, redacted statements, participants, resource edges and a typed pattern. Login, host and application identities
are omitted. The source is read under pressure and work budgets and rechecked before completion; changing membership
or a result exceeding `--max-snapshot-rows` leaves the capture incomplete. Choose smaller windows for a busy source.
`history_complete: false` and an unknown retained horizon describe a native limitation. Successful emptiness means
that no matching event was visible in that read; it does not establish complete deadlock history. No diagnostic export,
event session or database setting is enabled by the command. Ingestion and durable remote recovery are separate from
this local capture command.
### Monitor persistent activity
Activity monitoring saves a bounded native metadata baseline before running offline diagnostics. It retains ordinary sessions and short waits from the provider’s declared population. SQL and blocker investigation are separate steps. Initialize a local outbox, then run:
```sh
culprit collect outbox init ./activity-outbox --json
culprit collect activity shop-staging --outbox ./activity-outbox --json
```
The default is one attempt per minute, with the next interval starting after the previous attempt finishes. `--poll-seconds` accepts 60 seconds or more; failed attempts back off, up to 15 minutes or the configured interval if longer. There are no overlapping reads or catch-up bursts. `--max-polls 1` performs one bounded attempt. Ctrl+C cancels owned work and stops the monitor; unconfirmed native shutdown stops further polling.
Polling, native retention and episode analysis are independent. Defaults are `--blocked-seconds 30` and `--running-seconds 60`. These thresholds select diagnostic episodes after the baseline has been saved. Diagnostic revisions retain observed evidence and lifecycle changes; notification routing and throttling are separate. Unchanged counters alone do not establish that a request is hung. Requests that start and finish between polls can be missed.
Each provider owns the native population, source authority, read bounds and visibility qualification. A fully read population can still exclude system sessions, parallel tasks or other nodes. Capped or hidden reads retain their verified positive rows with incomplete native coverage. Only qualified absence in the matching native source can resolve an episode; missing visibility and failed reads preserve uncertainty. Source-owned session, request and statement identities support later exact rechecks without executing the observed statements.
The native capture contains `activity.ndjson` and its manifest. The same offline diagnostic worker used by fleet collection writes separate derived captures and durable working-set checkpoints. Native evidence is sealed before that work starts. JSON mode reports `active_episodes`, `uncertain_episodes` and `native_coverage`; counts remain `null` when matching analysis is unavailable. An episode can resolve while still retaining owed analysis. A request waiting on a resource is an affected participant, not a proven owner or cause.
For a standalone baseline, use `collect once CONNECTION --collection activity --output NEW_DIRECTORY --json`, without `--from` or `--until`. `collect activity` monitors one connection; `collect fleet` schedules multiple connections and sources. Native and derived captures both charge to the outbox limits. A full outbox stops before another source read. Remote recovery and acknowledgement govern safe eviction.
### Collect a static fleet
`collect fleet` uses the same authenticated providers, native admission guard and durable outbox as one-off collection.
Each inventory target has a stable `id`, a connection, an explicit database or shared-resource `subject`, one static
shard and a physical admission group. A database and its shared pool/instance can use the same connection with
separate schedules and checkpoints. A shared native resource has one owner across the complete inventory, even
when several member connections can read it. Databases sharing an instance or elastic pool must use the same
admission group; a group cannot be split across shards. Only one process may own a shard's scheduling state and
outbox. The workspace permits one native operation at a time, including interactive reads. Group names do not
establish measurement scope. See [shared-subject discovery and collection](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#database-and-shared-subjects)
for the available native routes.
```json
{
"targets": [{
"id": "shop-database",
"connection": "shop-staging",
"subject": { "kind": "database" },
"shard": "alpha",
"admission_group": "shop-elastic-pool",
"schedules": [
{
"id": "live",
"every_seconds": 60,
"jitter_seconds": 15,
"collection": { "kind": "activity" }
},
{
"id": "queries",
"every_seconds": 300,
"jitter_seconds": 30,
"collection": { "kind": "query-history", "lookback_seconds": 86400, "reconcile_seconds": 3600 }
}
]
}]
}
```
```sh
culprit collect outbox init ./fleet-outbox --json
culprit collect fleet --inventory ./inventory.json --shard alpha \
--state ./fleet-state --outbox ./fleet-outbox \
--azure-identity ./identity.json --json
```
Each schedule can supply a complete `budget` object with the same fields as `CollectionBudget`; omitting it uses the shared collection defaults. An activity schedule similarly defaults to the normal incident policy. Unknown configuration fields are rejected. Other collection kinds are `resource-history` and `deadlock-history` (each with `window_seconds` and `overlap_seconds`), and `snapshot` (with a `dataset` matching a point collection listed above). A capture window including overlap may span at most one day; interval metadata discovery can cover up to seven days. Provider support and coverage limits remain unchanged; scheduling does not enable missing native features.
Schedules never run faster than once a minute. Positive jitter is added to the period after a completed attempt, and each physical group waits at least a minute between native operations. Pressure suppresses the whole group with increasing delays up to fifteen minutes; failed sources back off independently. Old backfill and recent Query Store reconciliation have separate durable turns, so a long backfill cannot monopolize history collection. Confirmed older captures outside the reconciliation horizon are skipped using the outbox receipts. Failed windows and unconsumed interval pages survive restart. Backfill is bounded to seven days; uncovered older windows and native-retention failures are recorded as durable gaps, rather than reported as successful collection.
Fleet authentication requires explicitly configured unattended Azure credentials for Entra connections, or `--password-env` credentials saved on a password connection. It never falls back to the Azure CLI or a keychain prompt. A changed inventory, ownership assignment or observed database identity requires draining and replacing the scheduling state; pending captures are not redirected. Ctrl+C and SIGTERM request cancellation and await the existing native shutdown path. Unconfirmed shutdown retains the workspace fence and stops the runner. `--max-work` limits work items, including interval discovery and local skips; a discovery success is not a successful data capture.
This command captures locally. Remote delivery, automatic eviction, deployment and production overhead qualification have separate acceptance gates; an outbox capacity limit pauses source work without proving any data reached a remote destination.
### Keep captures in a local outbox
Collection supports unattended Azure authentication with `--azure-identity FILE` on `collect once`, `collect activity` and `collect fleet`. An Entra connection then uses only that configured identity, with no Azure CLI or interactive fallback. For an AKS projected workload token, the JSON file contains the tenant and application IDs and the absolute token-file path:
```json
{
"kind": "workload-identity",
"tenant_id": "00000000-0000-0000-0000-000000000001",
"client_id": "00000000-0000-0000-0000-000000000002",
"token_file": "/var/run/secrets/azure/tokens/azure-identity-token"
}
```
Replace the example IDs with the provisioned identity. For VM/VMSS managed identity through Azure IMDS, use `{"kind":"managed-identity","client_id":"YOUR-IDENTITY-CLIENT-GUID"}`; `client_id: null` explicitly selects the system-assigned identity. These files contain configuration references, never passwords or access tokens. Refresh reopens rotated projected tokens and caches SQL, Storage and Kusto credentials separately. Tokens remain in the engine process. Database permissions and network access must already exist. The direct paths have local contract tests; live workload identity/RBAC validation requires the corresponding Azure host. [Federated credentials](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow), [VM managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token).
Without the flag, `collect once` and `collect activity` may use the Azure CLI session already authenticated by their pipeline. For strict CLI-only behavior in those commands, set `CULPRIT_ENTRA_LOGIN=azure-cli`; the Azure CLI owns token refresh in that path. `collect fleet` requires explicit unattended credentials instead.
Initialize an outbox once, then use `--outbox` instead of `--output`:
```sh
culprit collect outbox init ./telemetry-outbox --json
culprit collect once shop-staging \
--from 2026-11-09T06:00:00Z --until 2026-11-09T07:00:00Z \
--outbox ./telemetry-outbox --json
culprit collect outbox status ./telemetry-outbox --json
```
The outbox has one local writer. It reserves space and a capture revision in a SQLite journal before reading the source. Each stream has a stable batch ID. Only a complete, verified capture whose native work has stopped can become `ready`: its file receipts, state and exact native-range head commit in one transaction. Range heads identify individual intervals; they do not establish continuous coverage of the time between them.
Revisions contain `outbox_id`, `owner_epoch` and `sequence`. Compare the latter two as decimal integers, and only within the same intact outbox. Reopening an owner allocates a new epoch on its first capture. A retry that reads the source again gets a new revision; recovery of already sealed files preserves the original revision. A standalone `--output` export has no revision.
```sh
culprit collect outbox recover ./telemetry-outbox --json
culprit collect outbox verify ./telemetry-outbox OBSERVATION_ID --json
culprit collect outbox replay ./telemetry-outbox OBSERVATION_ID \
--output ./replayed-observation --json
```
Recovery examines unfinished attempts and the directory inventory. It commits sealed, valid files when native work was confirmed stopped; otherwise it records an interrupted or quarantined attempt without advancing its range head. Collection runs recovery automatically before reserving its first attempt. An incomplete capture is retained for inspection; there is no resume within an interval. Repeat `collect once` explicitly to reread it. `verify` audits a ready capture against its original journal receipts and quarantines corruption. `replay` verifies and copies the original bytes to a new directory, publishing the original manifest last. These outbox commands neither open database connections nor allocate capture revisions. Recovery does not rehash the whole retained backlog; use `verify` or `replay` to audit a ready capture.
An interrupted active request or an unconfirmed cancellation blocks further collection through that outbox, including after restart. First run recovery and independently establish that the old collector's database work has stopped. Then explicitly acknowledge that observation:
```sh
culprit collect outbox acknowledge ./telemetry-outbox OBSERVATION_ID \
--source-quiescent --json
```
The workspace also keeps a durable safety record for every capture, including standalone `--output` exports. Uncertain native work blocks all new collection in that workspace, even after restart or when using a different output directory or outbox. Inspect it without connecting to the database:
```sh
culprit collect admission status --json
```
After independently verifying that the listed observation's database work has stopped, acknowledge that exact observation:
```sh
culprit collect admission acknowledge OBSERVATION_ID --source-quiescent --json
```
For an outbox capture, acknowledge both the outbox and workspace records. These commands record the operator's assertion; they do not query or cancel the database, clear a different observation, or make an interrupted capture ready. An active owner prevents acknowledgement. SQL Studio shows the connection or connection test and its observation ID when a scan is paused. After checking database activity, confirm the request has stopped and select **Resume scanning**. Acknowledging in the same workspace instance also reopens its native gate. If another process acknowledges the record, reopen the paused application. This ownership applies only to processes using the same workspace directory; separate workspaces and hosts are not coordinated.
Defaults retain up to 1 GiB of charged capture space and 256 attempts, including incomplete and quarantined attempts. `init --max-bytes` and `--max-captures` set these limits. Each attempt reserves its total-byte budget plus 256 KiB before source work; completed attempts are charged their artifact sizes plus 4 KiB. A full outbox refuses new collection before the provider starts. The SQLite database has a separate 16 MiB ceiling plus its WAL and shared-memory files. Status is paginated with `--limit` (1–500) and `--after` using the returned `next_cursor`. These local CLI commands do not automatically deliver or evict captures.
Use a private directory on a local filesystem and preserve it as a unit; do not copy, restore or share it with an active owner. Tests cover process termination around the local commit boundary. They do not establish power-loss durability or network-filesystem support.
Embedding applications can compose a remote outbox with `ObjectRecoveryStore`, `AzureBlobTransport` and `DeliveryWorker`. Remote commits permit local eviction while the analytical destination is unavailable, and a replacement delivery journal can resume without recollecting the database. The latest activity checkpoint remains local during normal eviction. Remote ownership and capture ordering are separate from database cancellation: after total volume loss, establish source quiescence independently before resuming collection. Azurite exercises the Blob protocol locally; live Azure authorization, networking and ADX ingestion are separate acceptance checks.
Run the owned, loopback-only Blob integration fixture with `python3 dev/smoke-delivery.py`. It builds the affected engine tests, creates an isolated Azurite container with synthetic credentials, runs the conditional-write/recovery test and removes the container. It does not use Azure credentials or connect to a database.
Applications embedding the Rust libraries can read explicitly selected ADX or ClickHouse captures through the
[verified evidence API](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#components-and-ownership), using warehouse query credentials and independent
recovery-proof access. It reconstructs resource samples, inline operational facts, interval query runtime/waits and
query/plan definitions after exact verification. Native identities, units, outcomes and references stay intact;
truncated SQL/plans, missing rows and recovery-only details remain explicit gaps. It does not open the source database,
choose the latest capture or combine epochs. With the engine's `collector` feature, the separate offline consumer
can analyze one verified query-history capture through the existing checks. Its result retains native evidence and
limitations; it provides neither a current database-health report nor a desktop warehouse connection. Missing
runtime rows prevent invented workload shares, and missing current fix prerequisites withhold executable SQL.
Byte limits cover complete native query response bodies, including metadata/completion frames, and decoded rows
also respect the per-response ceiling. Recovery proofs have their own ceiling. HTTP/TLS/authentication overhead is outside those byte limits. Caller timeout does
not acknowledge remote warehouse query shutdown.
### Upgrading
Connections, saved passwords, saved queries and editor tabs carry over. Scans and reports are read only in the format the installed version saves: when an upgrade changes that format (the release notes say so), scans an earlier version saved are set aside, and history (trends, What changed, digests) starts again with your first scan after upgrading. A saved plan is read as it was saved; a later fix to a plan parser reaches a plan when it is explained or scanned again.
## Coding agents
Culprit is built to be driven by coding agents. Every command prints JSON when stdout isn't a terminal (or SARIF 2.1.0 with `--format sarif`), finding ids are stable, and connections are referenced by name, so agents never handle credentials.
**MCP server.** `culprit mcp` serves Culprit over the Model Context Protocol on stdio (no network port, no token). Tools: `list_connections`, `scan`, `dashboard`, `findings`, `finding`, `top_queries`, `query`, `query_plan`, `plan_insights`, `last_actual_plan`, `query_progress`, `what_changed`, `events`, `cloud_metrics`, `mark`, `explain`, `lint_sql`, `live`, `blocking`, `deadlocks`, `waits`, `schema`, `drift`, `index_advice`, `verify`, `export_finding`, `run_query`. All are read-only except `mark`, which adds a note to the connection's local timeline.
```sh
claude mcp add culprit -- culprit mcp # Claude Code
culprit mcp --connection shop-staging # expose only some connections
```
Cursor (`.cursor/mcp.json`), Codex (`~/.codex/config.toml`, `[mcp_servers.culprit]`) and other clients take the same command: `culprit` with the argument `mcp`.
**What agents may do** is set per connection, in the app (the "Agents" menu on each connection) or with `culprit conn set --agent off|stats|query`:
| Access | Agents can |
|---|---|
| `off` | Nothing; the connection is hidden from them |
| `stats` (default) | Read findings, query statistics, schema, live sessions and estimated plans. Nothing runs your SQL |
| `query` | Also run one read-only statement at a time, each one only after you approve that exact text in the desktop app |
`run_query` refuses anything that isn't a single statement that only reads data. It runs inside a transaction that is never committed (read-only on Postgres and MySQL), returns at most 200 rows and is cancelled after 30 seconds. Approval requests show the agent's name, the connection and the exact SQL; Deny is the default, and they are denied automatically after 60 seconds or when the app isn't open.
**Audit log.** Every tool call is appended to `audit.jsonl` in Culprit's data directory (readable by your user only), with the SQL text for `explain` and `run_query`. `culprit audit` shows the latest entries.
**Set up a repository.** `culprit agent init` writes a short Culprit section into `AGENTS.md`, a Claude Code skill (`.claude/skills/culprit/SKILL.md`) and a `.mcp.json` entry, so agents in that repo use Culprit without being told. It's safe to re-run and writes no findings, host names or secrets; pass `--connection ` to name the connections the project uses.
More in [agents.md](/docs/agents.md).
## Speed
Measured on an Apple-silicon MacBook (macOS 26), release build, empty profile, three launches each, time from process start to the first on-screen window:
| | Launch → window (cold / warm / warm) | Physical memory after 4 s | App size |
|---|---|---|---|
| Culprit (Tauri) | 857 / 277 / 250 ms | ~99 MB across 4 processes | 8.9 MB |
| A popular native macOS database client | 1009 / 267 / 271 ms | ~44 MB in 1 process | 383 MB |
Memory is `phys_footprint` (what macOS charges the app), not RSS, which double-counts shared system frameworks. Culprit's own process is ~28 MB; the rest is the system WebKit that renders the UI (web content ~41 MB, GPU ~23 MB, networking ~7 MB), the fixed cost of a webview UI over a native one.
Reopening a connection renders its last report from disk immediately; a fresh SQL Server scan takes 0.1–0.5 s locally and 2.5–4.5 s against Azure SQL over the internet (1.4K queries, 30 days of Query Store). `CULPRIT_TRACE_STARTUP=1` prints the app's own window-shown time.
## Extending
- **Checks:** implement `culprit_core::Check` and pass it to `culprit_checks::analyze_with` or `Workspace::with_check`; it runs, ranks and locks like a built-in check.
- **Engines:** providers implement `culprit_core::Provider`; built-in ones are cargo features, and `Workspace::with_provider` plugs one in at runtime.
## Safety
- Scans read statistics and catalog views only.
- Statements Culprit runs as reads must be exactly one statement that only reads, checked under every server setting that changes parsing; on SQL Server the server confirms it first by compiling the text without running it. For agents with `query` access on production, use a read-only login: see [agents.md](/docs/agents.md).
- Postgres sessions are read-only with statement and lock timeouts. SQL Server sessions use a short lock timeout, low deadlock priority and read-uncommitted reads of the statistics views.
- Estimated plans never execute anything. Reads run in a read-only transaction everywhere; on production, anything Culprit can't prove reads needs an explicit confirmation each time, and Explain Analyze only measures provable reads.
- Statement text from a database's own history is lexed as exactly one statement before it reaches `EXPLAIN` (MySQL plans go through prepared statements). TLS certificates are verified for every non-local host unless the connection string asks for less.
- Coding agents (`culprit mcp`) read statistics and estimated plans by default. They run statements only on connections you opt in, one approved read-only statement at a time, and every call is audited.
- Fix scripts are shown and copied, never applied. They use `ONLINE = ON` / `CONCURRENTLY` where the server supports it.
- **TLS settings.** New connections show a Connection security section. TLS options in a pasted string populate the controls; an explicit selection overrides them. For an existing connection, use **Edit connection settings** on its card, including connections imported from other tools or discovered through Azure/AWS. Test uses saved credentials without changing the connection; Save changes persists the policy. PostgreSQL/YugabyteDB and MySQL/MariaDB offer their native TLS modes and a CA certificate; SQL Server offers encryption and certificate-trust settings. Token-based authentication requires verified TLS. SQLite uses a local file and has no TLS setting. For a MariaDB server without TLS, select **Disabled · no encryption**, or use `mariadb://user@host:3306/database?ssl-mode=DISABLED` when adding it. Saved settings also live in that connection's `[connections..options]` table in `connections.toml`; update its existing TLS key rather than adding a second spelling.
- Connection metadata (`~/.config/culprit/connections.toml`) and reports (`~/.local/share/culprit/reports/`) are readable by your user only. `CULPRIT_HOME` puts both in one directory.
## Building
Requirements: Rust (stable), Bun.
```sh
cargo build --release -p culprit-cli # target/release/culprit
cd app && bun install && bunx tauri build # desktop app
cd app && bun run dev # UI in a browser, backed by fixtures/*.report.json
```
`cargo test --workspace` runs the unit tests. `dev/postgres` and `dev/mssql` contain reproducible demo databases with planted problems.
### Platforms
- **macOS.** `dev/build-local.sh` builds the app and the CLI and signs both with your Developer ID, so the keychain's "Always Allow" sticks across rebuilds.
- **Linux.** The desktop app needs WebKitGTK; on Debian and Ubuntu: `sudo apt install libwebkit2gtk-4.1-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev librsvg2-dev libayatana-appindicator3-dev libssl-dev libxdo-dev`. `bunx tauri build --bundles deb` makes a `.deb`. Passwords go to the Secret Service (GNOME Keyring, KWallet); on servers, containers and CI, which have none, pass passwords with `--password-env NAME` and set `CULPRIT_KEYCHAIN=off`. Configuration and reports follow the XDG directories (`~/.config/culprit`, `~/.local/share/culprit`).
- **Windows.** Passwords go to Windows Credential Manager, and configuration and reports to `%APPDATA%\culprit`. The Azure and AWS CLIs are run as `az.cmd` and `aws.exe`. `bunx tauri build --bundles msi` makes an installer. Shortcut labels read Ctrl where macOS shows ⌘.
CI (`.github/workflows/ci.yml`) checks formatting, runs clippy and the tests on Linux, macOS and Windows, and builds the desktop app on all three, keeping the unsigned bundles as build artifacts.
## Layout
```
crates/culprit-core model: snapshots, plans, findings; Provider and Check contracts
crates/culprit-checks every check, as a pure function of a snapshot
crates/providers/culprit-mssql SQL Server provider
crates/providers/culprit-postgres PostgreSQL provider and TimescaleDB integration
crates/providers/culprit-yugabyte Native YugabyteDB YSQL/DocDB provider
crates/providers/culprit-mysql MySQL and MariaDB provider
crates/providers/culprit-sqlite SQLite 3 file provider
crates/culprit-querylog framework query log parser (Rails, Django, EF Core, Ecto, JSONL)
crates/authentication/ credential contracts, Azure/Entra and AWS authentication providers
crates/telemetry/ ADX and ClickHouse analytical stores
crates/recovery/ Azure Blob and S3 conditional object recovery
crates/culprit-cloud pluggable cloud discovery and metrics
crates/culprit-collector capture, outbox, fleet scheduling and verified analytical delivery
crates/culprit-read bounded native reads and shared source admission
crates/culprit-engine connection store, credential composition, scans, reports, agent approvals and audit log
crates/culprit-mcp the MCP server for coding agents and `culprit agent init`
crates/culprit-cli the `culprit` binary
app/ React UI and the Tauri shell
docs/DESIGN.md UX and functional design
docs/guide.md this guide
```
---
# Engine parity
Culprit runs one analysis pipeline, workspace model, execution-plan viewer, migration linter, fleet collector and MCP toolset across eight database products. What each scan or capture can prove depends on the measurements that engine records. Select a provider below for connection setup, read-only `GRANT` statements, workload and plan sources, live diagnostics, schema coverage, operational limits and verified releases.
## Providers
| Database | Connection target | Main evidence |
|---|---|---|
| [SQL Server](/docs/providers/mssql.md) | SQL Server, Azure SQL Database, Managed Instance and Amazon RDS | Query Store intervals, plan cache, DMVs, Showplan XML and Extended Events (`.xel` / XML) |
| [PostgreSQL](/docs/providers/postgres.md) | PostgreSQL 15–18, Amazon RDS, Aurora and Azure Flexible Server | `pg_stat_statements`, catalog and I/O views, `EXPLAIN`, `hypopg` and JSON/CSV logs |
| [TimescaleDB](/docs/providers/timescale.md) | PostgreSQL connection; `timescaledb` detected automatically | PostgreSQL sources plus logical hypertable storage, chunk compression and background job views |
| [YugabyteDB](/docs/providers/yugabyte.md) | Dedicated `yugabyte://` / YSQL over DocDB provider | Native YSQL/DocDB RPC counters, `DIST` plans, `yb_pg_stat_plans`, ASH and tablet metadata |
| [MySQL](/docs/providers/mysql.md) | MySQL 5.7–8.4, Amazon RDS, Aurora and Azure Flexible Server | `performance_schema` digests and histograms, `sys`, JSON/tree `EXPLAIN` and slow query log |
| [MariaDB](/docs/providers/mariadb.md) | MySQL / MariaDB connection; MariaDB detected automatically | `performance_schema`, `slow_log` table, `userstat`, `ANALYZE FORMAT=JSON` and Galera status |
| [ClickHouse](/docs/providers/clickhouse.md) | ClickHouse HTTP(S), one database and node per source | Logged initial queries, MergeTree parts and merges, mutations, replication and insert failures |
| [SQLite](/docs/providers/sqlite.md) | Local read-only SQLite file (`query_only`) | Catalog pragmas, bounded `dbstat`, `sqlite_stat1`, `EXPLAIN QUERY PLAN` and framework query logs |
Every provider guide follows the same seven sections:
1. **Connecting** — URLs, TLS defaults, cloud IAM / Entra ID, SSH jump hosts and IDE connection import
2. **Permissions and setup** — Least-privilege read-only `GRANT` SQL and optional server telemetry setup
3. **Workload and plans** — Statement history, runtime spread, estimated vs measured plans and virtual indexes
4. **Live activity and waits** — Active sessions, lock chains, wait sampling, deadlocks and opt-in diagnostics
5. **Schema and indexes** — Catalog inspection, index advice, storage layout and offline SQL migration linting
6. **Limits and evidence** — Connection safety bounds, background collector coverage and strict attribution rules
7. **Verification** — Reproducible Docker/file fixtures, verified server versions and source declarations
## Feature overview
**✓** supported natively · **◐** partial, version-dependent or supplied by an alternate source · **—** not recorded by the engine.
Actual availability always depends on server version, enabled telemetry sources and login privileges.
| Feature | SQL Server | PostgreSQL | TimescaleDB | YugabyteDB | MySQL | MariaDB | SQLite | ClickHouse |
|---|---|---|---|---|---|---|---|---|
| Statement workload | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ◐ query log | ✓ query log |
| Timelines and period comparison | ✓ intervals | ◐ scans | ◐ scans | ◐ matching scans | ◐ scans / slow log | ◐ scans / slow log | — | ◐ logged initial requests |
| Estimated plans / access paths | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ◐ EQP access paths | ✓ physical steps |
| Explicitly measured execution plans | ✓ | ✓ | ✓ | ✓ DIST | ◐ 8.0.18+ | ✓ ANALYZE | — | — |
| Retained last actual execution plan | ◐ 2019+ opt-in | — | — | — | — | — | — | — |
| Virtual indexes (`--with-index`) | — | ✓ `hypopg` | ✓ `hypopg` | ✓ `hypopg` | — | — | — | — |
| Live sessions and blocking chains | ✓ | ✓ | ✓ | ◐ native scoped | ✓ | ✓ | — | ◐ current requests |
| Live statement / operation progress | ✓ operator profiles | ◐ progress views | ◐ progress views | ◐ backfill / COPY | ◐ plan / stages | ◐ SHOW ANALYZE | — | — |
| Recorded waits / activity | ✓ Query Store waits | ◐ timed I/O | ◐ PostgreSQL I/O | ◐ weighted ASH | ◐ counters / lock time | ◐ counters / lock time | — | ◐ focused profile events |
| Live wait sample | ✓ counter deltas | ✓ sessions | ✓ sessions | ✓ sessions | ◐ counters / sessions | ◐ counters / sessions | — | — |
| Deadlock evidence | ✓ `.xel` / XML / XE | ◐ count + JSON/CSV log | ◐ count + JSON/CSV log | — | ◐ latest InnoDB | ◐ latest InnoDB | — | — |
| Index usage and cleanup safety | ✓ | ✓ | ◐ ordinary tables | ◐ global views | ✓ (`INVISIBLE`) | ◐ `performance_schema` / `userstat` (`IGNORED`) | — | — |
| Health, storage and posture | ✓ | ✓ | ◐ logical + PG | ◐ DocDB / nodes | ✓ | ✓ + Galera | ◐ file + WAL | ✓ node-local operational sources |
| Offline SQL migration linting (SARIF) | ✓ | ✓ | ✓ hypertable-aware | ✓ DocDB-aware | ✓ | ✓ | ✓ | — |
| Offline log / `.xel` diagnostics | ✓ `.xel` & XML | ✓ JSON & CSV | ✓ JSON & CSV | — | — | — | ✓ framework / JSONL | — |
| Cloud auth & managed posture | ✓ Entra / Azure / RDS | ✓ AWS IAM / Entra | ◐ PostgreSQL auth | — | ✓ AWS IAM / Entra | ✓ AWS IAM / RDS | — | — |
| Background fleet collector (ADX / CH) | ✓ | ✓ (24 datasets) | ◐ PostgreSQL base | ✓ (16 datasets) | ✓ | ✓ + `mariadb.galera` | ✓ (10 datasets) | ✓ operational + focus |
| SSH jump hosts (`--ssh`) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | — |
Saved scans, offline replay, plan comparison, schema drift, SARIF migration linting (`culprit lint-sql`), Markdown/JSON exports and [MCP agent guardrails](/docs/agents.md) work identically across providers.
## Evidence and missing data
Unavailable or permission-denied sources never silently become `0` or a clean bill of health: Culprit locks only the affected checks and explains which view, extension or `GRANT` was missing. Cumulative counters, sampled sessions, retained event buffers and current storage allocations keep their own timestamps, reset epochs and units.
Per-day rates require at least one hour of dated window (labeled "a day" only after 20 hours), and unused-index verdicts require at least seven days of continuous index-usage counters across every read-serving replica or node. Two-period comparisons verify matching database identity, contributor roster and counter reset history before computing deltas. Read the shared [evidence rules](/docs/providers/coverage.md) for the exact thresholds behind every check.
## Verification
Every provider page documents its verified engine releases, disposable local fixture (`dev/*`), and authoritative source table (`src/sources.rs`). Version-specific fallbacks and managed-cloud restrictions are listed alongside the capabilities they govern.
For CLI commands, Studio workflows and exports, see the [user guide](/docs/guide.md). For the five-stage diagnostic pipeline (`sources → snapshot → prepare → detect → refine → rank`), see [architecture](/docs/architecture.md).
---
# SQL Server
[Engine parity](/docs/parity.md)
Culprit connects to boxed SQL Server (2017–2022+), Azure SQL Database, Azure SQL Managed Instance and Amazon RDS for SQL Server. Query Store supplies time-windowed workload intervals, historical plans and per-query wait categories; when Query Store is off or unreadable, Culprit falls back to the plan cache and DMVs with explicit retention boundaries.
## Connecting
Select **SQL Server** in Culprit SQL Studio or pass an ADO.NET, JDBC or `mssql://` connection string to the CLI. You can also import existing profiles from Azure Data Studio, VS Code (`mssql`), DBeaver or DataGrip with `culprit conn import`.
```sh
# Standard SQL login (password stored in OS keychain)
culprit conn add shop --env prod --url 'Server=tcp:db.example.com,1433;Database=shop;User ID=culprit_reader;Encrypt=strict'
# Azure SQL Database with Microsoft Entra ID (az login, Managed Identity, Workload Identity or device code)
culprit conn add shop-az --env prod --auth entra --url 'Server=tcp:shop.database.windows.net,1433;Database=shop'
# Private subnet via SSH jump host
culprit conn add shop-priv --env prod --ssh bastion@10.0.1.5 --ssh-key ~/.ssh/id_ed25519 \
--url 'Server=tcp:10.0.2.15,1433;Database=shop;User ID=culprit_reader'
```
| Capability | Behavior |
|---|---|
| TLS encryption | `Encrypt=true` by default on remote hosts; TDS 8.0 `Encrypt=strict` supported for SQL Server 2022 and Azure SQL |
| Cloud authentication | Microsoft Entra ID (`az` CLI, device-code flow, Managed Identity and Kubernetes Workload Identity). Amazon RDS SQL Server uses SQL authentication plus optional CloudWatch / RDS posture enrichment (IAM DB auth tokens are not offered by RDS SQL Server) |
| Cloud discovery | Discovers Azure SQL servers/databases/elastic pools and AWS RDS SQL Server instances without touching application tables |
| SSH jump hosts | Built-in SSH tunneling (`--ssh`, `--ssh-port`, `--ssh-key`); see [SSH jump hosts](/docs/ssh.md) |
| Environment safety | Passwords live in the OS keychain; `KILL` and measured plan execution are blocked on `prod` connections unless explicitly permitted |
### Read-only replicas
Save read-scale or Availability Group secondaries as a separate connection with `ApplicationIntent=ReadOnly`. Routing intent asks the listener for a read-only member; it does not prove which physical replica answered, guarantee every secondary was visited, or prevent writes on its own.
| Evidence area | Scope on replicas and secondary populations |
|---|---|
| Query Store history | Shared database catalog with separate native replica groups when secondary Query Store capture (`READ_CAPTURE_SECONDARY`) is enabled. Ordinary scans read the shared history once and persist independent per-population reports |
| Selecting a population | Inspect a specific replica role/group with `culprit scan shop --workload-population `, `culprit changes shop --workload-population `, or Studio's **Query history** population picker. Reports never silently blend primary and secondary populations |
| Activity and waits | Reflects the connected replica's live requests, locks and wait counters. Hyperscale replica continuity checks native database/replica identity and process epoch before linking follow-up reads |
| Retained actual plans | `LAST_QUERY_PLAN_STATS` plans are attached only when native execution-group provenance matches; otherwise the captured plan remains inspectable with its limitation noted |
| Unused-index verdicts | Local `sys.dm_db_index_usage_stats` counters on one member never prove an index is unused on secondaries. Disable/drop advice is withheld unless every read-serving member is covered across at least 7 days |
See Microsoft's [read-scale monitoring](https://learn.microsoft.com/azure/azure-sql/database/read-scale-out#monitor-and-troubleshoot-read-only-replicas) and [Query Store for secondary replicas](https://learn.microsoft.com/sql/relational-databases/performance/query-store-for-secondary-replicas) guides for native replica capture requirements.
## Permissions and setup
Culprit probes effective permissions and Query Store state up front. Missing privileges never fail a scan: unavailable views become explicit coverage notes with the exact `GRANT` needed.
```sql
-- SQL Server 2022+ (least-privilege performance state + plan XML)
USE [master];
CREATE LOGIN [culprit_reader] WITH PASSWORD = '';
GRANT VIEW SERVER PERFORMANCE STATE TO [culprit_reader];
USE [shop];
CREATE USER [culprit_reader] FOR LOGIN [culprit_reader];
GRANT VIEW DATABASE PERFORMANCE STATE TO [culprit_reader];
GRANT SHOWPLAN TO [culprit_reader];
```
- **SQL Server 2017–2019**: Replace the `PERFORMANCE STATE` grants above with `GRANT VIEW SERVER STATE TO [culprit_reader];` in `master` and `GRANT VIEW DATABASE STATE TO [culprit_reader];` in the target database.
- **Azure SQL Database**: Grant `VIEW DATABASE PERFORMANCE STATE` (or `VIEW DATABASE STATE`) and `SHOWPLAN` inside the target user database.
- **Query Store (recommended)**: Enable Query Store with wait capture for time-windowed intervals, plan regression tracking and wait-category attribution:
```sql
ALTER DATABASE [shop] SET QUERY_STORE = ON (
OPERATION_MODE = READ_WRITE,
WAIT_STATS_CAPTURE_MODE = ON
);
```
## Workload and plans
| Capability | SQL Server source and behavior |
|---|---|
| Statement workload | `sys.query_store_runtime_stats` over the selected time window; falls back to `sys.dm_exec_query_stats` plan-cache counters when Query Store is off |
| Period comparison | Native Query Store interval slicing (`culprit scan --since`, `culprit changes`), or saved-scan deltas when reading the plan cache |
| Captured & imported plans | Stored Showplan XML from Query Store / plan cache, plus offline `.sqlplan` and XML import in Studio, CLI and [Culprit Explain](https://explain.culpritsql.com) |
| Estimated vs measured plans | Estimated Showplan never executes user SQL; explicit measured runs use `SET STATISTICS XML ON` inside a rolled-back transaction |
| Retained last actual plan | Reads `sys.dm_exec_query_plan_stats` on SQL Server 2019+ and Azure SQL when `LAST_QUERY_PLAN_STATS = ON` |
| Runtime spread & PSP | Tracks min, avg, max and stdev per plan, preserves SQL Server 2022 Parameter Sensitive Plan (`PSP`) dispatcher-to-variant relationships without double-counting executions, and surfaces Query Store plan-forcing state |
| Compilation & gateways | Reads Query Store compile counts, durations and working memory alongside `RESOURCE_SEMAPHORE_QUERY_COMPILE` waits and Resource Governor gateway thresholds |
Culprit keeps compilation counters, cached plan sizes, execution memory grants and runtime intervals on their own native clocks:
- **Query identity verification**: Compilation metrics link to SQL text only when `query_id`, initial compile timestamp, `query_hash` and context settings match; reused IDs or post-reset counters are never mixed across epochs.
- **Temporary space semantics**: Query Store's tempdb metric represents average 8-KiB pages used weighted by executions—not total written bytes, peak concurrent footprint, or proof of a sort/hash spill.
## Live activity and waits
Live combines `sys.dm_exec_sessions`, `sys.dm_exec_requests`, `sys.dm_tran_active_transactions`, `sys.dm_os_waiting_tasks` and lock views to render active queries, idle-in-transaction blockers, live operator progress (`sys.dm_exec_query_profiles`) and sampled server wait deltas.
- **Schema-lock blocking chains**: On verified SQL Server 2022+ writable primaries, focused blocking analysis traces queued DDL (`Sch-M` / `Sch-S`) back to the upstream transaction holding incompatible locks and lists downstream waiters blocked behind the queued schema change using native lock-resource and task pointers.
- **Wait category discipline**: Query Store wait categories, `THREADPOOL` worker starvation, CPU, compilation and memory-grant waits remain distinct; aggregate wait totals never invent a specific blocking session.
- **System health deadlocks (SQL Server 2017+ & Managed Instance)**: When `system_health` writes to a single absolute local/UNC file path, Culprit reads retained deadlock graphs via catalog metadata without querying `sys.dm_xe_session_targets` (which forces target flushes).
- **Session control**: Outside `prod` connections, Studio exposes `KILL ` (SQL Server provides session termination rather than a separate query-cancel verb).
### Opt-in live & diagnostic readers
Heavy DMV projections are disabled during ordinary scans and Live polling so routine diagnostics stay fast and predictable. Request them explicitly on the CLI (`culprit scan `) or via `culprit collect once --collection `:
| Opt-in reader | CLI scan flag / collector recipe | What it captures and safety bounds |
|---|---|---|
| Observed page-wait targets | `--collect-page-wait-targets` / `page-wait-targets` | Maps up to 8 distinct `PAGELATCH_*` / `PAGEIOLATCH_*` wait pages via `sys.dm_db_page_info(..., 'LIMITED')` (rowstore leaf/branch, heap, PFS/GAM/SGAM) plus up to 8 partition counter points; 18-batch, 1s statement / 5s total budget, gated on Azure SQL resource pressure |
| Current execution memory | `--collect-request-memory` / `current-request-memory` | Captures active/queued `sys.dm_exec_query_memory_grants` reservations, usage, workers and SQL Server 2017+ workload-group tempdb usage/limits; 200-row, 9-query, 3s/10s budget |
| Task-level tempdb space | `--collect-task-space` / `task-space` | Captures `sys.dm_db_task_space_usage` user/internal allocation & deallocation page counters per task; 200-row, 1s/5s budget (see details below) |
| Out-of-memory events | `--collect-memory-failures` / `memory-failures` | Reads up to 128 retained `sys.dm_os_out_of_memory_events` rows on Azure SQL Database & Managed Instance; 3s/10s budget (see details below) |
| Boxed process CPU | `mssql.process-cpu` (collector) | Captures SQLOS user/kernel CPU totals, Resource Governor pool CPU totals and latest scheduler-monitor ring-buffer sample; 10 dispatches max |
| MI resource history | `mssql.mi-resource-stats` (collector) | Streams up to 512 15-second intervals (max 2h window) from `sys.server_resource_stats` on Managed Instance; 1s/5s budget |
### Task-level temporary-space observations
`culprit scan shop --collect-task-space` (and `--collection task-space`) opts into [`sys.dm_db_task_space_usage`](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-task-space-usage-transact-sql) when investigating active `tempdb` growth. Scans support SQL Server, Managed Instance and Azure SQL Database; fleet capture supports Azure SQL Database and boxed SQL Server 2022+ writable primaries.
- **Four exact 8-KiB page counters per task**: User allocations, user deallocations, internal allocations and internal deallocations per `(session_id, request_id, exec_context_id)`.
- **Strict attribution**: Cached temp tables, deferred drop cleanup and earlier statements in the same batch affect task counters. Checked current SQL is attached as an investigation candidate—not proof of peak footprint, spill duration or allocator ownership.
- **Hard ceiling**: Capped at 200 task rows + 1 overflow witness, 1-second statement timeout and 5-second total budget, with no server-side sort, plan XML fetch or OS stack walk.
### Azure SQL deadlock events
For **offline event analysis**—with zero database credentials or server changes—open binary `.xel` or exported XML files directly in **Studio** (**Plans → Open events XML**), drag-and-drop into **[explain.culpritsql.com](https://explain.culpritsql.com)**, run `culprit logs ./events.xel --input-format mssql-xe-xel`, or invoke MCP's `analyze_event_xel` / `analyze_event_xml` tools. Binary `.xel` framing, QPC-derived UTC timestamps, attention/timeout events, errors and multi-victim deadlock graphs are decoded locally in Rust/Wasm.
For **live Azure SQL Database scans**, Culprit **never** reads Azure SQL's internal `dl` session ([Microsoft advises against reading it](https://learn.microsoft.com/en-us/azure/azure-sql/database/xevent-db-diff-from-svr#best-practices) due to availability impact). Instead, an administrator can optionally create this bounded database-scoped ring buffer; Culprit only reads it if it already exists with these exact caps (`<= 1024` KiB, `<= 256` events):
```sql
CREATE EVENT SESSION [culprit_deadlocks] ON DATABASE
ADD EVENT sqlserver.database_xml_deadlock_report (
ACTION (package0.event_sequence)
)
ADD TARGET package0.ring_buffer (
SET max_memory = 1024, max_events_limit = 256
)
WITH (
MAX_MEMORY = 2048 KB,
EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
MAX_DISPATCH_LATENCY = 5 SECONDS,
STARTUP_STATE = ON
);
ALTER EVENT SESSION [culprit_deadlocks] ON DATABASE STATE = START;
```
Ring buffers clear on restart and overwrite oldest entries first, so an empty buffer means zero currently retained events—not proof that no deadlocks ever occurred.
### Retained out-of-memory observations
`culprit scan shop --collect-memory-failures` (and `--collection memory-failures`) reads [`sys.dm_os_out_of_memory_events`](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-os-out-of-memory-events?view=azuresqldb-current) on **Azure SQL Database** and **Azure SQL Managed Instance** (boxed SQL Server is excluded because Microsoft marks the view unsupported there).
- **Shared hosting scope**: Reports instance-wide (Managed Instance) or elastic-pool / hosting-level memory events rather than blaming the current database or a specific query.
- **Bounded projection**: Reads at most 128 rows without server-side sorting, joins or JSON parsing inside a 3-second statement / 10-second total budget, keeping offset-free native event timestamps separate from UTC capture bounds.
## Schema and indexes
Catalog and DMV readers inspect tables, columns, constraints, statistics (`DBCC` is never executed), persisted columnstore configuration (compression delay, ordered columns), partition functions/schemes, triggers, index definitions, `sys.dm_db_index_usage_stats` and optimizer missing-index DMVs.
- **Reversible index cleanup**: Eligible unused nonclustered indexes (verified over `>= 7` days across all readable replicas, excluding clustered, unique and constraint-backing indexes) recommend `ALTER INDEX ... DISABLE` first—stopping write maintenance while keeping metadata intact so `ALTER INDEX ... REBUILD` can restore it instantly.
- **Offline SQL migration linting**: `culprit lint-sql migrations/ --format sarif` (and `--write` safe autofixes) checks T-SQL DDL for table-locking rewrites, missing `ONLINE = ON` / `LOCK_TIMEOUT` guards, unindexed foreign keys and destructive changes in CI or VS Code.
- **Opt-in schema & operational collector datasets**: Beyond core schema/workload polling, `culprit collect` supports bounded targeted captures for `objects`, `triggers`, `partitions`, `cached-definitions`, `retained-plans`, `query-compilation`, `cached-runtime`, `columnstore-rowgroups`, `backup-history`, `agent-jobs`, `cdc`, `change-feed`, `hyperscale-log-components`, `suspect-pages`, `full-text-populations`, `table-memory`, `numa-nodes` and `tempdb-metadata-memory` (`sys.dm_db_xtp_memory_consumers` on SQL Server 2022+). Every capture replay works offline via CLI and MCP `analyze_capture`.
## Limits and evidence
- **Session guardrails**: Every monitoring connection sets `LOCK_TIMEOUT 2000`, `DEADLOCK_PRIORITY LOW` and `READ UNCOMMITTED` where appropriate, tags every query with `/* culprit */` so Culprit's own SQL is excluded from workload findings, and never replays timed-out batches automatically.
- **Confirmed cancellation**: Background telemetry owns each TDS connection until completion or confirmed cancellation; if driver cancellation remains uncertain, the workspace fences further background polls rather than leaking orphaned sessions.
- **Azure SQL pressure admission**: Heavy background recipes verify database CPU, instance CPU, worker %, data I/O and log-write pressure before running and abort immediately when pressure is elevated.
- **Operational scope**: Transaction log occupancy (`log_reuse_wait_desc`), filegroup space, shared `tempdb` user/internal/version-store allocation, last recorded `DBCC CHECKDB` timestamp (`DATABASEPROPERTYEX`, never running `DBCC CHECKDB`), and identity/sequence exhaustion bounds keep their exact database vs instance scope. See the shared [evidence rules](/docs/providers/coverage.md) and [collector source coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md).
## Verification
Exercised against **SQL Server 2022** and **Azure SQL Database**, with saved snapshots, `.sqlplan` / `.xel` corpora and offline golden replay tests. Spin up the local Docker fixture with planted indexing, parameter-sensitivity, blocking and deadlock scenarios in [`dev/mssql/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/mssql/README.md).
All declared SQL Server sources and capability locks live in [`culprit-mssql/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-mssql/src/sources.rs).
---
# PostgreSQL
[Engine parity](/docs/parity.md)
Culprit inspects self-hosted PostgreSQL, Amazon RDS, Amazon Aurora PostgreSQL, Azure Database for PostgreSQL Flexible Server and Google Cloud SQL using read-only catalog and statistics views. Cumulative workload history comes from `pg_stat_statements` paired with Culprit's saved scans for clean time-window deltas.
## Connecting
Select **PostgreSQL** in Studio or supply a `postgres://` URL, `libpq` key-value string or JDBC URL on the CLI. Existing connections from DBeaver, DataGrip, pgAdmin or VS Code can be imported with `culprit conn import`.
```sh
# Standard connection (remote TLS defaults to sslmode=verify-full)
culprit conn add shop --env prod --url 'postgres://culprit_reader@db.example.com:5432/shop'
# Amazon RDS / Aurora PostgreSQL with short-lived AWS IAM auth token
culprit conn add shop-rds --env prod --auth aws-iam --url 'postgres://culprit_reader@shop.cluster-xyz.us-east-1.rds.amazonaws.com:5432/shop'
# Azure Database for PostgreSQL with Microsoft Entra ID
culprit conn add shop-az --env prod --auth entra --url 'postgres://culprit_reader@shop.postgres.database.azure.com:5432/shop'
# Through an SSH jump host
culprit conn add shop-priv --env prod --ssh ubuntu@bastion.example.com --url 'postgres://culprit_reader@10.0.4.12:5432/shop'
```
- **TLS & credentials**: Passwords stay in the OS keychain; AWS IAM (`--auth aws-iam`) and Microsoft Entra ID (`--auth entra`) mint short-lived tokens per session. Managed cloud posture (RDS parameters, CloudWatch metrics, unencrypted session checks via `pg_stat_ssl`) enriches health views when cloud access is configured.
- **Engine routing**: [TimescaleDB](/docs/providers/timescale.md) uses this provider and is detected automatically when the `timescaledb` extension is installed. [YugabyteDB](/docs/providers/yugabyte.md) uses its own dedicated provider (`--engine yugabyte`); connecting to YugabyteDB with the PostgreSQL provider stops cleanly before calling heap storage APIs.
## Permissions and setup
Grant PostgreSQL's built-in `pg_read_all_stats` role (or `pg_monitor`) so Culprit can read query texts across roles and inspect session/storage statistics without superuser access:
```sql
CREATE ROLE culprit_reader WITH LOGIN PASSWORD '';
GRANT CONNECT ON DATABASE shop TO culprit_reader;
GRANT pg_read_all_stats TO culprit_reader;
-- Run inside the target database for workload history and zero-cost virtual index testing:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS hypopg;
```
- **Recommended server settings**: Enable `track_io_timing = on` (data-file and temp I/O timings) and `pg_stat_statements.track_planning = on` (planner overhead) when permitted. On managed services such as RDS where `ALTER SYSTEM` is unavailable, Culprit emits safe database-scoped tuning advice (`ALTER DATABASE shop SET ...`) where applicable.
- **Privilege-safe `EXPLAIN`**: Planning a query in PostgreSQL can invoke immutable/inlined SQL or PL/pgSQL functions. Culprit refuses elevated generic planning when untrusted roles' reachable functions could execute with the monitoring role's privileges, and always wraps plan checks in read-only transactions that roll back.
## Workload and plans
| Capability | PostgreSQL source and behavior |
|---|---|
| Statement statistics | Cumulative `pg_stat_statements` calls, total/min/max/mean/stddev time, rows, shared/local/temp blocks, I/O timings, WAL bytes, planning and JIT counters |
| Period comparison | Computes exact deltas between Culprit's saved scans (`culprit changes`) after verifying matching database identity and `pg_stat_statements_info.stats_reset` |
| Automatic plan capture | Safe generic plans via `EXPLAIN (GENERIC_PLAN)` on PostgreSQL 16+ or prepared-statement generic plans on PostgreSQL 12–15 |
| Measured plans | `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` run on explicit user request inside a rolled-back read-only transaction |
| Virtual indexes (`hypopg`) | Tests candidate indexes in backend memory (`culprit explain shop --sql '...' --with-index 'CREATE INDEX ON orders (customer_id)'`) without touching disk or locking tables |
| Plan import | Renders JSON and text `EXPLAIN` plans (including `psql` output) in Studio, CLI and [explain.culpritsql.com](https://explain.culpritsql.com) |
| Statement families | Groups normalized queries that differ only by `IN (...)` or `VALUES (...)` list lengths |
Temporary file block reads/writes (`temp_blks_read`, `temp_blks_written`) and `temp_blk_read_time` / `temp_blk_write_time` are projected in the primary statement read with their exact block size—never extrapolated into guessed disk throughput or `work_mem` formulas without actual plan spill evidence.
## Live activity and waits
Live combines `pg_stat_activity`, `pg_blocking_pids()`, lock catalogs and `pg_stat_progress_*` (`vacuum`, `analyze`, `create_index`, `cluster`, `copy`, `basebackup`) to display active queries, idle-in-transaction blockers, live wait-event sampling (1 Hz over active sessions) and operation progress.
- **Blocking & lock closure**: Focused blocking analysis verifies PostgreSQL's system identifier, server address/port, PID, `backend_start`, `xact_start` and query token before and after capturing bounded lock wait chains.
- **Session actions**: Outside `prod` connections, Studio exposes both `pg_cancel_backend` (cancel current query) and `pg_terminate_backend` (close connection).
- **Deadlock history & structured logs**: `pg_stat_database.deadlocks` tracks cumulative count; full participant lock graphs and SQLSTATE failures are decoded offline from PostgreSQL JSON (`jsonlog`) or CSV (`csvlog`) server logs without needing database credentials or `pg_read_file`:
```sh
# Offline analysis of PostgreSQL 15+ jsonlog or PostgreSQL 14+ 26-column csvlog (use csv13 for PG 13)
culprit logs ./postgresql.jsonl --input-format json --json
culprit logs ./postgresql.csv --input-format csv
```
`culprit logs` classifies SQLSTATE conditions (`40P01` deadlocks with reconstructed participant lock edges, `53200` OOM, `57014` query canceled, `25P04` idle-in-transaction timeout, lock/connection exhaustion), redacts SQL literals, omits free-form detail text, and caps single-pass reads at 1 MiB / 1,024 records by default.
## Schema and indexes
Catalog and statistics readers inspect tables, partitions, columns, constraints, extended statistics, index definitions, `pg_stat_user_tables`, `pg_stat_user_indexes`, `pg_statio_user_*`, PostgreSQL 16+ `pg_stat_io`, and PostgreSQL 17+ `pg_stat_checkpointer`.
- **PostgreSQL-native index advice**: Candidate indexes come from plan filter/join/sort operators, unindexed foreign keys and sequential-scan evidence—validated in milliseconds when `hypopg` is installed. DDL uses `CREATE INDEX CONCURRENTLY` and `DROP INDEX CONCURRENTLY` on ordinary tables, and distinguishes invalid (`!indisvalid`) remnants from active or disabled indexes.
- **Storage, vacuum & wraparound health**: Evaluates dead-tuple bloat, autovacuum lag and per-table freeze/MultiXact age (`relfrozenxid`, `relminmxid`), HOT update ratios blocked by indexed columns, sequence exhaustion (`pg_sequences`), replication slot `xmin` / `catalog_xmin` retention, WAL archiver failures (`pg_stat_archiver`), standby recovery conflicts and PostgreSQL 15+ logical subscription errors.
- **Offline SQL migration linting**: `culprit lint-sql migrations/ --format sarif` catches non-concurrent index builds, volatile column defaults, missing `lock_timeout` guards, unvalidated `ADD CONSTRAINT` table scans and unsafe type rewrites before deployment.
## Limits and evidence
### Connection safety and wire bounds
Every scan, probe, plan capture and collector poll shares one owned PostgreSQL wire reader with strict guardrails:
| Guardrail | Limit |
|---|---|
| Session posture | `SET default_transaction_read_only = on`, catalog-only `search_path`, `lock_timeout = '2s'`, parallel workers disabled for catalog queries |
| Statement timeouts | `20s` for scan/collector reads; `10s` for interactive enrichments |
| Result caps | `10,000` rows and `8 MiB` payload per query; `512` batches and `60s` ceiling across a full parallel snapshot |
| Cancellation fencing | Interrupted sessions are drained to `ReadyForQuery` or retired without automatic retry; unconfirmed shutdowns fence subsequent background polls |
### Background telemetry (`culprit collect`)
The fleet collector exports **24 `postgres.*` telemetry recipes** to Azure Data Explorer (ADX) or ClickHouse—covering statement counters (polled separately from redacted SQL text), bounded catalog fingerprints, table/index/I/O stats, persistent blocking activity and instance posture without running `EXPLAIN` or reading user table rows. See [PostgreSQL collector coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#postgresql-source-coverage).
PostgreSQL heap/buffer rules never carry over to engines that merely speak the PostgreSQL wire protocol. Cumulative counters are never treated as reset on simple postmaster restart unless `stats_reset` changed, per-day rates require dated history, and unused-index verdicts require at least 7 days of continuous counters. See the shared [evidence rules](/docs/providers/coverage.md).
## Verification
Exercised across **PostgreSQL 15–18** (including Amazon RDS and saved PostgreSQL 18.6 fixtures). Reproduce workload, bloat, wraparound, foreign-key and lock-contention scenarios locally with [`dev/postgres/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/postgres/README.md).
All declared PostgreSQL sources live in [`culprit-postgres/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-postgres/src/sources.rs). References: [PostgreSQL routine vacuuming & MultiXacts](https://www.postgresql.org/docs/18/routine-vacuuming.html), [`pg_sequences`](https://www.postgresql.org/docs/18/view-pg-sequences.html), and [JSON/CSV structured logging](https://www.postgresql.org/docs/18/runtime-config-logging.html#RUNTIME-CONFIG-LOGGING-JSONLOG).
---
# TimescaleDB
[Engine parity](/docs/parity.md)
Culprit detects TimescaleDB automatically through its PostgreSQL provider and queries the extension's public catalog views and size functions directly—keeping logical hypertables, compressed columnstore chunks, continuous aggregates and background jobs distinct from ordinary PostgreSQL heaps.
## Connecting
Choose **PostgreSQL** in Studio or on the CLI when connecting to self-hosted TimescaleDB or Tiger Cloud. Culprit detects the installed `timescaledb` extension and displays both the TimescaleDB and PostgreSQL versions.
```sh
# Self-hosted TimescaleDB or Tiger Cloud (TLS defaults to sslmode=verify-full)
culprit conn add metrics --env prod --url 'postgres://culprit_reader@tsdb.example.com:5432/metrics'
# Through an SSH jump host
culprit conn add metrics-priv --env prod --ssh bastion@10.0.1.5 --url 'postgres://culprit_reader@10.0.3.20:5432/metrics'
```
Connection store credentials, OS keychain secrets, SSH jump hosts (`--ssh`), IDE connection imports (`culprit conn import`), live sessions, `EXPLAIN` and saved-scan comparisons work identically to the [PostgreSQL provider](/docs/providers/postgres.md).
## Permissions and setup
Grant PostgreSQL's read-only statistics role plus `USAGE` / `SELECT` on TimescaleDB's public informational views and size functions:
```sql
CREATE ROLE culprit_reader WITH LOGIN PASSWORD '';
GRANT CONNECT ON DATABASE metrics TO culprit_reader;
GRANT pg_read_all_stats TO culprit_reader;
-- Inside the target database (if workload history or virtual index testing is needed):
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS hypopg;
```
- **Non-intrusive discovery**: Culprit inspects the existing `timescaledb` extension and its schema; if a view or size function is restricted, only that TimescaleDB capability is marked unavailable with a clear note. Culprit never installs extensions, alters compression/retention policies, or triggers background jobs.
- **Job history visibility**: Note that PostgreSQL's `pg_monitor` / `pg_read_all_stats` roles alone do not bypass TimescaleDB's owner filtering on some job history views—partial visibility is labeled explicitly rather than reported as zero failures.
## Workload and plans
Statement counters, query fingerprints, saved-scan deltas, virtual index testing (`hypopg`) and JSON/CSV server-log diagnostics use the [PostgreSQL workload sources](/docs/providers/postgres.md#workload-and-plans). Counter windows reflect `pg_stat_statements` history—never an interval guessed from chunk creation dates.
- **Chunk-to-hypertable plan attribution**: During `EXPLAIN` and plan analysis, Culprit resolves physical `_timescaledb_internal` chunk scans back to their owning logical hypertable so findings and index candidates point to the table engineers actually maintain.
- **Safe unknowns**: If an internal chunk cannot be mapped to a readable hypertable catalog entry, Culprit withholds generated DDL rather than emitting an index script against an internal chunk table.
## Live activity and waits
Live sessions, lock-wait graphs, 1 Hz session wait sampling, progress views and non-production cancel/terminate actions use the [PostgreSQL live sources](/docs/providers/postgres.md#live-activity-and-waits). Deadlock counts come from `pg_stat_database`, and full deadlock graphs can be decoded offline from PostgreSQL JSON/CSV logs via `culprit logs`.
### Background jobs
Opt into TimescaleDB background-job and continuous-aggregate diagnostics during a scan (`culprit scan metrics --collect-native-failures`) or a targeted capture (`culprit collect once metrics --collection jobs`):
| View / catalog | Captured facts and bounds |
|---|---|
| `timescaledb_information.jobs` & `job_stats` | Schedules, current state, total runs and exact failure counters (up to 256 job rows) |
| `job_history` & `job_errors` | Recent retained outcomes and error codes when installed on the server version (up to 256 run rows) |
| `continuous_aggregates` | View/source/materialization names plus `materialized_only`, compression and granular-refresh flags (up to 64 rows; [catalog reference](https://www.tigerdata.com/docs/reference/timescaledb/informational-views/continuous_aggregates)) |
- **Strict read budget**: Capped at 512 total rows across all views inside a 1-second statement timeout and 5-second total deadline. Culprit probes column availability before querying and never reads view SQL definitions, watermark functions or user rows.
- **Offline inspection**: View captured job health in Studio under **Health**, on the CLI via `--analysis jobs`, or through MCP's `waits` summary. Configuration flags describe current catalog settings—not refresh lag or worker ownership.
## Schema and indexes
Culprit queries `timescaledb_information.hypertables`, `dimensions` and `chunks`, together with `approximate_row_count()`, `hypertable_detailed_size()`, `chunks_detailed_size()` and `hypertable_index_size()` in the extension's schema:
- **Unified logical hypertable view**: Studio's **Schema** browser lists each hypertable once, aggregating estimated rows and storage across all rowstore and compressed columnstore chunks. Expand **Managed chunks** to inspect per-chunk sizes, row estimates and compression state (paginated 20 chunks at a time).
- **Hypertable-aware index DDL & `lint-sql`**: PostgreSQL rejects `CREATE INDEX CONCURRENTLY` on hypertables. Both the index advisor and `culprit lint-sql` emit `CREATE INDEX ... ON hypertable (...) WITH (timescaledb.transaction_per_chunk)` for non-unique hypertable indexes while keeping `CONCURRENTLY` for ordinary tables, and verify that unique indexes include all partitioning dimensions. Note that [per-chunk index builds](https://github.com/timescale/Tiger-Data-Docs/blob/main/src/content/docs/reference/timescaledb/hypertables/create_index.mdx) still lock the active chunk being built.
## Limits and evidence
- **No false "unused index" claims on hypertables**: Parent hypertable entries in `pg_stat_user_tables` and `pg_stat_user_indexes` stay at zero because reads/writes hit child chunks. Culprit marks logical hypertable scan/usage counters unknown instead of flagging parent indexes as unused or grading empty parent heaps for bloat.
- **Internal schemas excluded**: `_timescaledb_*` backing tables, compressed chunk relations and continuous-aggregate materialization tables are excluded from standalone schema/maintenance findings.
- **Graceful partial coverage**: If `timescaledb_information.hypertables` is unreadable, Culprit withholds table/index storage grades and suppresses `CONCURRENTLY` DDL on unresolved relations rather than treating hypertables as empty heaps.
- **DDL export & background collector**: Studio's DDL tab notes that recreating a hypertable requires `create_hypertable()` and policy exports rather than plain `CREATE TABLE`. Background `culprit collect` shares PostgreSQL's bounded wire reader for native relation metrics (without aggregating logical hypertable sizes in background polls); see [collector source coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#other-provider-source-coverage) and the shared [evidence rules](/docs/providers/coverage.md).
## Verification
Verified against **TimescaleDB 2.31.0** on **PostgreSQL 17.11** using `public.sensor_readings` (**120,000 rows across 14 chunks, 7 compressed**) alongside ordinary heap tables (`fixtures/timescale-demo.report.json`). Reproduce the database workload and background-job test cases locally:
- Disposable database & compression fixture: [`dev/timescale/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/timescale/README.md)
- Retained job-failure & permission test cases: [`dev/timescale/jobs.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/timescale/jobs.md)
- Extension reader implementation: [`culprit-postgres/src/timescale.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-postgres/src/timescale.rs)
- Live fixture screenshots: [TimescaleDB dashboard](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/timescale-dashboard.png) · [Hypertable with rowstore and compressed chunks](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/timescale-hypertable.png)
---
# YugabyteDB
[Engine parity](/docs/parity.md)
Culprit ships a dedicated **YugabyteDB** provider (`crates/providers/culprit-yugabyte`) built specifically for YSQL over DocDB. While YSQL speaks the PostgreSQL wire protocol, Culprit never applies PostgreSQL heap, buffer-cache, `VACUUM` or wraparound assumptions to DocDB's distributed LSM/tablet storage.
## Connecting
Select **YugabyteDB** in Studio or pass `--engine yugabyte` (`ysql` and `yugabytedb` are accepted aliases) or a `yugabyte://` URL on the CLI. Defaults are port `5433` and user/database `yugabyte`.
```sh
# Direct YSQL node connection (remote TLS verifies server certificates by default)
culprit conn add shop --env prod --url 'yugabyte://culprit_reader@yb-1.example.com:5433/shop'
# Private YugabyteDB cluster through an SSH jump host
culprit conn add shop-priv --env prod --ssh ops@bastion.example.com --url 'yugabyte://culprit_reader@10.0.8.11:5433/shop'
```
- **Automatic engine guard**: If you accidentally connect to YugabyteDB using the PostgreSQL provider, Culprit detects YSQL during the lightweight probe (before touching storage APIs) and prompts you to switch to **YugabyteDB**.
- **Direct YSQL backend vs Connection Manager**: Session-state operations (such as virtual index testing with `hypopg` and targeted session actions) verify a direct YSQL backend and refuse multiplexed YugabyteDB Connection Manager workers. Cloud IAM/Entra bearer tokens are refused on this provider.
## Permissions and setup
Grant `pg_read_all_stats` for full statement, plan-cache and ASH visibility across roles, and optionally `yb_db_admin` if you want host CPU/memory and TServer memory-tracker metrics:
```sql
CREATE ROLE culprit_reader WITH LOGIN PASSWORD '';
GRANT CONNECT ON DATABASE shop TO culprit_reader;
GRANT pg_read_all_stats TO culprit_reader;
-- Optional: enables yb_servers_metrics() shared node CPU & TServer memory limits
GRANT yb_db_admin TO culprit_reader;
```
### Node-local vs cluster-wide statistics
By default, YSQL statistics (`pg_stat_statements`, `pg_stat_activity`, index counters) are **node-local** to the TServer you connect to, and Culprit labels that scope clearly. If an administrator has enabled YugabyteDB's [cluster-wide database views](https://docs.yugabyte.com/stable/launch-and-manage/monitor-and-alert/cluster-wide-db-views/) outside Culprit, the provider reads them automatically and verifies every node's contributor status and reset epoch.
To expose cluster-wide reset timestamps and metric settings alongside global statement views, an administrator can create these superuser-owned views on `yb_global_views_server`:
```sql
SELECT yb_create_global_view('public', 'pg_stat_statements_info');
SELECT yb_create_global_view('public', 'pg_settings');
```
**Important `yb_pg_stat_plans` privilege guard**: On verified YugabyteDB **2026.1.2.0-b137**, reading `yb_pg_stat_plans` without an **effective** (inherited) `pg_read_all_stats` or superuser privilege crashes that YSQL backend inside `yb_pg_stat_plans_get_all_entries`. Culprit checks effective privileges before touching the plan cache and skips it cleanly when unprivileged.
## Workload and plans
| Capability | YugabyteDB source and behavior |
|---|---|
| Statement workload | Database-filtered `pg_stat_statements` aggregated by query identity (up to 8 MiB streamed without full latency-histogram expansion) |
| DocDB native costs | Storage read/write RPCs, DocDB rows scanned, RocksDB/LSM traversal counters, retries and storage timings (when enabled across all contributing nodes) |
| Automatic & retained plans | Safe generic YSQL `EXPLAIN` estimates plus retained [Query Plan Management (`yb_pg_stat_plans`)](https://docs.yugabyte.com/stable/launch-and-manage/monitor-and-alert/query-tuning/query-plan-manage/) JSON trees, execution counts and first/last-use timestamps |
| Measured `DIST` plans | Explicit `EXPLAIN (ANALYZE, DIST, VERBOSE, FORMAT JSON)` inside a rolled-back transaction, normalizing per-loop `DIST` RPC and storage metrics |
| Virtual indexes (`hypopg`) | `culprit explain shop --sql '...' --with-index 'CREATE INDEX ON public.orders (customer_id ASC)'` on a direct YSQL backend; resets `hypopg` and closes the session afterward |
| Plan import | Automatically recognizes YugabyteDB `DIST` / storage markers in JSON plans in Studio, CLI and [explain.culpritsql.com](https://explain.culpritsql.com) |
Retained `yb_pg_stat_plans` entries keep their own independent cache lifetime and reset epoch (tagged Culprit queries opt out of QPM tracking). Selected cached plan bodies are embedded into saved `.culprit` scans so they remain inspectable offline even after cache eviction.
## Live activity and waits
| Capability | YugabyteDB source and behavior |
|---|---|
| Live sessions & locks | Current-database sessions paired with `yb_lock_status` contention evidence (capped at 1,000 sessions / 2,000 waits); session IDs are node-qualified (`<32-hex-node-uuid>//`) |
| Recorded activity (ASH) | Reads [native Active Session History](https://docs.yugabyte.com/stable/launch-and-manage/monitor-and-alert/active-session-history-monitor/) inverse-sampling weights, wait components, observation nodes and query IDs (up to 10,000 samples / 8 MiB) |
| Unexpected terminations | Reads [`yb_terminated_queries`](https://docs.yugabyte.com/stable/explore/observability/yb-pg-stat-get-queries/) for backend crashes (`SIGKILL` / `SIGSEGV`) and temp-file limit aborts (up to 1,000 rows, 10s deadline; SQL/PIDs omitted) |
| Shared node resources | Calls `yb_servers_metrics()` (when granted `yb_db_admin`) for per-node CPU user/system fractions, host RAM and TServer root memory-tracker soft/hard limits |
| Live command progress | Tracks [index backfill](https://docs.yugabyte.com/stable/explore/ysql-language-features/indexes-constraints/index-backfill/) rows, `ANALYZE` phases and active `IN PROGRESS` `COPY` counters after verifying current SQL and backend identity |
- **ASH weight discipline**: ASH weights measure sampled active task presence—not elapsed query duration, exclusive wait share or host CPU %.
- **Distributed deadlocks**: Live `yb_lock_status` shows active lock waits, whereas retrospective distributed deadlocks surface as `40P01` errors in application / `yb-tserver` logs rather than PostgreSQL's heap deadlock counter.
## Schema and indexes
Catalog inspection covers tables, logical row estimates, columns, defaults, foreign keys, secondary indexes, **HASH vs ASC/DESC range key columns**, **tablet counts** and **colocation** metadata.
- **DocDB-aware index advice & `lint-sql`**: Distinguishes `HASH` sharding columns from ordered `ASC` / `DESC` range prefixes when detecting redundant indexes, covering lookups and schema drift. Repair scripts wait for active index backfills before touching invalid indexes, and `culprit lint-sql` validates YSQL migrations offline.
- **Unvalidated constraints**: Flags `NOT VALID` `CHECK` and foreign-key constraints on existing data with version-appropriate validation guidance.
- **Cluster-safe unused-index rules**: Culprit never calls an index unused from a single node's zero counter or a `NULL` global reset date—every contributing node in the cluster must prove at least 7 days of continuous counter history.
## Limits and evidence
| Boundary | How Culprit handles it on YugabyteDB |
|---|---|
| No PostgreSQL heap myths | Heap bloat, buffer hit ratios, dead tuples, HOT updates, autovacuum, XID/MultiXact wraparound and `ALTER SYSTEM` heap GUCs are disabled by design; database tuning suggestions are restricted to the 5 supported `ALTER DATABASE` YSQL settings |
| Sequence exhaustion | `pg_sequences.last_value` returns `NULL` in YSQL rather than reading DocDB sequence slabs, and Culprit never calls `nextval()`; sequence headroom stays unknown rather than guessed |
| Plan capture budgets | Capped at `20s` and `8 MiB` across estimated and retained `yb_pg_stat_plans` bodies (`--plans 0` skips bodies); uncalibrated YSQL optimizer costs never trigger findings without measured work |
| Multi-node comparisons | Saved-scan deltas (`culprit changes`) require identical contributing node sets and uninterrupted per-node reset timestamps; skipped or restarted nodes mark comparisons partial |
| Background telemetry | `culprit collect` ships **16 dedicated `yugabyte.*` recipes** (workload counters, QPM metadata, ASH, terminations, node resources, DocDB locks and catalog fingerprints) over the owned wire reader; see [collector source coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#other-provider-source-coverage) and [evidence rules](/docs/providers/coverage.md) |
## Verification
Verified against a three-node **YugabyteDB 2026.1.2.0-b137** cluster (`15.12-YB-2026.1.2.0-b0`), exercising global-view aggregation, independent node resets, paused/degraded node fault injection and recovery, `yb_db_admin` permission boundaries, `hypopg` virtual indexes and Connection Manager worker refusal.
- Reproducible 3-node cluster & workload suite: [`dev/yugabyte/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/yugabyte/README.md)
- Declared YugabyteDB sources: [`culprit-yugabyte/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-yugabyte/src/sources.rs)
- Verified UI captures: [Dashboard](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-dashboard.png) · [Recorded ASH activity](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-activity.png) · [Terminated queries](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-terminations.png) · [Shared node resources](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-resources.png) · [DocDB query metrics](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-queries.png) · [Retained QPM plan history](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-history.png) · [Hash keys & tablet schema](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/yugabyte-schema.png)
---
# MySQL
[Engine parity](/docs/parity.md)
Culprit inspects self-hosted MySQL (5.7–8.4), Amazon RDS for MySQL, Amazon Aurora MySQL, Azure Database for MySQL Flexible Server and Google Cloud SQL using `performance_schema`, `sys`, `information_schema` and `EXPLAIN`. When `performance_schema` digests are disabled, a readable `mysql.slow_log` table supplies a no-restart workload fallback. [MariaDB](/docs/providers/mariadb.md) shares the wire transport with its own dedicated plan, statistics and Galera handling.
## Connecting
Choose **MySQL / MariaDB** in Studio or pass a `mysql://` URL, JDBC / ADO.NET string or host/port on the CLI. Existing profiles from DBeaver, DataGrip or VS Code can be imported via `culprit conn import`.
```sh
# Standard MySQL connection (remote TLS defaults to VERIFY_IDENTITY)
culprit conn add shop --env prod --url 'mysql://culprit_reader@db.example.com:3306/shop'
# Amazon RDS / Aurora MySQL with AWS IAM authentication token
culprit conn add shop-rds --env prod --auth aws-iam --url 'mysql://culprit_reader@shop.cluster-xyz.us-east-1.rds.amazonaws.com:3306/shop'
# Azure Database for MySQL Flexible Server with Microsoft Entra ID
culprit conn add shop-az --env prod --auth entra --url 'mysql://culprit_reader@shop.mysql.database.azure.com:3306/shop'
# Private instance through an SSH jump host
culprit conn add shop-priv --env prod --ssh ubuntu@bastion.example.com --url 'mysql://culprit_reader@10.0.5.21:3306/shop'
```
Passwords remain in the OS keychain; AWS IAM (`--auth aws-iam`) and Entra ID (`--auth entra`) generate short-lived tokens automatically. Cloud posture checks inspect RDS/Azure configuration and unencrypted client connections (`performance_schema.session_status` / threads) where readable.
## Permissions and setup
Grant read-only monitoring privileges (`PROCESS` plus `SELECT` on `performance_schema`, `sys` and the target schema):
```sql
CREATE USER 'culprit_reader'@'%' IDENTIFIED BY '';
GRANT PROCESS, REPLICATION CLIENT ON *.* TO 'culprit_reader'@'%';
GRANT SELECT ON performance_schema.* TO 'culprit_reader'@'%';
GRANT SELECT ON sys.* TO 'culprit_reader'@'%';
GRANT SELECT ON `shop`.* TO 'culprit_reader'@'%';
-- Optional: if using table-based slow query log fallback when performance_schema is off
GRANT SELECT ON mysql.slow_log TO 'culprit_reader'@'%';
```
To recover full SQL samples on older setups where digest sample columns are absent or empty, ensure statement-history consumers are enabled:
```sql
UPDATE performance_schema.setup_consumers
SET ENABLED = 'YES'
WHERE NAME IN ('events_statements_current', 'events_statements_history', 'events_statements_history_long');
```
Culprit never modifies `setup_consumers`, `setup_instruments` or global variables itself; when MySQL 8.0+ configuration changes are recommended, Culprit surfaces `SET PERSIST` statements for an operator to review.
## Workload and plans
| Capability | MySQL source and behavior |
|---|---|
| Statement statistics | `performance_schema.events_statements_summary_by_digest` (counts, timers, rows, tmp tables, sort passes, index/no-index scans), or grouped runs from `mysql.slow_log` |
| Period comparison | Saved-scan deltas across digest snapshots (`culprit changes`), or native run timestamps when reading `mysql.slow_log` |
| Captured SQL samples | Digest `QUERY_SAMPLE_TEXT` on MySQL 8.0.3+, falling back to statement-history consumers or `slow_log` samples |
| Estimated & measured plans | `EXPLAIN FORMAT=JSON` (both v1 and MySQL 8.0/8.4 JSON v2) and `FORMAT=TREE`; explicit measured runs use `EXPLAIN ANALYZE` on MySQL 8.0.18+ inside a rolled-back read-only transaction |
| Plan import | Renders JSON and `EXPLAIN ANALYZE` tree plans in Studio, CLI and [explain.culpritsql.com](https://explain.culpritsql.com) |
| Runtime spread & tails | Digest min/avg/max plus MySQL 8.0.19+ per-digest latency histograms (`events_statements_histogram_by_digest`) |
Digest quantiles, native latency histograms and `slow_log` samples keep their own independent sample counts and reset epochs. Internal temporary table counts, on-disk temporary table counts and sort-merge passes are projected directly from the digest summary without guessing spilled byte volumes or sizing `tmp_table_size`.
## Live activity and waits
Live combines `PROCESSLIST`, `information_schema.INNODB_TRX` and lock-wait views (`performance_schema.data_lock_waits` on MySQL 8.0+, `sys.innodb_lock_waits` / `INNODB_LOCK_WAITS` on 5.7) alongside `sys.schema_table_lock_waits` metadata-lock blocking.
- **Blocker SQL recovery**: When an idle-in-transaction blocker has an empty `PROCESSLIST` query, Culprit inspects `events_statements_history` to surface the earlier statement holding the lock.
- **Live plan & stage progress**: Uses `EXPLAIN FOR CONNECTION ` and `performance_schema` stage instruments where enabled. Outside `prod`, Studio exposes both `KILL QUERY` (cancel) and `KILL` (terminate).
- **Lock timers & deadlocks**: Digest `SUM_LOCK_TIME` (exported in exact picoseconds for Fleet, displayed in milliseconds in scans) reflects MySQL 8.0.28+'s corrected row + table lock accounting without claiming historical parity on 5.7. InnoDB exposes the latest detected deadlock (`SHOW ENGINE INNODB STATUS`), which Culprit parses into a participant lock graph without claiming complete incident retention.
### Opt-in diagnostic & replication readers
To keep routine scans lightweight, deeper `performance_schema` and cluster inspections run only when explicitly requested via `culprit scan ` or `culprit collect once --collection `:
| Opt-in reader | Flag / collector recipe | Supported versions & safety bounds |
|---|---|---|
| Tracked session memory | `--collect-session-memory` / `session-memory` | **MySQL 8.0.31+**: Reads current & high-water `TOTAL_MEMORY_ALLOC` / `CONTROLLED_MEMORY` from `performance_schema.threads` via in-memory thread join (never touching `sys.processlist`); 24-query, 2s/10s, 8 MiB cap |
| Retained error log | `--collect-native-failures` / `native-failures` | **MySQL 8.0.22+**: Reads up to 128 structured rows from `performance_schema.error_log` (UTC timestamp, error code, priority, subsystem) while omitting the free-form `DATA` column so user literals never leak; 2s/10s cap |
| Event Scheduler catalog | `--collect-native-failures` / `mysql.jobs` | **MySQL 5.7+**: Reads up to 128 visible `information_schema.EVENTS` schedules/statuses (omitting event SQL bodies and definers); 2s/10s, 512 KiB cap |
| Group Replication | `mysql.group-replication` (collector) | **MySQL 5.7.17+**: Captures `replication_group_members` and `replication_group_member_stats` (certification/applier queues, conflicts, member roles); 23 phases, 1s/5s, 128 rows/table cap |
## Schema and indexes
`information_schema`, `performance_schema.table_io_waits_summary_by_index_usage` and `sys` supply tables, columns, foreign keys, auto-increment utilization, column histograms and index usage counters.
- **Reversible `INVISIBLE` index workflow**: On MySQL 8.0+, cleanup advice for eligible unused indexes (after `>= 7` days of continuous counters, never touching primary, unique or foreign-key-backing indexes) recommends `ALTER TABLE ... ALTER INDEX ... INVISIBLE` first so optimizer impact can be verified with instant rollback before dropping. On MySQL 5.7, Culprit preserves the full `CREATE INDEX` definition first.
- **Online DDL & `lint-sql`**: Both the schema advisor and `culprit lint-sql migrations/ --format sarif` emit `ALGORITHM=INPLACE, LOCK=NONE` where supported and flag table-rebuilding column alterations, missing foreign-key indexes and auto-increment exhaustion risks in CI and VS Code.
## Limits and evidence
- **Independent counter resets**: Digest summaries, latency histograms, table I/O summaries and `slow_log` tables reset independently; Culprit verifies counter continuity before computing rates or deltas and never substitutes `0` when an instrument or consumer is disabled.
- **Shared instance metrics**: InnoDB redo-log waits, buffer pool counters and host/cloud metrics retain their instance-wide scope rather than being blamed on a single schema's queries.
- **Background telemetry (`culprit collect`)**: Shares the owned MySQL wire reader with strict statement timeouts, byte budgets and cancellation fencing—exporting exact picosecond counters, catalog fingerprints, persistent blockers and the latest InnoDB deadlock to ADX or ClickHouse without running application SQL. See [collector source coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#other-provider-source-coverage) and [evidence rules](/docs/providers/coverage.md).
## Verification
Verified against **MySQL 5.7.44** and **MySQL 8.4** (saved fixture: MySQL **8.4.11**), covering `performance_schema` digests, latency histograms, MySQL 5.7 lock-view fallbacks, `INVISIBLE` index handling, metadata-lock blocking and InnoDB deadlocks.
- Reproducible Docker fixture & workload: [`dev/mysql/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/mysql/README.md)
- Declared MySQL sources: [`culprit-mysql/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-mysql/src/sources.rs)
- Native references: [MySQL 8.4 error-log table](https://dev.mysql.com/doc/refman/8.4/en/performance-schema-error-log-table.html) · [metadata-lock waits](https://dev.mysql.com/doc/refman/8.4/en/sys-schema-table-lock-waits.html)
---
# MariaDB
[Engine parity](/docs/parity.md)
Culprit detects MariaDB automatically over the MySQL wire protocol and switches to MariaDB-native execution plans (`ANALYZE FORMAT=JSON`), persistent column statistics, lock views, `IGNORED` index syntax, multi-source replication channels and Galera cluster telemetry—keeping every counter and version rule distinct from [MySQL](/docs/providers/mysql.md).
## Connecting
Select **MySQL / MariaDB** in Studio or pass a `mysql://` URL on the CLI. Existing connections from DBeaver, DataGrip or VS Code can be imported via `culprit conn import`.
```sh
# Standard MariaDB connection (remote TLS verifies server identity by default)
culprit conn add shop --env prod --url 'mysql://culprit_reader@mariadb.example.com:3306/shop'
# Amazon RDS for MariaDB with short-lived AWS IAM token
culprit conn add shop-rds --env prod --auth aws-iam --url 'mysql://culprit_reader@shop.xyz.us-east-1.rds.amazonaws.com:3306/shop'
# Private MariaDB node through an SSH jump host
culprit conn add shop-priv --env prod --ssh ubuntu@bastion.example.com --url 'mysql://culprit_reader@10.0.6.14:3306/shop'
```
In JSON exports and SDK payloads, MariaDB uses `engine = "mysql"` while `server.product` / `latest_scan.product` identifies `"MariaDB"` and parsed plans carry `props.flavor = "MariaDB"`.
## Permissions and setup
Grant read-only monitoring privileges (`PROCESS`, `REPLICA MONITOR` / `BINLOG MONITOR` where applicable, and `SELECT` on monitoring catalogs):
```sql
CREATE USER 'culprit_reader'@'%' IDENTIFIED BY '';
GRANT PROCESS, REPLICA MONITOR ON *.* TO 'culprit_reader'@'%';
GRANT SELECT ON performance_schema.* TO 'culprit_reader'@'%';
GRANT SELECT ON mysql.slow_log TO 'culprit_reader'@'%';
GRANT SELECT ON `shop`.* TO 'culprit_reader'@'%';
```
### Zero-restart workload setup when `performance_schema` is off
Many MariaDB installations ship with `performance_schema = OFF` (which requires a restart to enable). Instead of demanding a production restart, Culprit prioritizes MariaDB's dynamic table-based slow query log and `userstat` counters when nothing is currently recorded:
```sql
-- Dynamic, zero-restart workload & index-usage capture (review overhead before lowering long_query_time):
SET GLOBAL log_output = 'TABLE';
SET GLOBAL slow_query_log = ON;
SET GLOBAL userstat = ON;
```
Culprit presents these commands as guidance in `server.missing[]` and Studio—scans never execute `SET GLOBAL` themselves.
## Workload and plans
| Capability | MariaDB source and behavior |
|---|---|
| Statement statistics | `performance_schema` digests (`workload.source = "performance_schema"`), or fingerprinted runs from `mysql.slow_log` (`workload.source = "slow query log"`) |
| Period comparison | Saved-scan deltas for digests, or native `slow_log` timestamps and `long_query_time` windowing (`"slow-log"`) |
| Estimated & measured plans | MariaDB `EXPLAIN FORMAT=JSON` and `ANALYZE FORMAT=JSON` (per-operator r_rows, r_loops, filtered %, r_total_time_ms and page reads inside a rolled-back read-only transaction) |
| Legacy JSON compatibility | Handles pre-11.0 MariaDB plans without native cost fields (using row estimates without conflating them with MySQL/PostgreSQL costs) and repeated `table` members alongside `nested_loop` arrays |
| Plan import & replay | Imports MariaDB `EXPLAIN` / `ANALYZE` JSON in Studio, CLI (`explain --query-id`), MCP `query_plan` and [explain.culpritsql.com](https://explain.culpritsql.com) |
| Runtime spread | Digest min/avg/max, or exact percentiles and histograms computed directly from retained `mysql.slow_log` runs |
## Live activity and waits
Live combines `information_schema.PROCESSLIST` (including MariaDB's sub-second `TIME_MS` precision and `STAGE` / `MAX_STAGE` progress for `ALTER TABLE` and `LOAD DATA`), `INNODB_TRX`, `INNODB_LOCK_WAITS` and `INNODB_LOCKS`.
- **Read-only transaction ID guard**: MariaDB 10.x assigns `trx_id = 0` to transactions that have not yet modified rows; Culprit matches waiting sessions through their requested lock descriptors rather than falsely linking unrelated `trx_id = 0` sessions.
- **Running query plans (`SHOW ANALYZE`)**: On MariaDB **10.9+**, Live can inspect an executing statement's live plan via `SHOW ANALYZE FORMAT=JSON `. Outside `prod` connections, `KILL QUERY` and `KILL` are available.
- **Scheduled events (`mysql.jobs`)**: On MariaDB releases exposing `server_uid`, `--collect-native-failures` and `--collection jobs` capture up to 128 `information_schema.EVENTS` schedules without reading event bodies.
## Schema and indexes
Catalog views supply tables, columns, foreign keys, auto-increment bounds, indexes and MariaDB engine-independent persistent statistics (`mysql.column_stats` / `ANALYZE TABLE ... PERSISTENT FOR COLUMNS (...)`).
- **MariaDB 10.6+ `IGNORED` indexes**: When index-usage history establishes an eligible unused index, Culprit emits MariaDB's native `ALTER TABLE ... ALTER INDEX ... IGNORED` (reversible via `NOT IGNORED`)—never MySQL's `INVISIBLE` syntax. Note that `userstat`'s `INDEX_STATISTICS` table records no enable/reset timestamp, so Culprit never claims a 7-day unused verdict from `userstat` alone without dated scan baselines.
- **Online DDL & `lint-sql`**: `culprit lint-sql migrations/ --format sarif` validates MariaDB migrations for `ALGORITHM=INPLACE, LOCK=NONE` compatibility, unindexed foreign keys and unsafe column rewrites.
## Limits and evidence
### Background telemetry and operational scope
Background `culprit collect` shares the owned MySQL-family wire reader with MariaDB-specific timeout, lock and multi-source [`SHOW ALL SLAVES / REPLICAS STATUS`](https://mariadb.com/docs/server/reference/sql-statements/administrative-sql-statements/show/show-replica-status) layouts. Server-wide counters (InnoDB redo waits, metadata-lock queues, replication channels) retain their instance scope rather than being attributed to a single database; see [collector source coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#other-provider-source-coverage) and [evidence rules](/docs/providers/coverage.md).
### Galera cluster observations (`mariadb.galera`)
Ordinary scans capture a lightweight 5-variable Galera readiness and flow-control summary (`wsrep_*`), treating `Donor/Desynced` state as operational context rather than an automatic outage. For deeper cluster troubleshooting on MariaDB nodes exposing native `server_uid`, run the explicit `mariadb.galera` collector recipe:
| `wsrep` metric group | Captured meaning and boundaries |
|---|---|
| Queue depths | Current receive/send write-set queues waiting to apply or transmit at capture time |
| Cumulative totals | Certification failures, local applier aborts, transaction replays, local commits and flow-control paused nanoseconds (kept with unknown reset epoch) |
| Flow-control fraction | `wsrep_flow_control_paused` covers the interval since the last `FLUSH STATUS` (Culprit never runs `FLUSH STATUS` and excludes read-relative min/max/avg variables) |
| Safety ceiling | Shared-instance scope; capped at 17 SQL statements total (including 3-point context verification), 17 allowlisted variables (`<= 32 KiB`), 1s statement timeout and 5s total budget ([Galera status reference](https://mariadb.com/docs/galera-cluster/reference/galera-cluster-status-variables)) |
## Verification
Verified across **MariaDB 10.5.29, 10.6.28, 10.11 and 11.8**—exercising `performance_schema` on and off, `mysql.slow_log` + `userstat` fallback, `ANALYZE FORMAT=JSON` plans, `IGNORED` indexes, blocking chains, InnoDB deadlocks and `SHOW ANALYZE` live progress.
- Reproducible Docker fixture: [`dev/mysql/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/mysql/README.md)
- Declared MySQL/MariaDB sources: [`culprit-mysql/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-mysql/src/sources.rs)
---
# ClickHouse
[Engine parity](/docs/parity.md)
Culprit inspects ClickHouse servers over read-only HTTP(S), scoping each connection to one node and one database. Workload families, exceptions and execution profiles come from `system.query_log`, live requests come from `system.processes`, physical query steps come from `EXPLAIN PLAN json=1`, and MergeTree operational diagnostics cover parts, merges, mutations, replication queues, distributed send queues and asynchronous inserts.
## Connecting
Select **ClickHouse** in Culprit SQL Studio or register a `clickhouse://` HTTP(S) endpoint on the CLI:
```sh
# Production HTTPS endpoint (port 8443, TLS certificate & hostname verification enabled by default)
culprit conn add analytics --env prod --url 'clickhouse://culprit_reader@ch.example.com:8443/analytics' --password-env CULPRIT_SOURCE_PASSWORD
culprit scan analytics
# Local plaintext fixture over HTTP (explicit port + ?sslmode=disable)
culprit conn add ch-local --env dev --url 'clickhouse://culprit_reader@127.0.0.1:8123/analytics?sslmode=disable'
```
| Capability | ClickHouse provider behavior |
|---|---|
| Transport & TLS | Speaks ClickHouse's HTTP(S) interface (`8443` default, `sslmode=verify-full` with optional `sslrootcert`); native TCP ports `9000` / `9440` use a different wire protocol and are not used |
| Node & database scope | Each connection inspects **one node and one database**; for predictable replica coverage behind a load balancer, save a connection per node or use a session-affine endpoint |
| Authentication | Dedicated password (stored in OS keychain or `--password-env`) or explicitly configured passwordless reader; cloud IAM/Entra tokens and SSH jump-host forwarding (`--ssh`) are refused |
| Session safety | Sends read-only execution settings and per-query resource ceilings on every HTTP request and maintains a dedicated HTTP session ID through final identity verification |
## Permissions and setup
Create a least-privilege ClickHouse reader and grant catalog visibility on the monitored database plus `SELECT` on the `system.*` tables you want Culprit to inspect:
```sql
-- Core catalog and query-history visibility
GRANT SHOW TABLES, SHOW COLUMNS ON analytics.* TO culprit_reader;
GRANT SELECT ON system.databases TO culprit_reader;
GRANT SELECT ON system.tables TO culprit_reader;
GRANT SELECT ON system.columns TO culprit_reader;
GRANT SELECT ON system.query_log TO culprit_reader;
-- Live requests and MergeTree / cluster operational health
GRANT SELECT ON system.processes TO culprit_reader;
GRANT SELECT ON system.parts TO culprit_reader;
GRANT SELECT ON system.merges TO culprit_reader;
GRANT SELECT ON system.mutations TO culprit_reader;
GRANT SELECT ON system.replicas TO culprit_reader;
GRANT SELECT ON system.replication_queue TO culprit_reader;
GRANT SELECT ON system.distribution_queue TO culprit_reader;
GRANT SELECT ON system.asynchronous_insert_log TO culprit_reader;
GRANT SELECT ON system.asynchronous_metric_log TO culprit_reader;
GRANT SELECT ON system.metric_log TO culprit_reader;
GRANT SELECT ON system.disks TO culprit_reader;
GRANT SELECT ON system.part_log TO culprit_reader;
GRANT SELECT ON system.query_views_log TO culprit_reader;
GRANT SELECT ON system.query_metric_log TO culprit_reader;
```
- **Settings profile constraints**: Because Culprit attaches a read-only flag and per-query resource bounds (`max_rows_to_read`, `max_bytes_to_read`, `max_memory_usage`, timeouts) to every HTTP query, a restrictive ClickHouse settings profile that marks those settings `CONST` / `READONLY` can reject requests before touching `system.*`. Configure bounded exceptions in the reader's profile where needed; see [ClickHouse settings constraints](https://clickhouse.com/docs/operations/settings/constraints-on-settings).
- **Non-intrusive log reads**: Running `EXPLAIN PLAN` or read-only editor queries additionally requires `SELECT` on the referenced tables. Culprit reads whatever `system.query_log` and `system.part_log` rows have already flushed—it never enables logging or issues `SYSTEM FLUSH LOGS`.
## Workload and plans
| Capability | ClickHouse source and behavior |
|---|---|
| Statement workload | Groups completed initial requests in `system.query_log` by `normalized_query_hash` where the query's native `databases` list names the selected database |
| Distributed queries | Counted once at the initiating node; `read_rows` counts ClickHouse rows read and elapsed duration can include remote shard work |
| Timelines & comparison | Time-bucketed execution and latency series plus two-period comparisons across logged initial requests |
| SQL sample redaction | Bounded SQL samples pass through Culprit's SQL literal redactor before export; oversized statements retain their exact counters with an explicit truncation note |
| Execution plans | Runs `EXPLAIN PLAN json=1, indexes=1` in Studio, CLI and the read-only editor (and imports ClickHouse plan JSON in [explain.culpritsql.com](https://explain.culpritsql.com)) to visualize physical pipeline steps |
| Unavailable plan metrics | ClickHouse `EXPLAIN PLAN` does not emit relational optimizer cost numbers, actual per-operator timings or retained historical plans |
## Live activity and waits
Live queries `system.processes` for visible foreground initial requests whose current session database matches the connection—displaying native `query_id`, user, elapsed duration, rows read and current SQL text.
- **Database context boundary**: A process's current database reflects session state rather than every cross-database table a running query might read.
- **Wait & progress model**: ClickHouse records query duration and resource/profile counters rather than relational lock-wait chains or an exclusive wait-category breakdown.
- **Session termination**: Outside `prod` connections, terminating an active request issues `KILL QUERY WHERE query_id = '...' SYNC;`.
## Schema and indexes
Schema inspection reads `system.databases`, `system.tables` and `system.columns` to report table engines (`MergeTree`, `ReplicatedMergeTree`, `Distributed`, etc.), row and on-disk byte totals, primary-key presence and typed column definitions.
- **MergeTree vs B-tree semantics**: MergeTree sorting keys (`ORDER BY` / sparse primary index) and data-skipping indexes operate on granules and parts rather than row-level B-tree pointers. Culprit never emits relational `CREATE INDEX` covering scripts or "unused index" drop verdicts against ClickHouse tables; instead, findings direct you to sorting keys, selected marks/parts and insert batching.
## Limits and evidence
| Source | What an investigator can establish |
|---|---|
| `system.query_log` | Recorded execution failures on the observed node—distinguishing memory limits, concurrency caps, timeouts, disk-space errors, Keeper errors and `TOO_MANY_PARTS` from benign cancellations |
| `system.parts` & `system.merges` | Active part counts per partition and in-flight background merges to contextualize insert/merge write pressure |
| `system.mutations` | Unfinished `ALTER TABLE ... UPDATE / DELETE` mutations with a recorded failed part and failure timestamp |
| `system.replicas` & `system.replication_queue` | Read-only or expired Keeper/ZooKeeper replica sessions, queues delayed `>= 5` minutes, and tasks failing with retry exceptions |
| `system.distribution_queue` | Blocked `Distributed` table send queues with pending on-disk batch files (exported with an opaque queue identity) |
| `system.asynchronous_insert_log` | Parsing and flush errors (`FlushError`) for asynchronous inserts |
| `system.query_views_log` | Failed materialized-view writes and successful writes taking at least one second, with the view, destination, and originating query ID |
| `system.query_log` on each configured node | Secondary executions linked by database, coordinator query ID and exact start time. Distributed family regressions compare mean coordinator duration over two adjacent 15-minute windows with at least five successful executions in each, a doubling of duration, and at least one additional second |
| `system.query_metric_log` | Recorded memory, peak memory, and sort and aggregation spill counts for the selected execution, where the server retained samples |
| `system.query_log` & `system.part_log` | Targeted follow-up of one recorded `query_id` plus concurrent part events on a named table during the 5 minutes preceding the execution’s end |
- **Per-request guardrails**: Native HTTP reads enforce an **8-second** statement timeout, **`2,000,000`** max rows read, **`128 MiB`** max bytes read / memory usage, and an **`8 MiB`** HTTP response ceiling. Unreadable tables and row caps appear explicitly in source coverage, single-node scans never claim cluster-wide health, and unconfirmed HTTP session shutdowns fence subsequent background collection.
### Investigating query cost and node health
In **Queries**, choose **Rank by** to find families by total elapsed time, CPU, bytes read, largest recorded execution memory, or p95 duration among successful executions. Each metric contributes candidates within the configured family cap. The denominator for elapsed time and executions covers all qualifying logged families. CPU totals require recorded CPU counters on every execution in that family. The p95 is a t-digest estimate and its successful sample count is shown beside it.
In a connected workspace, the **Plan** tab requests the current estimated plan for a readable SELECT sample. It describes the access path with the current schema, settings and reader permissions. The **History** tab shows retained plan variants when a provider supplies them. ClickHouse query-log families have no retained execution plan in these captures.
Open a family and inspect its slowest or largest successful execution. Each example retains its exact node, query ID, start and end times, memory, row and byte counts, and allowlisted profile events. Studio opens this evidence directly from the report. **Copy collector selection** requests a fresh exact-ID lookup while the log is available. The archive window’s native workload view can open the captured examples after the source log expires. Overlapping family captures keep their own window and population.
To attach an application endpoint to individual executions, add `culprit_endpoints=checkout,search` to the source connection URL and have the application set ClickHouse’s `log_comment` to the matching label. Each connection accepts up to 32 exact labels. Other comments are discarded at the database, and shared report exports omit endpoint labels.
**Live** shows current request memory and cumulative bytes read and written. **Health** charts the observed node’s CPU, resident memory, available memory, replica queue and running queries in completed UTC minutes. The chart readout includes concurrent merge, mutation and replica fetch maxima. Disk free space is sampled at the acquisition instant for each local disk. These measurements are shared across databases on that node. Missing logs, permissions or metric names limit their respective series. Select a metric tile or use the history selector to change the chart. Expand **Collection details** for coverage, original records and any permission or row-limit issues. Repeated operational faults are grouped by node, database, condition and query family or table. For parts-limit failures, completed table minutes show new parts, inserted rows and merge inputs alongside the error.
The macOS demo uses a local ClickHouse 26.8 server. [Top queries](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/clickhouse-top-queries.png) · [Execution details](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/clickhouse-query-details.png) · [Estimated plan](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/clickhouse-plan.png) · [Node health](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/clickhouse-health.png) · [Live sessions](https://raw.githubusercontent.com/culpritsql/culprit-sql-studio/main/docs/screenshots/clickhouse-live.png)
### Background telemetry and focused investigations
`culprit collect` captures a 15-minute `system.query_log` window (including resource-ranked families, successful execution examples and failed requests) alongside current MergeTree, mutation, replication and queue state:
```sh
culprit collect outbox init ./outbox
culprit collect once analytics --collection operational --outbox ./outbox
```
A fleet target scheduled for operational collection can automatically investigate a recorded query failure or distributed family regression. The collector reports this follow-up as `clickhouse.recorded-execution`. It uses the original database incarnation, node, query ID and microsecond timestamps to look up the run. The capture links back to that incident. It includes the terminal query record, up to five minutes of retained execution samples and, when one table can be identified, recent part events. An expired execution retains its original incident and an explicit outcome. Missing optional logs have independent coverage.
A fleet target with an **Activity** schedule can also investigate a query while it is running. After the long-running threshold (60 seconds by default), `clickhouse.current-request-work` reads `system.processes` again for that user and query ID. The original and follow-up samples retain elapsed time, rows and bytes read and written, and available memory and CPU counters. Culprit checks the database, server and overlap with the originally observed execution before attaching the second sample. A missing row means the reader could no longer see that request. Other users’ queries require native visibility on the connected node.
For shared node incidents, run `culprit collect resources analytics --kind node --json` and use the returned identity as the resource of one shared fleet target. Schedule its `operational` collection once per node. The collector evaluates the five most recent completed UTC minutes from the current server lifetime. A CPU warning requires average utilization of at least 90% of cgroup quota in each minute. A memory warning requires at most 5% average cgroup headroom in each minute. A replicated-merge backlog must grow every minute, by at least eight tasks overall, and reach at least sixteen. The archive retains the measured values. A restart, missing metric or missing minute prevents the corresponding warning. Studio shows the same warnings in node health.
Replication and materialized-view incidents use facts already captured by the baseline. For replica delay, the oldest repeatedly postponed task on the same replica can supply the native reason category. A buffered async-insert flush and query failures with an unambiguous native match share one finding. The archive retains each original record. To inspect a distributed execution, select the published member databases in Archives. Each member reports its own matching worker requests and coverage.
For an on-demand lookup in Studio, expand the execution or failure and use **Copy collector selection**, then run `culprit collect once analytics --selection focus.json --outbox ./outbox` with the saved selection. For example,
```json
{
"kind": "click-house-investigation",
"focus": {
"target": {
"engine": "clickhouse", "database": "analytics",
"location": {"kind": "server", "host": "ch.example.com", "port": 8443, "instance": "node-a"},
"incarnation": "637839ab-45c7-4091-b729-94717b33d2e4"
},
"request": {"node": "node-a", "database": "analytics", "query_id": "example-id", "started_us": 1735732800000000, "ended_us": 1735732802000000},
"table": "events"
}
}
```
Sealed ClickHouse captures publish to either **Azure Data Explorer (ADX)** or a **ClickHouse** telemetry warehouse using independent source, recovery and warehouse credentials. See [collector configuration](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md) and the [Helm chart](https://github.com/culpritsql/culprit-sql-studio/blob/main/deploy/helm/culprit-collector/README.md).
## Verification
To measure SQL collection overhead, run `python3 dev/benchmark-clickhouse-source.py --baseline REVISION` with the Git revision you want to compare. It alternates both query sets on the same disposable node and synthetic query log, enforces the provider's query limits, and checks independent ranking winners. The reported latency sums serial server execution times. Network, outbox and warehouse delivery have separate costs.
`dev/smoke-clickhouse-source.py` boots a disposable ClickHouse container and verifies query-family aggregation, `TOO_MANY_PARTS` insert refusals, failed mutations, malformed asynchronous inserts and memory/group-by limit exceptions (`--provider-test` also exercises the HTTP provider, archive recipe, focused lookup, read-only editor and plan parser; pass `--image` to test specific ClickHouse versions).
- Disposable smoke suite: [`dev/smoke-clickhouse-source.py`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/smoke-clickhouse-source.py)
- Declared ClickHouse sources: [`culprit-clickhouse/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-clickhouse/src/sources.rs)
---
# SQLite
[Engine parity](/docs/parity.md)
Culprit opens SQLite database files strictly read-only (`SQLITE_OPEN_READ_ONLY` + `PRAGMA query_only = ON`). Schema inspection, `sqlite_stat1` planner statistics, bounded `dbstat` storage analysis and `EXPLAIN QUERY PLAN` work immediately with zero application changes; statement workload history comes from an optional framework or JSONL query log (`crates/culprit-querylog`).
## Connecting
Select **SQLite** in Studio and pick a `.sqlite3` / `.db` file, or register the path on the CLI:
```sh
# Add a read-only SQLite file connection
culprit conn add app --env prod --url db/production.sqlite3
# Explicitly attach or disable an application query log
culprit conn set app --query-log log/production.log
culprit conn set app --no-query-log
```
File connections store local paths and require no network credentials. When `--query-log` is not set, Culprit automatically checks beside the database file, `./log/`, `./logs/`, and `../log/` for a matching log (`production.sqlite3` → `production.log`), while refusing to pair an environment-named database (`production.sqlite3`) with another environment's log (`development.log`).
## Permissions and setup
Culprit needs filesystem read permission on the database file (plus its `-wal` / `-shm` companions when WAL mode is active) and on any attached query log.
- **Zero application instrumentation required**: Culprit never installs hooks, triggers, extensions or driver wrappers, and never runs `WAL` checkpoints or `VACUUM`.
- **Connection-local pragmas**: Settings persisted in the database header (`journal_mode`, `auto_vacuum`, `page_size`, `user_version`) are read directly; per-connection pragmas (`synchronous`, `foreign_keys`, `cache_size`, `busy_timeout`) belong to your application's own connections, so Culprit explains how to verify them in application code rather than guessing from its own connection.
## Workload and plans
Because SQLite embeds no shared Query Store or `pg_stat_statements` memory across OS processes, Culprit reconstructs statement workload from your application's query log—fingerprinting SQL shapes, redacting literals, tallying calls/total/avg/max latency, and tracking structured `SQLITE_BUSY` / error counts separately from timed runs.
For execution plans, Culprit runs `EXPLAIN QUERY PLAN` read-only against the database schema (and imports sqlite3 CLI tree or pipe-delimited EQP text in Studio, CLI and [explain.culpritsql.com](https://explain.culpritsql.com)), surfacing full-table scans (`SCAN`), index searches (`SEARCH`), temporary B-tree sorts (`USE TEMP B-TREE`) and transient `AUTOMATIC COVERING INDEX` builds.
### If your framework already logs SQL
Culprit parses standard framework SQL logs out of the box with no format changes:
| Framework | Logger configuration |
|---|---|
| Ruby on Rails | Standard `debug` log level (default in development) |
| Django | `django.db.backends` logger at `DEBUG` |
| Entity Framework Core | `Microsoft.EntityFrameworkCore.Database.Command` at `Information` |
| Phoenix / Ecto | Standard Ecto `debug` query logger |
Point Culprit at any log file with `culprit conn set app --query-log /path/to/app.log` (or **Add query log** in Studio), or analyze a log standalone without a saved connection via `culprit logs`.
### Logging queries yourself
For applications using raw `sqlite3` without an ORM (FastAPI, Flask, Go, Rust or CLI tools), emit one JSON line (`JSONL`) per query:
```json
{"sql": "SELECT id, title FROM listings WHERE city = ? AND price < ? LIMIT ?", "ms": 4.2, "at": "2026-10-16T09:12:03.120+00:00"}
```
- `sql`: Parameterized SQL (`?` / `:name` placeholders keep user values out of the log file; Culprit also strips literals during ingestion).
- `ms`: Elapsed milliseconds across **both `execute()` and row iteration** (`sqlite3` steps lazily as rows are fetched).
- `at` *(optional)*: ISO 8601 timestamp with UTC offset (enables per-day rate calculations and window labels; without timestamps, Culprit shows percentage shares only).
- `request_id` *(optional)*: Correlates repeated statement shapes within one HTTP request/job for high-confidence N+1 detection.
```python
import json, time
from datetime import datetime, timezone
log = open("app.log", "a", buffering=1)
def query(conn, sql, params=()):
start = time.perf_counter()
rows = conn.execute(sql, params).fetchall()
log.write(json.dumps({
"sql": sql,
"ms": round((time.perf_counter() - start) * 1000, 3),
"at": datetime.now(timezone.utc).isoformat(),
}) + "\n")
return rows
```
### What the report says about a log
- **Ranked by total recorded time**: Distinct `WHERE` / `ORDER BY` shapes appear side by side with exact run counts and latency distributions.
- **Honest windowing**: Reports cite the exact span covered by the log (*"over the 50 minutes the Rails log covers"*), never claiming *"the last 50 minutes"*.
- **Streaming privacy**: Logs are streamed line by line; raw literals, free-form error text and raw `request_id` tokens never enter the saved report, and queries referencing tables absent from the opened SQLite file are excluded.
## Live activity and waits
SQLite is an in-process embedded library with no server session table, wait-event DMV or live lock graph. Studio and CLI mark live session/wait capabilities unavailable rather than displaying empty `0` dashboards, and keep the SQL editor strictly read-only on SQLite files.
## Schema and indexes
| Snapshot area | SQLite source | How Culprit reads it |
|---|---|---|
| Engine & header | `sqlite_version()`, `PRAGMA compile_options`, `page_size`, `journal_mode`, `auto_vacuum`, `user_version` | Reports persistent file header state alongside the linked SQLite library version |
| Tables & columns | `sqlite_schema`, `PRAGMA table_list`, `PRAGMA table_xinfo` | Preserves ordinary, `WITHOUT ROWID`, generated-column and virtual tables while excluding internal FTS/R-Tree shadow tables from standalone table checks |
| Row counts & sizes | Single-pass `dbstat` virtual table (within read budget) or `sqlite_stat1` | Never runs `SELECT COUNT(*)` on user tables; leaf cells count rowid rows, unknown stays `None` (never `0`) if over budget |
| Indexes & stats | `PRAGMA index_list`, `PRAGMA index_xinfo`, `sqlite_stat1` | Preserves partial-index `WHERE` clauses, expression indexes and per-index `ANALYZE` statistics coverage |
| Foreign keys | `PRAGMA foreign_key_list` | Detects unindexed child foreign keys that cause parent `DELETE` / `UPDATE` table scans |
| Free space & WAL | `PRAGMA page_count`, `freelist_count` + filesystem `.sqlite3-wal` stat | Measures freelist fragmentation and on-disk WAL size without checkpointing or truncating the WAL |
- **Schema & migration checks**: Flags unindexed foreign keys, duplicate/prefix-redundant indexes, missing `ANALYZE` (`sqlite_stat1`) statistics, freelist bloat and planner `AUTOMATIC INDEX` warnings. Because SQLite keeps no index-read counters, Culprit **never** flags an index as unused. `culprit lint-sql migrations/ --format sarif` lints SQLite schema migrations offline in CI and VS Code.
## Limits and evidence
- **Bounded `dbstat` read budgets (writers never wait)**: Full-file `dbstat` page inspection is capped at **4 GiB and 3 seconds** in WAL mode, or **128 MiB and 500 ms** with a rollback journal (where an open reader holds a shared lock that blocks writers). Files exceeding those bounds skip `dbstat` cleanly and report why.
- **Background telemetry (`culprit collect`)**: Exports **10 bounded `sqlite.*` metadata recipes** with a **250 ms** metadata ceiling—verifying file inode/replacement identity before and after each read, releasing the read snapshot before paging output, and skipping `dbstat` and default/DDL bodies. See [collector source coverage](https://github.com/culpritsql/culprit-sql-studio/blob/main/docs/collector.md#other-provider-source-coverage) and [evidence rules](/docs/providers/coverage.md).
- **N+1 attribution**: High call counts alone do not trigger an N+1 finding unless corroborated by explicit `request_id` correlation or repeated loop evidence.
## Verification
Verified against SQLite **3.53.2** using the reproducible fixture and framework query logs in [`dev/sqlite/README.md`](https://github.com/culpritsql/culprit-sql-studio/blob/main/dev/sqlite/README.md)—covering WAL vs rollback-journal read budgets, inode replacement detection, `query_only` enforcement, EQP parsing and log correlation.
- Declared SQLite sources: [`culprit-sqlite/src/sources.rs`](https://github.com/culpritsql/culprit-sql-studio/blob/main/crates/providers/culprit-sqlite/src/sources.rs)
- Query-log parser (`Rails`, `Django`, `EF Core`, `Ecto`, `JSONL`): [`crates/culprit-querylog`](https://github.com/culpritsql/culprit-sql-studio/tree/main/crates/culprit-querylog)
- Native error codes: [SQLite result and extended error codes](https://www.sqlite.org/rescode.html)
---
# SSH connections
Culprit can reach a private server database through an SSH jump host. The database connection keeps its real hostname and port: certificate verification, AWS IAM token signing, Entra ID and cloud metrics continue to use the database endpoint.
## Setup
Install a current OpenSSH client and make sure `ssh` works from a terminal. On Windows, enable the optional [OpenSSH Client](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse). Culprit also checks its standard installation location when launched without a terminal's PATH.
Connect to the bastion with OpenSSH first. Verify its host-key fingerprint with your administrator before trusting it in `known_hosts`. Culprit requires an already trusted host key, refuses changed keys and never opens a terminal prompt.
In **New connection**, keep the real database address in the connection string and enable **SSH jump host**. Enter `reader@bastion.example.com` or a host alias from your SSH configuration. **Identity file & port** optionally overrides the key path or SSH port. Leaving them empty uses OpenSSH's configuration and agent.
For an existing connection, choose **SSH** on its card. This also works for databases saved through Azure or AWS discovery. **Test connection** uses the draft route with the saved database credentials; **Save settings** changes only the route. Disable the checkbox and save to return to a direct connection.
A loopback database address through SSH belongs to the remote machine. Culprit does not label it local; an unclassified new SSH connection defaults to production confirmations. Choose its environment explicitly when it is staging or development.
The CLI uses the same settings:
```sh
culprit conn add shop --env staging \
--url 'postgres://app@shop.internal.example:5432/shop?sslmode=verify-full' \
--ssh prod-bastion
culprit conn set shop --ssh reader@bastion.example.com --ssh-port 2222 \
--ssh-key ~/.ssh/id_ed25519
culprit conn set shop --no-ssh
```
An SSH destination can include its port (`reader@bastion:2222`); use brackets for an IPv6 address with a port (`reader@[2001:db8::1]:2222`). The separate port field or `--ssh-port` must agree with an embedded port.
Identity-file paths are literal paths. Paths containing `%` expansion tokens must be configured through OpenSSH's `IdentityFile` setting instead.
## Authentication and configuration
Culprit delegates SSH authentication to [OpenSSH](https://man.openbsd.org/ssh_config). Your host aliases, `ProxyJump`, `ProxyCommand`, `IdentityAgent`, certificates and hardware-backed keys remain available through its configuration. Required proxy tools must be installed, configured and able to run without interactive terminal input.
Use an SSH agent or an unencrypted identity file. Unlock encrypted keys in the agent before connecting. Culprit stores only the destination, optional port and optional identity-file path in its connection metadata. It does not store an SSH password or key passphrase, display a passphrase prompt or read private-key contents into the UI. A key-file picker selects the path on your machine.
The database's authentication remains separate: its password stays in the keychain, and cloud tokens are requested for the original database hostname. TLS still follows the connection's existing verification settings; the tunnel does not relax certificate checks. The bastion must be able to resolve and reach that hostname and port. SQL Server gateway redirects are forwarded through the bastion too.
## Lifetime and limits
Each connection attempt owns a loopback listener and opens an [`ssh -W`](https://man.openbsd.org/ssh#W) channel for each database TCP session. It creates no persistent background SSH master. An existing control connection configured by you can be reused; Culprit does not close that user-owned master.
Dropping a pending connection cancels its listener. Closing a database session closes its SSH process tree, including proxy children; a half-close drains final response bytes with a one-second idle grace period. The last provider releases the listener and remaining sessions. Cancellation and normal operation deadlines still apply. SSH work is bounded to 16 active routes, 8 sessions per route and 32 sessions per workspace; pending connection attempts count toward those limits. Streams use fixed-size buffers and bounded diagnostic capture. Errors describe the failure without exposing raw proxy output.
SQLite reads a local file and does not offer SSH settings.
---
# Using Culprit from a coding agent
Culprit's CLI is designed to be driven by agents: JSON output, stable ids, no prompts, no credentials in arguments.
## Contract
- **Output.** JSON on stdout when stdout is not a terminal (or with `--json` / `--format json`). `--format md` gives a markdown table for PR comments; `--format sarif` emits SARIF 2.1.0 for GitHub Pull Request annotations.
- **Errors.** JSON on stderr: `{"error":{"code":"…","message":"…","hint":"…"}}`. Codes: `invalid_input`, `not_found`, `connection_failed`, `auth_failed`, `permission_denied`, `timeout`, `unsupported`, `query_failed`, `internal`.
- **Exit codes.** `0` success, `1` error, `2` named finding still present (`verify`), `3` findings at or above `--fail-on ` (`scan`, `lint-sql`).
- **Connections by name.** The person adds a connection once (`culprit conn add` or the app). Secrets live in the OS keychain, come from `az login` (Entra ID), or are read from an environment variable named with `--password-env`. Agents only ever pass the name.
- **Safe by default.** `scan`, `doctor`, `findings`, `show`, `top`, `live` and `explain` (without `--analyze`) never execute application SQL. `run` and `explain --analyze` on a production connection fail unless `--yes-execute-on-production` is passed; don't pass it without the person's explicit go-ahead.
- **Stable ids.** Finding ids are `:`, e.g. `missing-index:dbo.Orders(CustomerId)` or `plan-warnings:implicit-conversion:orders.status`. The same problem keeps the same id across scans, so "is it fixed?" is "is the id gone?".
- **No surprise network calls.** No command checks for updates on its own. `culprit update --check --json` asks GitHub for the latest published release and prints `{"current","latest","update_available","url"}`; `culprit update` replaces the binary with it after checking the release's SHA-256. Run them when the person wants Culprit current, not as part of another task.
## MCP server
`culprit mcp` serves the same capabilities as MCP tools over stdio. Register it once (`claude mcp add culprit -- culprit mcp`, or `culprit agent init` in a repository) and the agent can ask "what's slow on shop-staging?" directly.
| Tool | Does |
|---|---|
| `list_connections` | Connections the agent may use: name, engine, environment, agent access, latest scan |
| `scan` | Fresh snapshot (statistics views only) and ranked findings |
| `dashboard` | The database at a glance: fourteen tiles (database time, findings, top queries, waits, right now, health, deadlocks, indexes, plans, storage, connections, replication, failing queries, query statistics), each with a status, one takeaway, the rows behind it and the tool to call next; `attention` ranks what needs a look |
| `findings` | Findings from the latest scan, filtered by category or severity |
| `finding` | One finding as a markdown brief: evidence, queries, fix, verification |
| `top_queries` | Heaviest queries by time, CPU, reads or executions |
| `query` | One query: text, statistics, plan variants, related findings |
| `query_plan` | A query's plan as an indented operator tree (stored or estimated; never executes), with its insights' titles |
| `plan_insights` | What's wrong in a query's plan (`query_id`) or a statement's estimated plan (`sql`): ranked insights with operators, fix and verify |
| `last_actual_plan` | The actual plan of a query's last run on SQL Server 2019+ (`LAST_QUERY_PLAN_STATS`), without re-running the query |
| `query_progress` | How far along a running session's statement is right now |
| `what_changed` | Queries that got slower, new queries, queries that improved or stopped between two periods, and the plan changes behind them |
| `events` | Timeline events around a connection: deploy marks, schema changes, setting changes, restarts and cloud throttling |
| `cloud_metrics` | CloudWatch (`aws`) or Azure Monitor (`az`) CPU, credits, IOPS and latency for the server |
| `mark` | Record a moment (e.g. a deploy) on a connection's timeline |
| `explain` | Estimated plan for a statement the agent provides (never executes); supports virtual index verification (`with_indexes` on PostgreSQL via HypoPG) |
| `lint_sql` | Lint migration or DDL SQL offline against the latest saved snapshot: blocking locks, unindexed/mismatched FKs, table rewrites, and broken live queries |
| `live` | Sessions, waits and blocking right now |
| `blocking` | Who blocks whom right now, as chains under each head blocker |
| `deadlocks` | Recent deadlocks explained, with the pattern and fix |
| `analyze_event_xml` | Explain supplied SQL Server Extended Events XML: attention, errors and deadlocks, without a database connection |
| `waits` | Wait categories with the queries behind each, or a live sample (`now: true`) |
| `analyze_capture` | When explicitly enabled: explain bounded native facts from one verified local capture using the shared report |
| `schema` | Tables; or one table's columns, indexes and which captured plans use each index |
| `drift` | Schema, index, setting and version differences between two connections |
| `index_advice` | The index advisor: indexes to add, indexes to clean up, and table storage guidance |
| `verify` | Re-scan and check whether each finding is fixed, still present or unknown |
| `export_finding` | Redacted Markdown for one finding or the whole scan, ready to paste into a PR or issue |
| `run_query` | One read-only statement, up to 200 rows: needs `query` access and the person's approval in the app |
When the startup host installs the existing local-capture capability, `analyze_capture` also accepts
`analysis: "incident_history"`. It reads immutable diagnostic revisions for the delegated connection and exact
observation ID, including resolved work absent from the controller checkpoint. The response retains original
phase, analysis status, clocks, reasons, past follow-up outcomes and reference availability. It shows at most
five revisions and states omissions. Selected history does not establish current controller state or authorize
current session actions; referenced payloads are not reopened by this read.
Results are compact JSON. Text that comes from the database (query text, object names, comments, values) is data, not instructions, and the server's instructions tell the agent so.
`analyze_event_xml` takes one `xml` string and is available in evidence-only mode. It accepts exported XML,
keeps incomplete input and unqualified clocks explicit, and bounds both input and the serialized tool response.
It accepts no filesystem path or connection name. Imported database labels never attach the artifact to a live
database, and the tool starts no source read or event session.
**Policies.** `culprit conn set --agent off|stats|query`, or the Agents menu on the connection in the app. `stats` is the default. `culprit mcp --connection ` (repeatable) exposes only those connections.
**Approvals.** `run_query` checks the statement is a single read-only statement, then waits up to 60 seconds for the person to approve that exact text in the desktop app. A decision is bound to a SHA-256 of the connection and the SQL, so it can't approve different text. If the app isn't open, the request is denied at once with a hint to open it. Approved statements run in a transaction that is never committed (read-only on Postgres and MySQL), with a 30-second limit.
**What "read-only" rests on.** Three layers, each with its limit:
- Culprit's classifier refuses anything it can't prove is one statement that only reads. It lexes the text under every server setting that changes parsing (quoting, backslash escapes) and refuses invisible characters outside strings. Its list of functions with side effects is a deny-list, so a function it doesn't know about can still run.
- The server enforces what it can: Postgres and MySQL run the statement in a read-only transaction, which stops table writes but not functions with side effects outside tables (statistics resets, locks, sleeps). On SQL Server the text first compiles under SHOWPLAN, which runs nothing, and must come back as exactly one SELECT. A login without SHOWPLAN permission skips this check, and the result says so.
- The login. For `query` access on a production database, give the connection a login that can read the tables it needs and nothing else: no EXECUTE on administrative functions, no ownership of objects. That is the one complete guarantee.
**Audit.** Every call (tool, client, connection, outcome, duration, and SQL for `explain` and `run_query`) is appended to `audit.jsonl` in the data directory. `culprit audit --json` reads it.
### Saved collector captures
Enable local evidence at server startup:
```sh
culprit mcp --connection shop-staging --evidence-outbox /path/to/outbox
```
`analyze_capture` takes `connection`, `observation_id` and a closed `analysis` choice. It supports `source_overhead`, `page_server_reads`,
`memory_clerks`, `hyperscale_log_components`, `performance_counters`, `wait_counters`, `database_properties`, `instance_resources`,
`index_configuration`, `indexed_views`, `compilation`,
`configured_log_rates`, `connection_outcomes`, `jobs`, `request_memory`, `task_space`, `current_request_work`,
`statement_work`, `maintenance_progress`, `completed_spills`, `storage`, `blocking` and `session_census`.
`observation_id` is the capture's `manifest.json` → `capture.observation_id`. The connection must be delegated to the agent and match the original
journal entry. The tool reanalyzes verified originals, with redacted SQL previews only when their exact original
definitions match. Memory clerks retain their original shared-server scope, native counts and read bounds; they
are not allocations attributable to the selected database or its queries. It does not connect to the database or use credentials, recovery storage or a warehouse.
`source_overhead` inspects sanitized acquisition metadata through the same bounded local worker and delegated
connection. It can inspect failed or provisional attempts with no source/database identity; it reads no native result
files and starts no database work. A provisional manifest is explicitly incomplete and cannot be retained as sealed
saved-scan history. Sealed successful and failed attempts can be attached through the existing saved-report intake;
these historical measurements do not describe the current scan or prove database/member continuity. Sharing
withdraws the whole original. Regular scan/probe acquisition metrics remain a separate unavailable seam.
Operational analyses share one authenticated original read. Results keep native source coverage and acquisition
clocks independently of local verification bytes. Details return at most five entries with explicit presentation
counts; this does not truncate or relabel the original captured population. Compilation and completed-spill facts
retain their historical native lifetimes, not current compiler ownership or a statement's elapsed-time cause.
`indexed_views` reads the same original Indexes catalog as table-index analysis. It keeps view indexes separate,
including their native usage and partition configuration. Missing usage is not measured zero; retained totals alone
do not justify dropping an index. Current scan metadata and earlier authenticated captures remain independent.
`wait_counters` preserves the original native scope. Qualified elastic-pool captures describe the pool through its
original anchor and membership points; they do not identify one database as the cause. Unsupported tiers or missing
visibility remain unavailable. Counter reset times and compute continuity remain unknown.
For `blocking`, select the focused closure capture. The same worker authenticates its exact original Activity
capture from the retained receipt, with one cumulative row, byte and deadline allowance for both inputs. A missing,
changed or unsettled original is refused; another baseline cannot replace it. Both native scopes and clocks remain
separate. Relationships and graph details have explicit presentation limits, and historical nodes offer no live
session action. A fully read file does not establish complete native lock visibility or repair unknown original scope.
The directory must be available for exclusive ownership; a running collector's lock is not bypassed. An embedding
host can instead share its existing Outbox actor. Without the startup option or an injected reader, this tool is
absent. MCP diagnostic text stays English independently of the desktop language.
To attach an existing clerk capture to a normal saved scan:
```sh
culprit scan shop-staging --evidence-outbox /path/to/outbox --memory-clerks-capture OBSERVATION
```
Both flags are required together. The capture must belong to that saved connection's journal entry. This runs the
ordinary database scan and retains the independently captured clerk originals after the native scan owner closes;
it starts no new clerk acquisition. Reopening the report reanalyzes those originals without accessing the outbox.
## Dashboard
`culprit dashboard --json` (MCP: `dashboard`) is the best first call: one database at a glance, the same tiles the app opens with.
```sh
culprit dashboard shop-staging --json | jq '{headline, attention}'
culprit dashboard shop-staging --json | jq '.tiles[] | {key, status, takeaway, next}'
culprit dashboard shop-staging --scan # scan first; --no-live skips reading sessions; a report file works offline
```
Each tile: `key` (`db-time`, `findings`, `top-queries`, `waits`, `now`, `health`, `deadlocks`, `indexes`, `plans`, `statistics`), `status` (`good`, `info`, `watch`, `bad`, `unavailable`), `takeaway` (one sentence), `detail`, `metrics` (`key`, `label`, `value`, `text`), `items` (the rows behind it, with `query_id` / `finding_id` to follow), `fix_sql` (copy-only, when one statement unlocks the tile) and `next` (the command, or MCP tool, that shows more). `attention` lists the tiles at `watch` or `bad`, most urgent first, and `headline` is the first one's takeaway. An `unavailable` tile says why this engine, login or scan can't show it (Postgres keeps no wait history; Query Store is off) instead of looking empty. The `now` tile reads sessions once; `--no-live` (MCP `live: false`) skips it.
## Plan insights
`culprit explain`, `culprit plan show` and the MCP tools `plan_insights`, `query_plan` and `explain` include insights: plan problems ranked by how much of the plan's work they touch.
```sh
culprit explain shop-staging --query-id 7 --json | jq '.insights.items[] | {severity, rule, title, fix_sql}'
culprit plan show slow.sqlplan # tree with ◆ on flagged operators, then the insights
```
Each item: `rule` (stable id, e.g. `key-lookups`, `non-sargable`, `misestimate`), `severity`, `impact` (0–1 share of the plan's work), `nodes` / `operators` (operator ids in the plan tree), `title`, `detail`, `fix`, `fix_sql` (copy-only; may be null), `verify`. `note` says what this engine's plan can't show (e.g. estimated plans have no actual rows), so an empty list is not proof of a clean plan. To check a rewrite, call `plan_insights` with `sql` before and after: the rule should disappear.
## Repository setup
```sh
culprit agent init # AGENTS.md section, .claude/skills/culprit/SKILL.md, .mcp.json entry
culprit agent init --connection shop-staging # name the project's connections and limit the MCP server to them
culprit agent init --no-mcp # instructions only
```
The AGENTS.md section sits between `` and `` markers and is replaced in place on re-runs; everything else in the file is kept. Nothing written contains findings, host names or secrets.
## Setting up connections
```sh
culprit conn discover --match shop --match stg --json # Azure SQL databases visible to `az login`, with suggested aliases
culprit conn discover --match shop --match stg --save # save them (Entra ID auth, nothing secret stored; production needs --include-production)
culprit conn rename shop-stg-db shop-staging # aliases are just names
```
## Typical loop
```sh
culprit conn list --json # what can I reach?
culprit scan shop-staging --json # summary + ranked findings (compact)
culprit scan shop-staging --window 6h --json # the same over the last 6 hours (or 90m, 2d, 1d12h)
culprit show shop-staging 'missing-index:dbo.orders(customer_id)' --json
# → finding, the queries involved with stats and hottest plan operator, and `brief`:
# a self-contained markdown description of the problem, evidence, fix and verification
culprit top shop-staging --by time -n 10 --json # heaviest statements
culprit explain shop-staging --query-id 10 --json # estimated plan of a captured query
culprit explain shop-staging --file query.sql --json # estimated plan of a new query, before shipping it
culprit drift shop-staging shop-prod --json # indexes, columns, settings that differ; SQL to align
culprit indexes shop-staging --json # the index plan: add (by DB time of the queries behind each), clean up, tables
culprit plan diff before.sqlplan after.sqlplan --json # did my index change the plan? headlines + changes
culprit plan diff shop-staging:10:7 shop-staging:10:9 --json # two Query Store plans of query 10: why one is slower
```
`top` and `show` include `trend_mean_ms` per query: its average duration in each bucket of the window (null where it didn't run), so "when did this get slow" needs no extra call. The `regression` finding states it directly.
`plan diff` returns `headlines` (plain sentences, the slower or changed plan described against the baseline), `changes` (each with `kind`: access, operator, added, removed, cost, rows or warning, plus node ids in either plan), `cost_ratio`, and the node `matches` between the plans. Plan text from another tool works too: `culprit plan show -` reads a .sqlplan, Postgres EXPLAIN (text or JSON) or MySQL EXPLAIN JSON/tree from stdin.
`indexes` (MCP: `index_advice`) returns `candidates` (keys, include, `source`: optimizer, plan-scan or foreign-key, `reason`, copy-only `sql` or `widens`, the `queries` behind it with their share of database time, merged `requests`, `writes_per_day`, `verify`), `cleanups` (`kind`: duplicate, prefix, overlap or unused, the `other` index, `sql`), `tables` (`kind`: scan-heavy, forwarded-fetches or over-indexed) and `notes`. Every item carries the `finding_id` that explains it when there is one. It also takes a saved report file.
After a fix ships: `culprit scan shop-staging --json` and check the finding id is gone. Findings carry `last_seen` (when their queries last ran) and `inactive: true` when those queries stopped running long before the data window ends, which usually means a deploy replaced them; treat those as history, not current problems.
After a fix ships: `culprit verify shop-staging '' --json` re-scans with the same window and reports each finding as `fixed`, `still-present` or `unknown` (its check couldn't run), plus `new` findings the change may have caused (a new index that isn't read yet). It exits 2 when a finding you named is still present, so CI can gate on it, and its `note` says why a shipped fix can still show (the Query Store window still holds earlier runs; pg_stat_statements and performance_schema count since their last reset). Findings carry `last_seen` (when their queries last ran) and `inactive: true` when those queries stopped running long before the data window ends, which usually means a deploy replaced them; treat those as history, not current problems.
## Sharing what Culprit found
```sh
culprit export shop-staging --finding 'missing-index:dbo.orders(customer_id)' # Markdown for the PR description
culprit export shop-staging --html -o findings.html # every finding, one offline HTML page
culprit plan export shop-staging:10:7 shop-staging:10:9 --html -o compare.html # a plan comparison with both diagrams
culprit plan export shop-staging:10:7 --native -o plan.sqlplan # the stored plan, opens in SSMS
```
Literal values in query text, predicates and parameter values are replaced with `'?'` and `?` unless `--no-redact`; names and parameter markers (`@P1`, `$1`, `?`) stay, each engine's quoting is followed, and SQL Server's four-part names drop their database. Shared analysis exports never include connection names, hosts or credentials. HTML pages are self-contained: inline CSS and SVG, no scripts, fonts or network requests. The editor's CSV/JSON result exports are separate: they keep the loaded query values and do not apply analysis redaction.
MCP: `verify` (`connection`, optional `finding_ids`) and `export_finding` (`connection`, `finding_id`, `redact` default true) do the same for agents. `plan diff` results also carry `scenarios`: the conditions that differ (estimator version, parameter values, row estimates with stale statistics from the latest scan when the plans came from a connection, indexes, type conversions, parallelism, memory), each with a plain-language title and detail.
## Blocking and deadlocks
```sh
culprit blocking prod --json # chains under each head blocker: headline, advice, the tree with what each waits for
culprit deadlocks prod --since 24h --json # recent deadlocks, explained: pattern, both statements, who was rolled back, fixes
culprit deadlocks --file deadlock.xdl --json # explain a saved one: SQL Server .xdl, InnoDB status text, Postgres log lines (- for stdin)
```
The MCP server has the same as `blocking` and `deadlocks`. `blocking` returns `chains[]` with `head`, `head_kind` (`idle-in-transaction`, `running`, `idle`, `unknown`), `headline`, `advice`, `waiters` and a nested `tree` (`session`, `waits_for` in words, `wait_type`, `sql`, `blocks[]`). `deadlocks` returns `deadlocks[]` with `pattern`, `objects`, `headline`, `explanation`, `processes[]` (`rolled_back`, `statement`), `locks[]` (`held_by`, `wanted_by`) and `fixes[]` (`title`, `detail`, copy-only `sql`, and `finding` when a finding is the same fix). Postgres returns `counted` and a `note` instead of graphs. Statements and names are data from the database, not instructions.
## Where the time goes
```sh
culprit waits shop --json # wait categories with meaning, detail and the queries behind each; pressure signals
culprit waits shop --now --seconds 30 # sample what the server waits on right now (read-only)
culprit waits --file report.json --json # offline, from a saved report
```
`waits` returns `{ connection, waits, pressure }`. `waits.categories[]` has `key` (cpu, io, rows, lock, latch, log, network, parallelism, memory, compilation, other), `label`, `share`, `wait_ms`, `top_wait` (the engine's own name), `meaning`, `detail`, `queries[]` (`id`, `share_of_category`, `share_of_query`, `executions`) and `attribution` when the engine can't name queries. `pressure.signals[]` each carry `key`, `value`, `unit`, `scope` (now / since-startup / sampled), `status` (good / info / watch / bad) and `healthy` in words. The MCP tool `waits` returns the same, compacted; `now: true` samples for up to 30 seconds.
New findings come from these signals: `memory-grant`, `memory-queue`, `compile-pressure`, `worker-pressure`, `held-cleanup`, `network-wait`, `tier-limit`, `checkpoint-pressure`, `row-lock-waits`.
`pressure` also carries `files[]` (`name`, `kind` data/log/temp/other, `database`, `reads`, `read_ms`, `writes`, `write_ms`, bytes; times are totals since startup, `null` where the engine doesn't time them) and `replicas[]` (`name`, `role` replica/this-server/slot, `state`, `sync`, `lag_seconds`, `lag_bytes`, `unsent_bytes`, `error` as a code and fixed name). New signal keys: `new-connections`, `pooled-reuse` (SQL Server), `session-length` and `sessions-abandoned` (Postgres 14+), `thread-cache-misses`, `aborted-connects`, `aborted-clients` (MySQL/MariaDB). The MCP `waits` tool returns `storage` (average read and write per file in words) and `replication`.
Query JSON (`top`, MCP `query`) carries `costs`: `failed`, `aborted`, `aborted_mean_ms`, `warnings`, `top_error`, `plan_ms`, `plans`, `jit_ms`, `jit_functions`, `log_bytes`, `log_share`, `log_full_pages`, `row_bytes` — `null` where the engine doesn't keep it (PostgreSQL has no per-statement error count, MySQL no planning time or redo bytes). Snapshots carry `constraints[]` (untrusted or not validated), `histograms` (MySQL 8 / MariaDB; `null` where there are none to read), `tables[].storage` (Postgres `hot_updates`, `new_page_updates`, `fillfactor`, estimated `bloat_bytes`) `tables[].in_row_bytes`, `lob_bytes` and `overflow_bytes` (how a table's own data splits between its rows and large values kept apart from them: SQL Server LOB and row-overflow pages, PostgreSQL TOAST; `null` on MySQL), `sizes_before` (each table's data size at the previous scan, which `large-rows` reports growth from), `indexes[].contention` (SQL Server lock and latch waits, `lock_escalations` and `lock_escalation_attempts`, `sequential_key`; `lock-escalations` reports escalations only, since the attempt counter moves with SQL Server's own background work) and `indexes[].created_at_latest` (the latest an index may have been created, set by a scan only when an earlier scan saw its table without it or its table changed before Culprit's first scan; `unused-index` waits until that is a week old). `tuning` carries `recommendations[].score`, `applied_at` and `index` (Azure SQL Database's CreateIndex and DropIndex: `schema`, `table`, `name`, `columns`, `include`) and `forced_plans[].forcing` (`MANUAL` or `AUTO`); `tuning-advice` findings include `forced-scan:` (a forced plan scanning where an index could seek), `forced-plans`, `create-index:()` and `drop-index:.`. On Azure SQL Database `deadlocks` reads an explicitly configured, bounded database-scoped deadlock event session. Findings from them: `failing-query`, `planning-time`, `jit-overhead`, `log-volume`, `lock-time`, `big-result`, `slow-storage`, `connection-churn`, `hot-rows`, `lock-escalations`, `last-page-insert`, `untrusted-constraint`, `missing-histogram`, `hot-updates`, `table-bloat`, `large-rows`, `replica-lag`.
## Actual plans and running statements
```sh
culprit explain shop --query-id 10 --last-actual --json # SQL Server's kept actual plan of the last run (never runs it)
culprit explain shop --sql "SELECT …" --analyze --json # measure once: rolled back / read-only, reads only on production
culprit live shop --progress 64 --json # how far along session 64's statement is
culprit live shop --progress 64 --watch # refresh every second until it finishes
```
Actual plans in JSON carry `actual`: `elapsed_ms`, `cpu_ms`, `logical_reads`, `physical_reads`, `memory_granted_kb` / `memory_used_kb`, `spilled`, `slowest_node` (own time), and `worst_estimate_node` with `worst_estimate` (×, positive = more rows than estimated), measured where the bad estimate *starts*. Text output shows each operator's share of the time when the plan has per-operator timing, of the estimated cost otherwise, and says which.
`--progress` returns `running`, `elapsed_ms`, `cpu_ms`, `logical_reads`, `percent` with `percent_basis`, `hot_node`, `phase`/`phase_percent` (Postgres CREATE INDEX…, MySQL stages), `nodes` (SQL Server: `state` pending/running/done, `rows`, `est_rows` per operator), the `plan`, and a `note` when the engine can only say less. MCP: `last_actual_plan` and `query_progress`.
## What changed between two periods
```sh
culprit changes shop --json # default: the last hour (or since the previous scan) vs before
culprit changes shop --since 2026-10-11T14:00:00Z --json # a deploy: everything after it vs the same length before
culprit changes shop --recent 6h --min-runs 20 --threshold 2
```
`changes` returns `{ connection, engine, source, baseline, recent, baseline_total, recent_total, baseline_coverage, min_executions, threshold, summary, queries, unchanged, notes }`. Each `queries[]` entry has `query_id`, `status` (`regressed`, `new`, `improved`, `stopped`, `not-comparable`, `low-sample`, `unchanged`), `headline` (one sentence, UTC), `baseline` / `recent` (`executions`, `total_ms`, `mean_ms`, `min_ms`, `max_ms`), `ratio`, `impact_ms`, `recent_share`, `plan_switch` (`from`, `to`, `at`, `what`) and `reason` for `not-comparable`. SQL Server answers from Query Store's intervals; Postgres and MySQL from Culprit's saved scans (at least three; scan again to add a point). A query without data in one period is never treated as zero. MCP: `what_changed` (`since`, `recent_hours`, `min_runs`).
Query JSON (`top`, `query`) also carries `runs`, `spread` (`min_ms`; MySQL adds `p50_ms`/`p95_ms`/`p99_ms`, `histogram` as `[low_ms, high_ms, runs]` and `lock_ms`) and, with several plans, `plan_spread[]` (`plan_id`, `runs`, `mean_ms`, `min_ms`, `max_ms`, `stddev_ms`, `compiled`, `variant_query` for SQL Server 2022 parameter-sensitive variants). The `parameter-sensitive` finding names the fast and slow plan and gives a copy-only fix ladder.
## Provider coverage
[Engine parity](/docs/parity.md) indexes the setup, sources, operations, limits and verified versions for every provider.
Use the report's product, version, capabilities and source coverage when deciding which operations are available.
A shared engine identifier does not make every product's syntax or measurements interchangeable; the provider guides
explain automatically detected integrations and product-specific JSON fields.
## Offline and CI
```sh
culprit analyze report-or-snapshot.json --json # re-run the checks on a saved file, no database
culprit lint-sql shop-staging --file migrations/ --fail-on high # lint migration files offline against the latest snapshot
culprit lint-sql shop-staging --file migrations/ --write # rewrite fixable DDL in place with safe online syntax
culprit lint-sql shop-staging --file migrations/ --format sarif > db.sarif # SARIF 2.1.0 for GitHub PR annotations
culprit scan staging --fail-on high # exit 3 when something high-impact appears
culprit findings staging --format md # markdown table for a PR comment
```
Reports are stored per connection under `~/.local/share/culprit/reports//` (or `$CULPRIT_HOME/reports/`).
### A scheduled digest
`culprit digest` turns a scan into a few facts for a job to post (Slack, Teams, an issue): counts by severity, database time in the last 24 hours against the 24 hours before (`database_time` says it, `day` has the numbers; scan with `--window-days 2` or more for the day before), what changed since the previous digest (`new`, `fixed`, `worse` with the severity it `was`, and `again`: findings counting events since startup, lock escalations today, whose `count` grew since the previous digest, with how many in `count_since`; a count lower than before, or a server start (`server_started_at`) different from the previous digest's, was reset in between, so all of it counts as new; a lock-escalations finding is High when its count grew since the previous digest and Low history when it didn't), and the top findings, one per query, table or index, with the others about the same one in `also` and the finding in full in `detail` (summary, numbers, each query's statement and the plan step to look at, the fix, how to verify it, what to check first: the app's finding view as data, for a thread reply per finding). It also holds `top_queries`, the queries that used the most database time over the window (`--top-queries`, 5 by default, 0 leaves them out), each with what it does (`label`), its statement on one line, the tables it names, its share of database time, runs and average time, and the ids of the findings about it; `index_advice`, the index advisor's plan, with indexes to `create` (table, keys, includes, who asks for it, why, the CREATE statement) and to `drop` (unused, duplicate, prefix, overlap, with size and why), Azure SQL's own recommendations included, each list capped by `--top` with `create_total` and `drop_total` counting all of them; and `deadlocks`, the scan's deadlocks grouped by pattern on the same tables (the two statements, the lock modes they waited for, the explainer's headline and fix), with `new_since` counting the ones after the previous digest's scan. When deadlocks couldn't be read (a missing permission, Postgres keeping only a counter), `count` is null and `note` says why, rather than reporting none. A scan reads deadlocks over its whole window, a day at least. It is always JSON, and it reads saved reports only, never the database; formatting is the consumer's job.
```sh
culprit digest staging # latest scan vs the scan before it with the same window
culprit scan staging --window-days 1 --json --full > report.json # or --window 6h for the last six hours
culprit digest --report report.json --since previous-digest.json > digest.json # CI: keep digest.json for the next run
```
Keep the digest between runs, not the report: a report holds the parameter values plans were compiled for and statements as the server saw them, which can include data the application sent. A digest is redacted: statements, plan predicates and the SQL quoted in its prose have their literal values replaced with placeholders, and parameter values are never in it. Reports given to `--report` or `--since` are re-checked with the current checks, so a finding means the same thing on each side. `--top` caps each list (5 by default). Text in it comes from the database (table names, query handles): escape it for the place you post it.
## JSON shapes
The types are generated from the Rust model into `app/src/gen/*.ts` and are the reference: `Report`, `Finding`, `Snapshot`, `QueryStat`, `Plan`, `PlanNode`, `ServerInfo`, `LiveState`, `ResultSet`.
---
# Evidence and provider coverage
[Engine parity](/docs/parity.md) is the coverage index. Each provider page names its own sources, permissions, measurements
and limits. These rules govern how Culprit interprets evidence across every provider.
## Availability and scope
A missing, denied, failed or truncated source records its own coverage outcome. It does not become a zero value or
prove that a database is healthy. Findings distinguish a measured negative result from missing evidence.
Each report's `assessments` distinguishes findings, assessed checks without a finding, insufficient evidence,
unavailable sources and inapplicable checks. Supported findings can coexist with incomplete evidence. The app's
Check coverage panel and CLI JSON retain the reasons.
A scan describes one database. Server-wide or shared-node measurements stay labeled with that scope and are not
charged to one database or statement. Restricted role visibility and incomplete contributors remain explicit.
## Periods and comparisons
Current allocation, ages and queues describe scan time. Historical totals retain their dates and do not become
selected-window counters. Retained events, query statistics, plan caches and sampled task activity can cover different
periods; Culprit does not substitute one for another.
A counter comparison needs matching identity, scope and reset, monotonically increasing counts, and scans in
chronological order. Distributed counters also need the same complete set of contributing nodes. Without that
evidence, an observation remains context rather than a measured change.
Rates require sufficient dated history. Absence claims such as an index never being read require at least a week of
relevant counters, not merely the time since Culprit was installed or a database was reopened.
## Plans and findings
An estimated or compilation plan is not a trace of an actual execution. Operator timing, measured rows, trigger work
and historical parameter values require the source that recorded them or an explicitly requested measured run.
Trigger timing can overlap its modifying operator and is not blindly added to the tree.
Where the engine supplies its own verdict, that verdict takes precedence over an inference from plan shape. A scan,
ratio, queue, allocation or optimizer cost alone does not establish a bottleneck. Findings state the data period,
confidence, fix and verification, and unavailable evidence prevents an unsupported conclusion.
Query and plan recommendations preserve result semantics, including NULLs, ordering and pagination. Verify equivalent
results, reads and duration under representative data; a changed operator alone is not enough. An inexpensive run can
still expose a scaling risk without establishing an urgent index migration.
## Index availability and maintenance
An index's availability to the optimizer and whether writes maintain it are different facts. The provider supplies
those states. Failed schema reads cannot justify a recommendation based on an absent index, and unknown usage cannot
justify dropping an index as unused.
Advice uses the engine's dialect and the actual table kind, version and recorded definition. Proposed changes are
shown for a person or embedding application to review; scans do not apply them.
## Evidence beyond a scan
Backup recoverability, corruption, filesystem capacity, application transaction boundaries and distributed request
traces need their own evidence. Culprit does not report these areas healthy from their absence. Provider pages explain
which related observations are available and what they cannot establish.
For the implementation and source contracts, see the [architecture](/docs/architecture.md).