Repository navigation
Add query --explain to show execution plan and index usage - #131
Conversation
Implements a --explain flag on the query command that reports the query execution plan (utilized/potential indexes, index hit ratio, retrieved/output document counts, request charge) and a plain-language evaluation instead of returning documents. - Executes only the first page (MaxItemCount = 1) to keep RU cost low; reported metrics are an estimate. - Interactive sessions render a human-readable table with verdict lines; MCP, output redirection, and explicit --format json emit structured JSON. - Adds PlanEvaluation record, ParseIndexPlan, and EvaluatePlan helpers with unit tests. - Updates localization strings, docs/commands.md, and README. Closes #106
There was a problem hiding this comment.
Pull request overview
Adds an --explain mode to the existing query command so the shell can report Cosmos DB query execution/index usage (human-readable in interactive sessions, structured JSON for MCP/redirected output), along with the supporting docs, localization, and unit tests.
Changes:
- Extend
QueryCommandwith--explainexecution path, plan parsing/evaluation helpers, and shared request-failure handling. - Introduce
PlanEvaluationdata model and add unit tests forParseIndexPlan/EvaluatePlan. - Update localization strings and user docs (
README.md,docs/commands.md) to describe the new option.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| README.md | Advertises query "<sql>" --explain as a supported feature. |
| docs/commands.md | Documents --explain usage, output intent, and cost/limit behavior. |
| CosmosDBShell/lang/en.ftl | Adds help text and user-facing strings for explain output. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs | Implements explain execution, plan parsing/evaluation, rendering/JSON output, and refactors request error handling. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/PlanEvaluation.cs | Adds a record type to carry explain evaluation data. |
| CosmosDBShell.Tests/CommandTests/QueryCommandTests.cs | Adds unit coverage for explain plan parsing and evaluation behaviors. |
Use the current CommandState structured result and RenderUser model after merging main.
Code Coverage OverviewLanguages: C# C# / code-coverage/dotnetThe overall line coverage in commit b831900 in the Show a line coverage summary of the most impacted files.
Updated |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:593
CreateCommandState(this.OutputFormat)runs before the try/catch, so an invalid per-command--formatvalue will throw anArgumentExceptionthat bypasses this method’sCommandException("query", …)wrapping (and won’t get the consistentquery:-prefixed error handling). Move state creation inside the try block so format parsing errors are handled consistently with other query failures.
This issue also appears on line 655 of the same file.
var returnState = CreateCommandState(this.OutputFormat);
try
{
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:659
- As in the explain path,
CreateCommandState(this.OutputFormat)is executed before the try/catch, so an invalid--formatvalue can throw outside theCommandException("query", …)wrapper and produce inconsistent error reporting. Move the state (and other locals) initialization inside the try block.
var returnState = CreateCommandState(this.OutputFormat);
var aggregatedDocuments = new List<JsonElement>();
try
{
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:351
ParseIndexPlanmarksplanAvailable=truefor anyUtilizedIndexes/PotentialIndexesvalue that is merely a JSON object, even when it doesn't contain the expectedSingleIndexes/CompositeIndexesarrays. In that case the parser extracts zero utilized indexes andEvaluatePlanwill report a full scan, contradicting the intended behavior (“unrecognized index metrics payload” should result in unknown scan type /planAvailable=false). TightenIsIndexGroupto only treat objects as recognized when they are empty ({}) or contain at least one of the expected arrays (and keep supporting the direct array form).
private static bool IsIndexGroup(JsonElement group)
{
return group.ValueKind is JsonValueKind.Object or JsonValueKind.Array;
}
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Suppressed comments (2)
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:416
ExtractIndexSpecreturns raw string values without trimming. If the metrics payload includes leading/trailing whitespace, the explain output will contain inconsistent specs. Trimming here keeps both the human-readable and JSON outputs stable.
if (element.ValueKind == JsonValueKind.String)
{
return element.GetString();
}
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:436
- When extracting composite index specs from
IndexSpecs, the code accepts whitespace-only strings because it checksIsNullOrEmptyrather thanIsNullOrWhiteSpace. This can yield blank components in the displayed/joined composite spec.
var value = path.GetString();
if (!string.IsNullOrEmpty(value))
{
paths.Add(value);
}
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:563
- RenderExplain double-escapes labels/values by calling Markup.Escape before Theme.FormatHelpName/FormatTableValue. Those Theme helpers already apply Markup.Escape internally, so the current code can produce incorrectly escaped output (e.g., literal "[[" sequences) if any localized string/value contains Spectre markup characters. Pass the raw strings to Theme and let it handle escaping once.
Theme.FormatHelpName(Markup.Escape(MessageService.GetString("command-query-explain-utilized"))),
Theme.FormatTableValue(Markup.Escape(evaluation.UtilizedIndexes.Count > 0 ? string.Join(", ", evaluation.UtilizedIndexes) : "-")));
table.AddRow(
Theme.FormatHelpName(Markup.Escape(MessageService.GetString("command-query-explain-potential"))),
Theme.FormatTableValue(Markup.Escape(evaluation.PotentialIndexes.Count > 0 ? string.Join(", ", evaluation.PotentialIndexes) : "-")));
|
Addressed the latest suppressed Copilot observation in b831900: |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/QueryCommand.cs:372
- IsIndexGroup treats any JSON array as a recognized index-metrics group. If Cosmos ever returns an array with unexpected element shapes (e.g., non-string/non-{IndexSpec/IndexSpecs} objects), ParseIndexPlan will mark planAvailable=true but extract no specs, causing EvaluatePlan/BuildPlanMessages to report a full scan instead of the intended “plan unavailable/unknown scan type”. Tighten the array check so planAvailable only becomes true when the array is empty or contains at least one recognizable index spec.
private static bool IsIndexGroup(JsonElement group)
{
if (group.ValueKind == JsonValueKind.Array)
{
return true;
}
Summary
Implements
query "<sql>" --explain, which reports how the query engine resolves a query instead of returning documents. Closes #106.The output shows whether the query performed a full scan or an index seek, lists the utilized and potential indexes, the index hit ratio, retrieved/output document counts, and the request charge, plus a plain-language evaluation that highlights full scans and recommends indexes to add.
Behavior
MaxItemCount = 1) to keep RU cost low. Reported metrics are an estimate based on that page.--maxis ignored when--explainis supplied.McpPort), output redirection (StdOutRedirect), and explicit--format jsonemit the structured JSON plan/evaluation document, so AI tool integration is unaffected.Changes
QueryCommand: new--explainoption,ExecuteExplainAsync,RenderExplain,BuildExplainJson, and extractedThrowIfRequestFailedAsyncshared with the normal query path.ParseIndexPlanandEvaluatePlanplus thePlanEvaluationrecord (own file).lang/en.ftl.docs/commands.mdquery section andREADME.mdfeature list.EvaluatePlan(full scan / index seek / recommendations) andParseIndexPlan(single + composite specs, null/empty/whitespace, malformed JSON).Validation
dotnet buildmain + test projects: 0 warnings / 0 errors.QueryCommandTests: 16 passing (8 new).Example:

or as structured output
