Skip to content

Add query --explain to show execution plan and index usage - #131

Merged
Mike Krüger (mkrueger) merged 17 commits into
mainfrom
dev/mkrueger/query-explain
Aug 28, 2026
Merged

Mike Krüger (mkrueger) merged 17 commits into
mainfrom
dev/mkrueger/query-explain

Conversation

@mkrueger

@mkrueger Mike Krüger (mkrueger) commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Cost-aware: executes only the first page (MaxItemCount = 1) to keep RU cost low. Reported metrics are an estimate based on that page. --max is ignored when --explain is supplied.
  • Human-readable by default: interactive sessions render a Spectre table with verdict lines.
  • Machine-readable when appropriate: MCP (McpPort), output redirection (StdOutRedirect), and explicit --format json emit the structured JSON plan/evaluation document, so AI tool integration is unaffected.

Changes

  • QueryCommand: new --explain option, ExecuteExplainAsync, RenderExplain, BuildExplainJson, and extracted ThrowIfRequestFailedAsync shared with the normal query path.
  • New pure helpers ParseIndexPlan and EvaluatePlan plus the PlanEvaluation record (own file).
  • Localization strings in lang/en.ftl.
  • Docs: docs/commands.md query section and README.md feature list.
  • Unit tests for EvaluatePlan (full scan / index seek / recommendations) and ParseIndexPlan (single + composite specs, null/empty/whitespace, malformed JSON).

Validation

  • dotnet build main + test projects: 0 warnings / 0 errors.
  • QueryCommandTests: 16 passing (8 new).
  • Localization key audit and help verification tests pass.

Example:
image

or as structured output
image

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 QueryCommand with --explain execution path, plan parsing/evaluation helpers, and shared request-failure handling.
  • Introduce PlanEvaluation data model and add unit tests for ParseIndexPlan / 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.
Copilot AI review requested due to automatic review settings June 16, 2026 12:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Copilot AI review requested due to automatic review settings August 25, 2026 09:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

@github-code-quality

github-code-quality Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Code Coverage Overview

Languages: C#

C# / code-coverage/dotnet

The overall line coverage in commit b831900 in the dev/mkrueger/query-e... branch remains at 62%, unchanged from commit fb6d06e in the main branch.

Show a line coverage summary of the most impacted files.
File main fb6d06e dev/mkrueger/query-e... b831900 +/-
D:\a\CosmosDBSh...etionHandler.cs 90% 90% 0%
D:\a\CosmosDBSh...CommandState.cs 88% 89% +1%
D:\a\CosmosDBSh...QueryCommand.cs 39% 41% +2%
D:\a\CosmosDBSh...anEvaluation.cs 0% 100% +100%

Updated August 28, 2026 13:08 UTC

Copilot AI review requested due to automatic review settings August 28, 2026 07:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings August 28, 2026 07:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Copilot AI review requested due to automatic review settings August 28, 2026 08:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 --format value will throw an ArgumentException that bypasses this method’s CommandException("query", …) wrapping (and won’t get the consistent query:-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 --format value can throw outside the CommandException("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
        {
Copilot AI review requested due to automatic review settings August 28, 2026 11:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings August 28, 2026 12:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread docs/commands.md Resolved
Copilot AI review requested due to automatic review settings August 28, 2026 12:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  • ParseIndexPlan marks planAvailable=true for any UtilizedIndexes/PotentialIndexes value that is merely a JSON object, even when it doesn't contain the expected SingleIndexes/CompositeIndexes arrays. In that case the parser extracts zero utilized indexes and EvaluatePlan will report a full scan, contradicting the intended behavior (“unrecognized index metrics payload” should result in unknown scan type / planAvailable=false). Tighten IsIndexGroup to 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;
    }
Copilot AI review requested due to automatic review settings August 28, 2026 12:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  • ExtractIndexSpec returns 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 checks IsNullOrEmpty rather than IsNullOrWhiteSpace. This can yield blank components in the displayed/joined composite spec.
                        var value = path.GetString();
                        if (!string.IsNullOrEmpty(value))
                        {
                            paths.Add(value);
                        }
Copilot AI review requested due to automatic review settings August 28, 2026 12:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) : "-")));
Copilot AI review requested due to automatic review settings August 28, 2026 13:03
@mkrueger

Copy link
Copy Markdown
Collaborator Author

Addressed the latest suppressed Copilot observation in b831900: RenderExplain now passes raw labels and values to Theme.FormatHelpName/Theme.FormatTableValue, which already perform Spectre markup escaping. This prevents double-escaped bracket output. The test project builds with 0 warnings/errors and 25 focused query tests pass.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;
        }
@mkrueger
Mike Krüger (mkrueger) merged commit c2aac52 into main Aug 28, 2026
10 checks passed
@mkrueger
Mike Krüger (mkrueger) deleted the dev/mkrueger/query-explain branch August 28, 2026 13:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants