# Admission Control Source: https://docs.cockroachlabs.com/docs/continuum/admission-control # Cockroach Aegis Agentic Ecosystem Source: https://docs.cockroachlabs.com/docs/continuum/aegis-agentic-ecosystem **This feature is in private preview** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. Cockroach Aegis exposes its analysis of your CockroachDB clusters to your own AI agents through a hosted [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) endpoint. An agent such as Claude Code or Codex CLI can retrieve Aegis's cluster and workload reports and its recommendations, and combine that CockroachDB-specific context with application code, metrics, and incident information from your other tools. Benefits of connecting your agent to Aegis include: * Analyzed context. Your agent receives the reports and recommendations that Aegis's CockroachDB-specific agent harness has already produced from its check-ins and investigations, rather than raw database signals. * A standard integration. The endpoint uses MCP over HTTP with OAuth, so it works with any MCP client that supports remote servers. * No cluster access. The Aegis MCP endpoint doesn't interact with your cluster or issue any queries to it, even read-only ones. It gives your agent recommendations and reports that Aegis has already generated, and lets it update recommendation status in Aegis. * Persistent context. [Reports and recommendations](/docs/continuum/aegis-overview#reports-and-recommendations) are stored in the hosted Aegis service, so your agent can retrieve them at any time, including when Aegis cannot currently reach the cluster. This page describes: * Ways to [bring your own agent](#bring-your-own-agent) to Aegis. * How to [connect through MCP](#connect-through-mcp), including setup for [Claude Code](#claude-code-setup) and [Codex CLI](#codex-cli-setup), how to [verify the connection](#verify-the-mcp-connection), and the [available operations](#available-operations). * How to [analyze a workload change through MCP](#analyze-a-workload-change-through-mcp). For information about how Aegis works, see [Cockroach Aegis Overview](/docs/continuum/aegis-overview). For information about connecting a cluster, permissions, and data handling, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). ## Bring your own agent Connect your AI agents to Aegis to use its cluster reports, recommendations, and other context in your existing workflows. For example, you can use Aegis context to: * Review query and schema changes alongside the workload report. * Investigate a capacity problem using the cluster's configuration and resource observations. * Assess cluster health when an incident alert arrives, using Aegis reports and recommendations. * Build an event timeline with Aegis context to identify signals worth investigating. * Compare reports from different environments to find similar anomalies or assess whether CockroachDB contributes to an incident. Aegis gathers observations during check-ins, maintains cluster and workload context, and investigates anomalies. Through MCP, your agent uses the resulting reports and recommendations alongside its own tools and context. The MCP tools return Aegis's stored analysis and are separate from the tools Aegis uses to observe the cluster. Reports and recommendations live in the hosted Aegis service. Aegis needs its connection to the monitored cluster only to make new observations. When that connection is unavailable, your agent can still retrieve the stored reports over MCP. Check their observation times before using them to reason about a live incident. ## Connect through MCP Aegis exposes a hosted MCP endpoint: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} https://aegis.crdb.dev/mcp ``` Use an MCP client that supports remote HTTP servers and OAuth. Aegis supports dynamic client registration, PKCE, refresh tokens, and a consent screen. Authenticate with the CockroachDB Cloud account associated with your Aegis organization. To connect an agent: 1. Connect a cluster to Aegis and allow it to produce its initial reports. For instructions, see [How do I connect a cluster?](/docs/continuum/aegis-security-and-data-access#how-do-i-connect-a-cluster). 2. Add the Aegis endpoint to your agent's MCP client, as described for [Claude Code](#claude-code-setup) and [Codex CLI](#codex-cli-setup). 3. Complete the sign-in and consent flow. 4. Verify access with the read-only instance and report tools, as described in [Verify the MCP connection](#verify-the-mcp-connection). ### Claude Code setup Register the hosted server with your Claude Code client: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} claude mcp add --transport http aegis https://aegis.crdb.dev/mcp ``` Complete the client's OAuth sign-in and consent flow. If the new server's tools do not appear, restart the client. ### Codex CLI setup Register Aegis as a remote HTTP MCP server: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} codex mcp add aegis --url https://aegis.crdb.dev/mcp ``` If registration did not already start the OAuth sign-in flow, start it: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} codex mcp login aegis ``` Sign in with the CockroachDB Cloud account associated with your Aegis organization and complete the consent flow. This sign-in is separate from the cluster's SQL credentials, which the MCP client never needs. ### Verify the MCP connection You can use the following read-only operations to check the connection: 1. Confirm that the client lists the six tools in [Available operations](#available-operations). If tools are missing, verify the remote HTTP URL, inspect the client's startup error, and reload or restart the client after configuration changes. 2. Ask the agent to call `list_instances` and select the intended instance by name. Use the returned Aegis instance `id` for subsequent calls. This is a different identifier from the CockroachDB Cloud cluster ID. 3. Call `get_instance` for that instance to inspect its status and check-in count, and confirm that it is the cluster you intended to monitor. 4. Call `get_reports` for the same instance to retrieve the cluster and workload reports from its latest completed check-in. Check the returned `check_in_id` and `as_of` timestamp. If the first check-in has not yet produced reports, confirm its progress in the Aegis web UI. 5. Call `list_recommendations` for that instance. A successful response can contain an empty list. To interpret that result alongside the reports, see [Why might there be no recommendations?](/docs/continuum/aegis-overview#why-might-there-be-no-recommendations). The `check_in_id` identifies the check-in represented by the response, and `as_of` identifies the report snapshot's timestamp. A check-in can carry reports forward unchanged, so these two fields tell you which check-in you are looking at, and each report's `changed`, `created_at`, and `version_id` fields tell you whether that check-in rewrote it. Read the observation times and metric windows inside each report to see what period it describes. The cluster and workload reports can have different update times. A report retrieved after a workload stops can still describe the running workload, even when the check-in completed after the stop. To confirm recovery, use a report whose observation window covers the period after the workload stopped. For example, try giving the agent this verification request: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Use Aegis MCP to find {workspace_name} with list_instances. Use its returned instance ID to call get_instance, get_reports, and list_recommendations. Report the check_in_id and as_of timestamp, each report's changed, created_at, and version_id fields, and the observation windows inside each report. If there are no recommendations, summarize the reports instead. This is a read-only check: leave recommendation state unchanged. ``` Replace `{workspace_name}` with the cluster's name in Aegis. Tool discovery shows which operations the client knows about, and a successful tool call confirms access to the selected instance. Aegis delivers reports and recommendations through tool calls, so an empty **Resources** or **Resource templates** list in your MCP client is expected. ### Available operations The hosted endpoint exposes the following operations: | Data | MCP tool | Operation | | - | - | - | | Instances | `list_instances` | List instances visible to the signed-in user. | | Instances | `get_instance` | Get an instance's metadata, status, and check-in count. | | Reports | `get_reports` | Get the latest or a specified check-in's cluster and workload reports. | | Recommendations | `list_recommendations` | List recommendations, optionally filtered by status. | | Recommendations | `resolve_recommendation` | Mark an open recommendation done or dismissed. | | Recommendations | `mark_recommendation_read` | Mark a recommendation read or unread. | Resolving a recommendation or marking it read updates Aegis's record of that recommendation. The monitored cluster is unchanged by this action, since you must separately apply any recommended changes through your normal change process. For more information about how Aegis controls access to cluster data, see [SQL permissions and data access](/docs/continuum/aegis-security-and-data-access#sql-permissions-and-data-access). ## Analyze a workload change through MCP This section describes a high-level workflow for comparing Aegis reports from before and after a workload change, to assess the change's effect on query performance and cluster health. The workflow is read-only and assumes a cluster that is already connected to Aegis. For detailed examples that follow this workflow with real workloads and measurements, see [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows). To compare reports around a workload change: 1. Select the intended instance with `list_instances` and retrieve the current reports with `get_reports`. Record the returned `check_in_id` as the baseline. Aegis stores every check-in's reports, so your agent does not need to keep the baseline in its own context; it can retrieve it again later by passing that `check_in_id` to `get_reports`. 2. Make the workload change through your normal operating process, and record its time and application name. The MCP report tools read analysis only; the workload runs separately. 3. Check progress with `get_instance`. After a later check-in completes, retrieve its reports with `get_reports`, and retrieve the baseline reports by passing the baseline `check_in_id`. Confirm that the new reports were updated and that their observations cover the change. If they do not yet cover it, wait for a later check-in and record the gap. 4. Compare workload characteristics, query latency, contention, and cluster resource observations. Distinguish Aegis's stated findings from conclusions your agent infers. When comparing with application measurements, account for differences in observation windows and in units, such as SQL statements per second versus transactions per second. 5. Retrieve recommendations with `list_recommendations` and review any proposed actions alongside the reports. If the list is empty, summarize the available analysis and its limitations. Apply changes through your normal review process. Set meaningful `application_name` values in your application's [SQL connection settings](/docs/stable/connection-parameters#additional-connection-parameters), such as `workload-loader` and `workload-runner`, so that Aegis can distinguish traffic sources in its workload observations. For example, after recording the baseline check-in and making the workload change, ask your agent to assess the evidence: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Use Aegis MCP to retrieve the status, reports, and recommendations for {workspace_name}. Compare the latest reports with the baseline reports from check-in {baseline_check_in_id} and with the workload change at {change_time_utc}. Report the check_in_id, as_of, each report's changed/created_at/version_id, and its observation windows. Explain changes in workload performance and cluster health, separating Aegis's findings from your inferences. If the reports do not yet cover the change, say so. If there are no recommendations, explain the relevant report findings instead. This is a read-only analysis: leave the cluster, the workload, and recommendation state unchanged. ``` Replace `{workspace_name}` with the cluster's name in Aegis, `{baseline_check_in_id}` with the check-in ID you recorded before the change, and `{change_time_utc}` with the workload change's UTC timestamp. To assess recovery after a workload stops, repeat the comparison with reports whose observations cover the period after it stopped. For a worked example, see [Step 6. Check recovery and choose a next action](/docs/continuum/aegis-example-workflows#step-6-check-recovery-and-choose-a-next-action) in the transaction contention workflow. ## See also * [Cockroach Aegis Overview](/docs/continuum/aegis-overview) * [Security and Administration](/docs/continuum/aegis-security-and-data-access) * [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows) # Investigate Workload Performance with Aegis Source: https://docs.cockroachlabs.com/docs/continuum/aegis-example-workflows **This feature is in private preview** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. The example workflows on this page show how to use Cockroach Aegis [reports and recommendations](/docs/continuum/aegis-overview#reports-and-recommendations) alongside your own measurements on a test cluster. In each workflow, you generate a workload, examine the evidence Aegis produces, decide whether a change is appropriate, and check the observations after the workload or configuration changes. This page describes two workflows: * [Understand transaction contention](#understand-transaction-contention): run a small TPC-C workload, read Aegis's analysis of hot-row contention, reduce concurrency, and compare the two phases. * [Review and apply an index recommendation](#review-and-apply-an-index-recommendation): create a table without a secondary index, generate a repeated full-scan query, review Aegis's index recommendation, apply the index, and verify the effect. Both workflows retrieve Aegis's analysis through MCP and apply any changes through a separate SQL connection. Aegis can also explain a workload's behavior without recommending a change, as the contention workflow shows. For information about how Aegis produces reports and recommendations, see [Cockroach Aegis Overview](/docs/continuum/aegis-overview). For MCP setup, see [Connect through MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). ## Before you begin * Use a dedicated, non-production cluster with no other workload. These examples write data and consume cluster resources. The reference contention run used a single-node, 4-vCPU Advanced cluster, which is sufficient for that example. A production configuration would add nodes for fault tolerance and load distribution. * [Connect the cluster to Aegis](/docs/continuum/aegis-security-and-data-access#connect-a-cluster). For a self-hosted cluster, keep the connector running throughout the tutorial. Cockroach Labs manages the connector for Cloud clusters. * Connect an MCP client and verify instance and report access. For instructions, see [Connect through MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). The instructions shown here rely heavily on your agent using MCP. * Install the `cockroach` binary and check `cockroach version`. Each example specifies its workload commands. For more information, see [`cockroach workload`](/docs/stable/cockroach-workload). * Use a separate SQL credential with permission to create the test database, read and write its tables, and create an index when an example requires it. Keep the Aegis connector role at its recommended read-only grants; the workload and any applied changes use this separate credential. * Set `PGURL` to this test cluster's connection URL, initially using `defaultdb`. Omit the password and retain `sslmode=verify-full` and the correct `sslrootcert` path. Supply the workload credential through `PGPASSWORD` using your normal secure credential-loading process, so that the password stays out of command arguments and shell history. For more information, see [Connection parameters](/docs/stable/connection-parameters). * For a CockroachDB Cloud cluster, use the `ccloud` CLI to obtain these values. `ccloud cluster sql --connection-url {cluster_name}` returns a connection URL that already includes `sslmode=verify-full` and the path to the downloaded CA certificate, and `ccloud cluster user create` creates the workload SQL user. For more information, see Get connection information for a cluster and Create a SQL user. ## Understand transaction contention In this example, you will run a small TPC-C workload and use Aegis reports to investigate [transaction contention](/docs/stable/performance-best-practices-overview#understanding-and-avoiding-transaction-contention). You will compare the reports with workload measurements, reduce concurrency, and check whether later observations cover the change. The goal is to understand the evidence Aegis provides, and to understand the workflow. Check [`cockroach workload run tpcc --help`](/docs/stable/cockroach-workload#tpcc-workload) before proceeding. Allow time for data initialization, two 12-minute measurement periods, and Aegis check-ins. The workload commands include a 30-second ramp before each measurement period. A check-in can complete without rewriting its reports, so allow for more than one check-in per phase. ### Step 1. Prepare the test dataset Confirm the SQL target and inspect the existing databases: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} cockroach sql --url "$PGURL" --execute 'SELECT now(), current_user; SHOW DATABASES;' ``` Verify that the host in `PGURL` is the intended test cluster. Choose an unused database name, changing the following example if the name already exists, so that no existing database is overwritten: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} export AEGIS_TPCC_DB='aegis_tpcc_contention' AEGIS_TPCC_ARTIFACTS=$(mktemp -d) export AEGIS_TPCC_ARTIFACTS cockroach workload init tpcc \ --db "$AEGIS_TPCC_DB" \ --warehouses 10 --seed 1 --data-loader IMPORT \ "$PGURL" ``` Initialize the dataset once. Both phases use it, and their transactions will change its data. Wait for initialization to finish successfully before continuing. TPC-C includes payment and new-order transactions that update shared rows. With 10 warehouses, payments update a small set of warehouse totals, and district updates touch a small set of totals and order counters. Concurrent transactions can end up waiting on these rows even when overall CPU utilization is low. For the underlying concepts, read [Understand hotspots](/docs/stable/understand-hotspots), particularly [row hotspots](/docs/stable/understand-hotspots#row-hotspot), and [Understand and avoid transaction contention](/docs/stable/performance-best-practices-overview#understanding-and-avoiding-transaction-contention). ### Step 2. Capture an idle baseline After initialization finishes, select the intended Aegis instance over [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp) with `list_instances` and confirm its identity with `get_instance`. Retrieve `get_reports` and `list_recommendations` for that instance. Save the report bodies, `check_in_id`, and `as_of`, as well as each report's `changed`, `created_at`, and `version_id` fields. Read the observation times inside the reports. Your baseline should describe the idle cluster after initialization. If it still describes initialization or an earlier workload, retain that context and wait for observations of the idle cluster. Aegis checks in automatically. Wait for a scheduled check-in that covers the idle cluster. Retrieving reports through MCP leaves the check-in schedule unchanged. Check progress with `get_instance` before retrieving the completed snapshot. ### Step 3. Run the higher-concurrency phase Record the start time and run TPC-C with 32 active workers: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} date -u '+%Y-%m-%dT%H:%M:%SZ' cockroach workload run tpcc \ --db "$AEGIS_TPCC_DB" --warehouses 10 --seed 1 \ --workers 32 --active-workers 32 --conns 32 \ --wait 0 --max-rate 100 --max-ops 75000 \ --duration 12m --ramp 30s --display-every 30s \ --histograms "$AEGIS_TPCC_ARTIFACTS/32w.json" \ --conn-vars application_name=aegis-docs-tpcc-32w,statement_timeout=30s \ "$PGURL" ``` The command disables TPC-C think time and caps workload operations at 100 per second. These operations are multi-statement transactions, so the rate differs from SQL statements per second, and the cap is an upper bound rather than a guaranteed throughput. This is a contention exercise rather than a compliant TPC-C benchmark or a capacity-sizing test. Watch the output, and stop the workload if it reports errors or the cluster shows unexpected resource pressure. Keep the load as specified; the goal is to see how Aegis gathers evidence, and getting a recommendation is optional. If your cluster can run this workload comfortably, you may not see a recommendation. Save the final totals and the end time after the command exits successfully. While the workload runs, wait for a scheduled check-in that covers the running workload. When it completes, retrieve and save the reports and recommendations through [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp), and confirm that the report bodies describe this application's activity during the run. ### Step 4. Interpret the contention evidence Ask your agent to compare the reports with the baseline using a prompt like the following: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Use Aegis MCP to retrieve get_instance, get_reports, and list_recommendations for {instance_id}. Compare with the saved baseline and the TPC-C run that started at {start_time_utc}, using application_name aegis-docs-tpcc-32w. Report check_in_id and as_of, each report's changed/created_at/version_id, and the observation windows in its body, and confirm that they cover this phase. Explain any evidence of hot rows, lock waits, serialization retries, and resource pressure. Separate Aegis's findings from your own inferences and from the workload runner's measurements. If there are no recommendations, explain the report findings instead. This is a read-only analysis: leave the cluster, the workload, and recommendation state unchanged. ``` Replace `{instance_id}` with the Aegis instance ID and `{start_time_utc}` with the recorded UTC start time. Supply the saved baseline reports in the conversation. In the reference run, Aegis identified contention on `warehouse` and `district` rows, including warehouse payment totals and district order counters. Its cluster report showed CPU and disk headroom. The workload report identified serialization retries and explained why optimizer index suggestions were not promoted into recommendations: those suggestions targeted scan paths that were a small part of the cost in this synthetic workload. What follows are suggestions for interpreting the findings: * Contention on a small set of keys can occur at low overall CPU. Updates to a single [hot row](/docs/stable/understand-hotspots#row-hotspot) serialize on that row, so [adding nodes](/docs/stable/cockroach-start#add-a-node-to-a-cluster) or [an index](/docs/stable/indexes) can address different bottlenecks. * Serialization retries are distinct from failed transactions. The reference workload may have reported zero terminal errors, while Aegis was likely to identify retry events. For more information, see [Transaction retry errors](/docs/stable/transaction-retry-error-reference). * An empty recommendation list can accompany a report with substantial analysis. Read the report for the explanation. * Verify the diagnosis with the cluster's contention and statement-performance views, filtered by the phase's application name and time window, following the instructions in [Monitor and analyze transaction contention](/docs/stable/monitor-and-analyze-transaction-contention). Note that cached contention entries can persist after load stops, so pair them with a time window when reading current contention. ### Step 5. Compare reduced concurrency Wait for the first command to exit. Record the next start time, then repeat the run with 8 active workers: ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} date -u '+%Y-%m-%dT%H:%M:%SZ' cockroach workload run tpcc \ --db "$AEGIS_TPCC_DB" --warehouses 10 --seed 1 \ --workers 32 --active-workers 8 --conns 32 \ --wait 0 --max-rate 100 --max-ops 75000 \ --duration 12m --ramp 30s --display-every 30s \ --histograms "$AEGIS_TPCC_ARTIFACTS/8w.json" \ --conn-vars application_name=aegis-docs-tpcc-8w,statement_timeout=30s \ "$PGURL" ``` Keep `--workers 32`, the warehouse count, and the connection-pool limit unchanged. `--active-workers 8` limits how many workers execute at once while preserving the existing workers' warehouse assignments. The pool closes idle connections, so the live connection count varies under lower load. Run the two phases sequentially on the same dataset. Repeat the check-in and report-retrieval process during this phase. Ask the agent to compare with the higher-concurrency reports, substituting the new application name and start time. Compare measured throughput as well as latency: lower concurrency can reduce contention while also reducing the rate of completed work. #### Reference measurements and limits A reference run we performed produced the following workload-client totals. Each phase had a 12-minute measurement period after a 30-second ramp: | Measurement | 32 active workers | 8 active workers | | - | -: | -: | | Completed transactions | 47,394 | 14,343 | | Transactions/sec | 65.8 | 19.9 | | Overall transaction p99 | 1,140.9 ms | 1,006.6 ms | | New-order transaction p99 | 1,006.6 ms | 738.2 ms | | Terminal workload errors | 0 | 0 | Separate SQL observations showed normalized CPU around 22–23% during the higher-concurrency phase and around 8% during the lower-concurrency phase. Warehouse-update profiles showed average statement service time around 42–44 ms at higher concurrency and 6–7 ms at lower concurrency. These are observations from selected statistics windows rather than whole-run aggregates or Aegis measurements. Throughput fell substantially while the overall client p99 improved modestly. The runs were sequential on a changing dataset, used a laptop client, and were an exercise rather than an isolated capacity benchmark. Statement service latency, sampled contention time, and client transaction latency have different meanings and measurement windows, so compare like with like. In this test, two completed check-ins during the lower-concurrency phase carried the earlier reports forward unchanged. Their `as_of` timestamps advanced, while both report bodies and `created_at` values still described the higher-concurrency phase. For this phase, the direct measurements above stand on their own, and Aegis's analysis of it was unavailable. If your reports are unchanged or do not cover the phase, record the gap. A new check-in ID indicates a new check-in, and each report's `changed` and `created_at` fields show whether its content is new. Wait for an applicable report, or use your existing monitoring tools for the comparison. ### Step 6. Check recovery and choose a next action After the second workload exits, record its end time and verify through your normal monitoring tools that workload traffic subsides. Keep the cluster connected to Aegis, allow time for idle observations, and retrieve reports after a later check-in. Confirm that the report contents cover the period after the stop time. In the reference test, direct SQL observations showed CPU returning to about 1.2%, while the first post-run MCP snapshot still carried the higher-concurrency reports. A later scheduled check-in produced reports describing an idle cluster with near-zero traffic and CPU around 1–3%, which confirmed recovery. Use what you learned to investigate a real workload's conflicting transactions and application requirements. Before choosing a mitigation, see [Reduce transaction contention](/docs/stable/performance-best-practices-overview#reduce-transaction-contention) and [Troubleshoot lock contention](/docs/stable/troubleshoot-lock-contention). Retain the test logs and reports needed for your comparison. Remove the test data and deprovision dedicated test resources through your normal cleanup process when you no longer need them. Note that stopping the TPC-C runs via [`cockroach workload`](/docs/stable/cockroach-workload) still leaves the database and the connector in place, and cloud cluster charges continue to accrue. ## Review and apply an index recommendation In this example, you will create an orders table without a secondary index and run a query that counts a customer's pending orders. You use Aegis to identify the repeated full scan, review its recommendation, apply the index through a separate SQL connection, and compare the query plan and subsequent reports. This complements the [contention example](#understand-transaction-contention): an index lets a selective query skip unrelated rows, while a hot row remains contended regardless of indexing. Aegis recommendations depend on the observed workload and its context, so an [optimizer](/docs/stable/cost-based-optimizer) suggestion is an input to a recommendation. ### Step 1. Create a table without a secondary index Using the separate workload SQL credential, open `cockroach sql --url "$PGURL"`. Verify the intended test cluster and run `SHOW DATABASES`. The following example uses `aegis_index_example`; choose a different name throughout if that database already exists. ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE DATABASE aegis_index_example; CREATE TABLE aegis_index_example.public.orders ( id INT8 PRIMARY KEY, customer_email STRING NOT NULL, product STRING NOT NULL, amount DECIMAL(10,2) NOT NULL, status STRING NOT NULL, created_at TIMESTAMPTZ NOT NULL ); ``` Exit the SQL shell and seed 200,000 synthetic rows in eight batches of 25,000. Run this block in Bash. The subshell stops on the first error; if a batch fails, inspect the partial dataset before proceeding. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ( set -e for low in 1 25001 50001 75001 100001 125001 150001 175001; do high=$((low + 24999)) cockroach sql --url "$PGURL" --execute " SET statement_timeout = '30s'; INSERT INTO aegis_index_example.public.orders SELECT i, 'user' || (i % 1000)::STRING || '@example.com', 'product-' || (i % 50)::STRING, (i % 10000)::DECIMAL / 100, CASE ((i // 1000) % 4) WHEN 0 THEN 'pending' WHEN 1 THEN 'shipped' WHEN 2 THEN 'delivered' ELSE 'returned' END, '2026-01-01'::TIMESTAMPTZ + i * INTERVAL '1 minute' FROM generate_series($low, $high) AS g(i);" done ) ``` Reconnect with `cockroach sql --url "$PGURL"`, collect table statistics, and verify the row count and indexes: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} ANALYZE aegis_index_example.public.orders; SELECT count(*) FROM aegis_index_example.public.orders; SHOW INDEXES FROM aegis_index_example.public.orders; ``` Continue only if the table has 200,000 rows and only the `orders_pkey` index. [`SHOW INDEXES`](/docs/stable/show-index) should return one row per column for that index. No index should yet exist that supports the `customer_email` and `status` filters. Remember to keep the Aegis connector role unchanged for this exercise. ### Step 2. Capture the query plan and Aegis baseline Run this read-only query with [`EXPLAIN ANALYZE`](/docs/stable/explain-analyze), which executes the query and reports its plan and measurements: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} EXPLAIN ANALYZE SELECT count(*) FROM aegis_index_example.public.orders WHERE customer_email = 'user42@example.com' AND status = 'pending'; ``` Save the output. Look for the index used, scan spans, rows decoded from KV, and execution time. In a reference run, the plan scanned all 200,000 rows of `orders_pkey` to find 50 matching orders. Three samples took 82–83 ms of execution time each. Through [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp), select the intended instance with `list_instances` and `get_instance`, then save `get_reports` and `list_recommendations`. Record report and recommendation IDs and timestamps. Existing reports might still describe an earlier workload; use their observation windows to establish the baseline. ### Step 3. Generate observations and retrieve the recommendation Exit the SQL shell. Run the following command in each of two terminals, with the same `PGURL` and securely loaded credential. Record the UTC start time. ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} date -u '+%Y-%m-%dT%H:%M:%SZ' cockroach sql --url "$PGURL" --watch 500ms --execute " SET application_name = 'aegis-docs-index-before'; SET statement_timeout = '30s'; SELECT count(*) FROM aegis_index_example.public.orders WHERE customer_email = 'user42@example.com' AND status = 'pending';" ``` Each command repeatedly runs the same query and returns `50`. This is a small read workload rather than a throughput benchmark. Monitor cluster resources and client errors. [`--watch`](/docs/stable/cockroach-sql#repeat-a-sql-statement) runs until interrupted, so set a 20-minute timer, stay with the test, and stop both clients with **Ctrl+C** when you have the observations you need or the timer expires. Stop sooner if errors or unexpected resource pressure occur. Wait for a scheduled Aegis check-in while the workload is active. After it completes, retrieve `get_reports` and `list_recommendations`. Statistics collection and report updates can take time; leave cluster-wide collection intervals at their defaults. Compare each recommendation's `check_in_id` and timestamps with the report snapshot. In this test, the new recommendation became visible while its check-in was still running, before `get_reports` returned that check-in's completed reports. Report and recommendation reads are separate observations with their own timestamps. Ask your agent to review the evidence using a prompt like the following: ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} Use Aegis MCP to retrieve reports and recommendations for {instance_id}. Find any recommendation about aegis_index_example.public.orders and the aegis-docs-index-before workload that started at {start_time_utc}. Report its identity, timestamps, proposed SQL, affected query, execution count, rows scanned, latency, and the observation windows in the reports. Explain why this index is useful and what storage and write costs it introduces. Distinguish an optimizer suggestion from a recorded Aegis recommendation. This is a read-only review: leave the cluster and recommendation state unchanged. ``` Replace `{instance_id}` and `{start_time_utc}` with your instance ID and recorded UTC start time. In a reference run, Aegis recorded a recommendation citing 603 executions, about 72.6 ms mean statement service latency, and 200,000 rows read per execution. It identified a missing [composite index](/docs/stable/indexes) and explained that the query would be covered without a `STORING` clause. It also noted the modest absolute workload and available cluster headroom. These were Aegis's reported statistics, which differ from the three individual `EXPLAIN ANALYZE` measurements above. If there is no applicable recommendation, inspect the reports, workload activity, permissions, and freshness. Aegis might judge the improvement low priority or retain older reports. Wait for a recommendation that targets this query; an optimizer suggestion alone is an input to Aegis's analysis, and this workflow reviews what Aegis recorded. ### Step 4. Review and apply the index Save the recommendation's ID, status, evidence, and proposed SQL, then stop both baseline clients. Confirm that the recommendation targets your test database and matches the query you measured. Check for an equivalent existing index and review the index's backfill and performance costs. For more information, see [Secondary index best practices](/docs/stable/schema-design-indexes#best-practices), [Index performance trade-offs](/docs/stable/indexes#performance), and [`CREATE INDEX`](/docs/stable/create-index). For the reference dataset, the reviewed recommendation was the following additive change: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} CREATE INDEX ON aegis_index_example.public.orders (customer_email, status); ``` After review and approval, execute the applicable statement through the separate workload SQL connection. Wait for it to complete and check its result before proceeding. If the client command fails or times out, check whether the schema change started before retrying. For more information, see [Online schema changes](/docs/stable/online-schema-changes). Verify the index and result: ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}} SHOW INDEXES FROM aegis_index_example.public.orders; SELECT count(*) FROM aegis_index_example.public.orders WHERE customer_email = 'user42@example.com' AND status = 'pending'; ``` The reference run created `orders_customer_email_status_idx`, and the query still returned `50`. You applied the index through your own SQL connection. Resolving the recommendation through MCP would change only its Aegis state. ### Step 5. Verify the effect and revisit Aegis Repeat the exact `EXPLAIN ANALYZE` query from [Step 2](#step-2-capture-the-query-plan-and-aegis-baseline) without [forcing an index](/docs/stable/table-expressions#force-index-selection). Confirm that the optimizer selects the new index and scans a selective span rather than the whole table. The reference run produced these direct measurements on the same table: | Measurement | Before the index | After the index | | - | - | - | | Selected index | `orders_pkey` | `orders_customer_email_status_idx` | | Rows decoded from KV | 200,000 | 50 | | Bytes decoded from KV | 17 MiB | 3.1 KiB | | Execution time, three samples | 82–83 ms | 0.70–0.73 ms | | Query result | 50 | 50 | Repeat the two-client watch command with `application_name = 'aegis-docs-index-after'`, leaving the query, data, and 500-ms interval unchanged. Set a five-minute timer for this phase and stop both clients when it expires. Record start and end times, and wait for a scheduled check-in covering activity after the index became available. Retrieve [reports and recommendations](/docs/continuum/aegis-overview#reports-and-recommendations) again. Ask your agent to compare with the saved pre-change evidence, using the index-creation time and after-phase application name. Look for evidence that Aegis observed the schema change and the new query behavior. Check recommendation state separately, since Aegis updates its record during a later check-in. Fresh snapshot timestamps indicate a new check-in, and each report's fields and observation windows show whether it contains a new diagnosis. In the reference run, the next requested check-in updated both reports. Aegis identified the index-creation event and completed schema change, reported that the full-scan condition was gone, and noted a latest cluster p99 SQL service latency around 0.84 ms. That cluster percentile is a different measurement from the per-statement mean and individual query execution times above. See the [recommendation in the web UI](/docs/continuum/aegis-overview#find-reports-recommendations-and-activity). That reference-run screenshot uses the database name `aegis_index_20260909` instead of `aegis_index_example`. Retain the recommendation, query plans, report snapshots, and timing notes. Use your normal change process for any real application rollout. Remove the example database and deprovision dedicated test resources when you no longer need them; stopping the query clients leaves both in place. ## See also * [Cockroach Aegis Overview](/docs/continuum/aegis-overview) * [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem) * [Security and Administration](/docs/continuum/aegis-security-and-data-access) * [Understand hotspots](/docs/stable/understand-hotspots) * [Understand and avoid transaction contention](/docs/stable/performance-best-practices-overview#understanding-and-avoiding-transaction-contention) # Cockroach Aegis Overview Source: https://docs.cockroachlabs.com/docs/continuum/aegis-overview **This feature is in private preview** and is only available to enrolled organizations. To enroll your organization, contact your Cockroach Labs account team or [sign up for the preview](https://www.cockroachlabs.com/preview-aegis/). This feature is subject to change. Cockroach Aegis is a managed service that monitors your CockroachDB clusters, investigates changes in cluster health and workload performance, and recommends actions for you to take based on what it finds. It is built on an **agent harness** designed specifically for monitoring and troubleshooting CockroachDB. Aegis supports both proactive tuning and reactive troubleshooting. It can identify opportunities to improve a workload before an incident, or investigate a change in latency, throughput, or cluster health when a problem occurs. It complements your existing monitoring tools with CockroachDB-specific analysis. Benefits of Aegis include: * Continuous, CockroachDB-aware monitoring that builds up context about your cluster over time. * Intelligent alerting and automatic investigations. When Aegis detects an anomaly or a potential issue, it can open an investigation and gather supporting evidence. * Recommendations that include supporting evidence and, where applicable, SQL for you to review and run. Recommendations are the primary information channel that you should pay attention to. * Periodic reports that explain what is happening on the cluster. * [Ask Aegis](#ask-aegis-cluster-aware-qa), a conversational user interface for questions about your cluster. * An [MCP endpoint](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp) that lets your own agents access Aegis's analysis. By default, Aegis's access to your cluster is read-only. It can only make recommendations about changes to make, which you can review and apply through your normal change process. This page describes: * How Aegis monitors your cluster through [check-ins](#automatic-monitoring-through-check-ins). * How [alerts and investigations](#intelligent-alerting-and-investigations) turn detected conditions into analysis. * How to read [reports and recommendations](#reports-and-recommendations). * How Aegis [uses accumulated context](#adaptive-learning), and how to steer it with custom instructions. * How to use the [Aegis web UI](#use-the-aegis-web-ui) and Ask Aegis. For information about connecting agents to Aegis, see [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem). For information about connecting a cluster, permissions, and data handling, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). ## Automatic monitoring through Check-ins Aegis reads cluster signals through a connection to your cluster, and records its analysis in a hosted service maintained by Cockroach Labs. A *check-in* is a periodic review of a cluster and its workload. During a check-in, Aegis compares current signals with its previous observations, refreshes its reports, and investigates conditions that warrant attention. Each check-in starts with Aegis reading the latest cluster and workload reports and any open investigation records, then using its tools to observe the cluster. What it records feeds the next check-in: * *Reports* carry updated cluster and workload context forward. * *Investigations* track deeper analysis of anomalies. * *Recommendations* surface actions for you to take. This cycle lets Aegis follow changes over time rather than analyzing each observation in isolation. Aegis checks in automatically and schedules its next check-in based on what it finds. You do not need to request routine check-ins. A healthy cluster is checked less frequently, and a condition that needs follow-up prompts an earlier check-in. An alert rule can also trigger a check-in ahead of schedule. For example, an alert rule that detects underreplicated ranges can wake Aegis to investigate the change, update the cluster report, and produce a recommendation if action is needed. To inspect check-in progress, open **Home** or the **#check-ins** channel in the [web UI](#use-the-aegis-web-ui). Retrieving a report through MCP returns the latest completed analysis and leaves the check-in schedule unchanged. A check-in can carry an existing report forward unchanged. To find out whether a report reflects a recent change, check the observation times inside the report. When you retrieve reports through MCP, each report's `changed`, `created_at`, and `version_id` fields show whether that check-in rewrote it. For details, see [Verify the MCP connection](/docs/continuum/aegis-agentic-ecosystem#verify-the-mcp-connection). Interpret findings in the context of your cluster's topology and recent changes. For example, a single-node cluster cannot satisfy a [replication factor](/docs/stable/configure-replication-zones#num_replicas) of 3, so Aegis reports its ranges as [underreplicated](/docs/stable/cluster-setup-troubleshooting#replication-issues). That finding reflects a resilience limit of that configuration rather than a new failure. ## Intelligent Alerting and Investigations Aegis uses alert rules and investigations to turn detected conditions into analysis and possible next steps. * An *alert rule* defines a condition to evaluate against cluster metrics or SQL query results. * An *alert* records that a rule's condition was met, and can trigger a check-in. * An *investigation* records Aegis's analysis of a problem across check-ins, including the evidence it gathers and the hypotheses it evaluates. You can inspect investigations in the [web UI](#find-reports-recommendations-and-activity). During a scheduled or alert-triggered check-in, Aegis can open an investigation when a condition warrants further analysis. An alert does not necessarily result in an investigation. Aegis can also create alert rules to monitor conditions it identifies. An investigation tracks the analysis of a condition and has its own criteria for when it is complete. When the analysis identifies an action for you to take, Aegis records a recommendation. An investigation can also conclude without producing a recommendation. ## Reports and Recommendations Aegis produces two kinds of output: reports that describe the cluster and its workload, and recommendations that describe actions for you to take. ### Reports Aegis maintains two reports for each cluster: * The *cluster report* describes topology, configuration, resource utilization, and health. * The *workload report* describes the workloads running on the cluster and their performance characteristics, such as query throughput and latency. Aegis carries these reports between check-ins and updates them as conditions change. Read them in the web UI to understand the latest observed state, or provide them to your own agents through [MCP](/docs/continuum/aegis-agentic-ecosystem#connect-through-mcp). For example, in a [controlled TPC-C test](/docs/continuum/aegis-example-workflows#understand-transaction-contention), the initial reports described an idle cluster. After the workload started, the updated workload report identified TPC-C traffic and attributed increased latency to contention on frequently updated `warehouse` and `district` rows, while the cluster report showed available CPU and disk capacity. Together, the reports distinguished workload contention from resource exhaustion. To reproduce this kind of comparison, see [Analyze a workload change through MCP](/docs/continuum/aegis-agentic-ecosystem#analyze-a-workload-change-through-mcp). ### Recommendations A recommendation contains an action, an explanation of why it matters, and the evidence behind it: the metrics, queries, or statistics Aegis observed, and links to relevant CockroachDB documentation. When the action can be expressed as SQL, the recommendation includes the statement for you to review. Examples include adding or dropping an index, changing a cluster setting, or investigating intermittent node restarts using information from outside the cluster. To act on a recommendation: 1. Review the proposed action and its supporting evidence. 2. Apply the change through your normal review and change process. 3. Compare subsequent reports and workload behavior with the evidence that prompted the change. 4. Mark the recommendation done or dismissed. Aegis never applies its own recommendations. If new information changes the advice, Aegis withdraws the recommendation and records a replacement, preserving the history of the earlier advice. A recommendation is the most important piece of information that Aegis surfaces to you. If you pay attention to nothing else Aegis does, you should read the recommendations. #### Why might there be no recommendations? A check-in can update the reports without identifying an action to recommend. An empty recommendation list means Aegis found nothing to recommend from what it observed. Read the reports for the observations and explanations behind that result, and for any limits on what Aegis could observe. For example, in the TPC-C test described in [Understand transaction contention](/docs/continuum/aegis-example-workflows#understand-transaction-contention), Aegis identified candidate indexes but did not recommend them. Its workload report explained that those indexes targeted queries contributing little to the workload's execution time and would not address the dominant row contention. The report explained the performance issue without proposing an index change. ## Adaptive Learning Aegis uses its history of observations, reports, investigations, and recommendations to keep its analysis specific to your cluster. For example, it detects a workload change by comparing current activity with an earlier report, and it remembers which recommendations it has already made. You can add your own context with **Custom Instructions**, which Aegis includes in every check-in. In the cluster workspace, go to **Custom instructions**, enter the context, and click **Save**. Use custom instructions to add business context that Aegis can't get from the cluster directly, such as a known issue, an intentional configuration choice, a planned migration, or an occasional analytics workload whose longer-running queries are expected. Adaptive learning means accumulating and using this cluster-specific context during analysis. Your cluster metadata and interactions with Aegis are not used to train or fine-tune AI models. For more information, see [How Aegis uses AI](/docs/continuum/aegis-security-and-data-access#how-aegis-uses-ai). ## Use the Aegis web UI The Aegis web UI provides a place to review the connected cluster's state, explore the evidence behind a recommendation, and ask questions through Ask Aegis. To give your own agents access to the same context using tools such as MCP, see [Agentic Ecosystem](/docs/continuum/aegis-agentic-ecosystem). ### Open a cluster workspace After you enroll and connect a cluster, sign in to Aegis with your CockroachDB Cloud account and open the cluster's workspace. The cluster name appears in the workspace header. For prerequisites, see [Security and Administration](/docs/continuum/aegis-security-and-data-access). **Home** summarizes the latest reported cluster and workload state, open recommendations, and recent check-ins. Aegis Home showing the connected cluster's summary, recommendation history, recent check-ins, and workspace navigation. *Home brings together the connected cluster's latest summary, recommendations, and check-in history.* ### Find reports, recommendations, and activity Use the workspace navigation to find the information relevant to your task: | Destination | Use it to | | - | - | | **Home** | Review the current summary, recommendations, and recent check-ins. | | **Recommendations** | Read an action's supporting evidence, proposed SQL, and status, and, for withdrawn recommendations, the reason the action no longer applies. | | **#check-ins** | Review the history of check-ins. Use an entry's **Updated reports** and **Transcript** controls to inspect its reports and activity. | | **Alerts** | Inspect the alert rules Aegis monitors and their current state. | | **Custom instructions** | Provide ongoing cluster context for check-ins, as described in [Adaptive Learning](#adaptive-learning). | Aegis Recommendations showing the index recommendation as withdrawn after index creation, while retaining its reason, original finding, supporting evidence, and proposed SQL. *An index recommendation after the index was applied. Aegis retains the finding, evidence, and proposed SQL, marks the status `withdrawn`, and records the reason the action no longer applies.* When investigations are open, they appear in the **Investigations** section. For more information, see [Intelligent Alerting and Investigations](#intelligent-alerting-and-investigations). Check-ins run automatically. If you need an additional check-in, click **Check in** in the **Check-in cadence** panel. For worked examples of interpreting contention and acting on an index recommendation, see [Investigate Workload Performance with Aegis](/docs/continuum/aegis-example-workflows). ### Ask Aegis: Cluster-aware Q\&A To open Ask Aegis, select **#ask-aegis** in the workspace's **Channels** section. Ask a question about the cluster, or follow up on a report or recommendation. Ask Aegis has access to the same cluster context and tools that Aegis uses during check-ins, and it can consult the CockroachDB documentation to explain its answers. For example, ask: * How is this cluster looking overall right now? * What changed in this cluster's workload since the previous check-in? * What evidence supports this index recommendation? * What did the investigation find about the increase in latency? In the conversation shown below, the answer to the first question described an idle, healthy cluster, noted the single-node cluster's lack of fault tolerance, and cited the cluster and workload reports along with fresh metrics, node-liveness, and event-log observations. When you assess an answer, compare the report times with the observation window it states, since a report and a live observation can describe different periods. Ask Aegis answering a question about the connected cluster's current health, citing observations and noting the single-node cluster's lack of fault tolerance. *An Ask Aegis conversation about a cluster's health, including the answer's stated sources and observation window.* ## Demo video For a demonstration of how to use Cockroach Aegis, watch the following video: