Repository navigation
feat: deterministic machine output, unified exit codes (0-6), and CI setup action - #173
Conversation
…t (A1) - Add --output json/ndjson/table and --quiet flags - Implement deterministic exit codes (0: success, 1: generic, 2: bad args, 3: auth, 4: not found, 5: throttled) - Emit structured JSON errors on stderr during machine modes - Automatically disable ANSI colors and suppress informational output in machine modes
There was a problem hiding this comment.
Pull request overview
Implements a first-cut “machine output contract” for the Cosmos DB Shell by introducing global --output/--quiet flags, adding NDJSON output support, and mapping error conditions to deterministic exit codes intended for CI/CD and automation consumption.
Changes:
- Adds root CLI flags
--output/-oand--quiet/-q, and forcesNoColors+ quiet behavior for machine modes. - Introduces
OutputFormat.Ndjsonplus NDJSON formatting support for JSON-like command results. - Adds exit-code plumbing via
CommandState.ExitCode,ParserErrorCommandState.ExitCode = 2, andErrorCommandState.ExitCodemapping for Cosmos SDK failures and argument errors.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
| CosmosDBShell/Program.cs | Adds root options, machine-mode detection, defaulting to NDJSON in non-interactive runs, and maps parse/connect failures to deterministic exit codes. |
| CosmosDBShell/lang/en.ftl | Adds help strings for --output and --quiet. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs | Implements Quiet suppression for ShellInterpreter.Write* and emits structured JSON errors to stderr in machine modes. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ParserErrorCommandState.cs | Sets parser-error command states to exit code 2. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Core/OutputFormat.cs | Adds Ndjson output format enum value. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ErrorCommandState.cs | Adds exit-code mapping based on exception type / Cosmos status codes. |
| CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs | Adds ExitCode and NDJSON formatting logic; extends SetFormat to accept ndjson. |
Comments suppressed due to low confidence (1)
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs:70
- For an invalid format string,
SetFormatcurrently throwsShellException, which maps to exit code 1 viaErrorCommandState. Since an invalid--outputvalue is a bad-arguments case, throwing anArgumentExceptionhere will allow it to deterministically map to exit code 2.
{
throw new ShellException(MessageService.GetString("error-invalid_output_format", new Dictionary<string, object> { { "format", outputFormat } }));
}
- Handle root System.CommandLine parser errors via JSON serialization to STDERR in machine modes - Propagate COSMOSDB_SHELL_FORMAT automatically to command formatters - Ignore case on JSON/NDJSON format checks - Bypass interactive RBAC prompts in quiet/machine modes - Prevent trailing blank lines in JSON serialization output - Add integration tests for deterministic machine exit codes - Update CLI argument tables in README
|
Can you fix/comment/close the copilot issues - otherwise we can't merge. |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (1)
CosmosDBShell/Program.cs:165
- When
--output json|ndjsonor--quietis used, this early--otelvalidation error still writes plain text to STDOUT (andShellInterpreter.WriteLinecan't honoro.Quietyet becauseShellInterpreter.Instance.Optionsis assigned later). This breaks the machine-output contract by contaminating STDOUT; emit the structured error JSON to STDERR in machine mode.
Environment.ExitCode = 2;
ShellInterpreter.WriteLine(MessageService.GetArgsString(
"otel-error-invalid-endpoint", "endpoint", o.OtlpEndpoint));
return;
}
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 78 out of 78 changed files in this pull request and generated no new comments.
Suppressed comments (2)
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1547
PrintStateclearsOutputRenderedwhen it's already true andmarkAsRenderedis false:
if (state.OutputRendered)
{
state.OutputRendered = markAsRendered; // sets false
return state;
}This defeats the purpose of the flag and can allow already-rendered states to be rendered again later (nested statements, outer ExecuteCommandAsync calls, etc.).
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:203
- The PR description says the
COSMOSDB_SHELL_FORMATenvironment variable was removed, but the newDefaultOutputFormatlogic still explicitly reads it (and new tests cover the fallback). This is a public contract discrepancy: either remove env-var support end-to-end, or update the PR description/docs to reflect that the env var still supplies the session default format (without enabling machine mode).
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 79 out of 79 changed files in this pull request and generated no new comments.
Suppressed comments (3)
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1546
PrintStateclearsOutputRenderedwhen the state is already rendered (state.OutputRendered = markAsRendered). WhenPrintState(state)is called later with the defaultmarkAsRendered: false(e.g. fromExecuteCommandAsync), this resets the flag back tofalse, which can re-enable duplicate rendering if the same state is printed again by a caller/wrapper.OutputRenderedshould never be reset once true; just return early when already rendered.
docs/navigation.md:114- The JSON envelope example hard-codes
"type": "item", but listing commands return differenttypevalues (e.g.,database,container,file,theme). This should use a placeholder like<kind>or a more general example to avoid misleading pipe-path guidance.
README.md:175 - The README says
--outputfalls back toCOSMOSDB_SHELL_FORMAT, but the PR description states that environment variable was removed. Since code/tests still reference the env var fallback, please reconcile the public-facing contract (either update the PR description, or remove the env var fallback everywhere and adjust docs/tests accordingly).
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 79 out of 79 changed files in this pull request and generated 1 comment.
Suppressed comments (3)
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1546
- PrintState clears OutputRendered when called with markAsRendered=false, which can re-enable rendering and cause duplicate output in later PrintState calls. If a state is already rendered, it should remain rendered; at most, callers should be able to additionally mark it as rendered, not unmark it.
README.md:175 - The PR description says the COSMOSDB_SHELL_FORMAT environment variable was removed, but the updated README (and the code in ShellInterpreter.DefaultOutputFormat) still documents/implements it as a fallback. Either the PR description needs updating, or the fallback should be removed from docs+code to match the stated behavior.
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1560 - PrintState treats output as "redirected" only when the shell's internal '>' redirection is used (StdOutRedirect). This misses process-level redirection/piping (Console.IsOutputRedirected / Console.IsInputRedirected), so user-facing RenderUser/highlighting can still run when stdout is redirected, contradicting the documented "user falls back to JSON when redirected/piped" behavior.
ConnectCommand: PrintConnectionInfoAsync had no RenderTabular, so --output table/csv fell back to the generic 9-column JSON-field table (including array-valued readRegions/writeRegions), which wraps long values like the endpoint mid-word on narrow CI consoles. Add a curated 2-column key/value RenderTabular mirroring the existing RenderUser table.
QueryCommandTests: -metrics:File result now carries documents under 'values' (per the standardized {type, values} list envelope documented in CHANGELOG.md), not the old 'documents' key. Update the stale assertion.
Adds command-connect-info-property/-value localization keys for the new table headers.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 79 out of 79 changed files in this pull request and generated no new comments.
Suppressed comments (2)
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1547
- PrintState() clears OutputRendered when it short-circuits a state that was already rendered (because markAsRendered defaults to false). This makes the rendered state look "unrendered" to any later caller and can enable duplicate printing if PrintState is invoked again on the same state. The early-return path should preserve OutputRendered (optionally OR-in markAsRendered), not overwrite it.
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:220 - The PR description states that COSMOSDB_SHELL_FORMAT was removed as a source of truth, but the runtime still reads COSMOSDB_SHELL_FORMAT in DefaultOutputFormat. Please reconcile the public contract: either remove the environment-variable fallback (and update tests/docs accordingly), or update the PR description/docs to reflect that the env var is still supported as a non-machine-mode default format selector.
PrintState: the OutputRendered early-return path reset the flag to markAsRendered's default (false) instead of leaving it true, so a state printed once (e.g. inside a script loop via markAsRendered:true) could be re-rendered by a later PrintState call on the same object. Once rendered, stay rendered. WatchCommand: the trailing render always forced OutputFormat=User with an empty RenderUser whenever stdout wasn't redirected, even when --max bounded the run and populated a real Result. That silently discarded an explicitly requested --format/--output (e.g. 'watch --max=20 --output table'). Only suppress the trailing dump when nothing was collected (the plain unbounded tail case, where there's genuinely no Result to show). docs/navigation.md: generalize the pipe-flow JSON envelope example so it doesn't imply type is always 'item'. Addresses Copilot suppressed/inline review comments on PR Azure#173. A related suggestion (also checking Console.IsOutputRedirected in PrintState's redirected flag) was investigated but not applied: that flag is also used to decide between Console.Out.WriteLine and this.Redirect(), and Redirect() silently no-ops when StdOutRedirect is unset, so folding in process-level redirection detection there discards output for every piped/-c invocation. A correct fix needs a separate flag for the rendering decision; left as a follow-up rather than risking that regression here.
WelcomeCommand called shell.ShowWelcome() directly during ExecuteAsync, writing the raw ANSI banner to Console.Out unconditionally before PrintState ever ran. In machine mode or redirected output (e.g. -c welcome --output json), that leaked the banner ahead of the JSON result, corrupting deterministic stdout. Assign it to RenderUser instead so PrintState's format/redirection/machine-mode policy decides whether to show it, matching the pattern used elsewhere (Connect/Watch). Verified: -c welcome --output json now emits only the clean result on stdout with no ANSI banner; interactive rendering (WelcomeCommandTests) still shows the banner via RenderUser. Addresses a new Copilot review comment on PR Azure#173 (WelcomeCommand.cs).
Copilot review follow-upAlso fixed the two
Went through the suppressed comments from the latest review plus the two comments that were actually posted (WatchCommand.cs, WelcomeCommand.cs). Summary and fixes: Fixed
Investigated, not applied
All changes validated: full offline+emulator suite green (2126 passed / 2 skipped), plus the two originally-failing CI tests ( |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 79 out of 79 changed files in this pull request and generated no new comments.
Suppressed comments (1)
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1593
ShellInterpreter.PrintStatedecides whether to invokeRenderUserand whether to emit ANSI/highlighted output using onlyStdOutRedirectandIsMachineMode. This misses OS-level redirection/piping (Console.IsOutputRedirected/IsInteractiveSession), so a "user" result can still render banners/tables/ANSI into non-interactive stdout (e.g. running the REPL with> out.txt), violating the documented contract thatuserfalls back to plain structured output when stdout is redirected/piped.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 79 out of 79 changed files in this pull request and generated 3 comments.
Suppressed comments (1)
docs/ci.md:38
- This example passes the connection string as an argument inside the
-ccommand text, butCOSMOS_CONNECTIONis an app-level connection string and should be supplied via--connect(matching README and other docs). As written, it suggestsseed.cshexpects a connection string parameter, which is confusing/inconsistent.
|
Addressed the remaining suppressed Copilot documentation finding in 4927d08: the CI seed example now passes COSMOS_CONNECTION through the app-level --connect option before -c, consistent with README.md and docs/programming.md. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 81 out of 81 changed files in this pull request and generated no new comments.
Suppressed comments (4)
CosmosDBShell/Program.cs:167
- When validating --otel, machine-mode detection again relies on args.Contains("-c"), which misses Windows-style "/c". This means "/c" + malformed --otel can emit human text instead of structured JSON error output. Use the parsed ExecuteAndQuit option value instead.
CosmosDBShell/Program.cs:194 - Same "/c" detection issue for the mutually-exclusive -c/-k error path: args.Contains("-c") will not treat Windows-style "/c" as execute-and-quit, so machine-mode callers can get non-structured error output. Use the parsed option values instead of raw args matching.
CosmosDBShell/Program.cs:76 - Machine-mode detection during root parse errors only checks for a literal "-c" in args. On Windows, System.CommandLine accepts "/c" (documented in docs/navigation.md), so parse errors under "/c" will incorrectly fall back to human output instead of structured JSON and exit-code behavior. Prefer deriving execute-and-quit presence from the parsed option result rather than raw args string matching.
This issue also appears in the following locations of the same file:
- line 162
- line 191
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellExitCode.cs:111
- ShellExitCode.IsUsage doesn't treat System.Text.Json.JsonException as a usage error. Many commands wrap invalid JSON input as CommandException(inner: JsonException), and FromException peels the wrapper; those failures will currently map to GeneralFailure (1) instead of UsageError (2), which contradicts the documented contract for bad arguments/syntax errors.
|
Addressed the four suppressed findings from Copilot's 2026-08-20 review in b5988d3: machine-mode checks now derive execute-and-quit state from the parsed option instead of raw argv at all startup error sites, and wrapped JsonException failures now map to usage exit code 2. Added focused /c process coverage and wrapped-JSON classification coverage. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 81 out of 81 changed files in this pull request and generated no new comments.
Suppressed comments (1)
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/WatchCommand.cs:240
- The interactive-only suppression block forces
OutputFormat.Usereven when the user explicitly requested a structured format (e.g.watch --format json/ global--output json). In machine mode this results in no output at all (AnsiConsole writes are suppressed andResultis null), and it violates the comment’s intent that explicit formats must be honored.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 81 out of 81 changed files in this pull request and generated no new comments.
Suppressed comments (2)
README.md:225
- This claims the
useroutput format “automatically falls back to JSON whenever output is redirected, piped”. The current renderer gating inShellInterpreter.PrintStateonly treats the shell’s own>redirection (StdOutRedirect) and machine mode, not OS-level stdout piping/redirection, so this statement is likely inaccurate. Either adjust the docs or update the implementation to detect OS-level redirection/pipes.
README.md:158 - The YAML snippet is copy-pasteable, but the inline comment is contradictory:
version: latestis not “pinning”. Consider wording it as “latest, or pin a tag for reproducible builds” to avoid confusing CI consumers.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 81 out of 81 changed files in this pull request and generated no new comments.
Suppressed comments (1)
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/WatchCommand.cs:241
- This block suppresses the final structured output when
collected == null, butcollectedis only populated when--maxis set or stdout is redirected. In machine mode (--output json/csv,--quiet, bare-c),AnsiConsoleoutput is suppressed, sowatchcan end up producing no deterministic output unless--maxis provided. Consider treating machine mode like redirection (always collect/emit structured output) or explicitly disallowing machine-modewatchwithout--max.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 81 out of 81 changed files in this pull request and generated 1 comment.
Suppressed comments (2)
CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/WatchCommand.cs:1
result.SetFormat(this.OutputFormat)can set an explicit structured format (e.g., JSON/CSV), but theif (!redirected && collected == null)block unconditionally overrides it toUser, contradicting the comment and silently breaking explicit--format json/csvcases. Restrict this override to cases where no explicit format was requested (e.g., checkstring.IsNullOrWhiteSpace(this.OutputFormat)or!result.OutputFormatExplicitlySet), and avoid mutatingOutputFormatwhen the user explicitly selected a structured output mode.
CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs:1- Writing machine-mode errors to
ErrOutRedirectwill throw if the target directory doesn’t exist (or the path is invalid), which can mask the original failure and make error reporting unreliable in automation. Consider ensuring the parent directory exists (when present) before writing, and/or wrapping the file write in a try/catch that falls back toConsole.Error.WriteLine(json)if the redirect write fails.
Description
Implements the deterministic machine-output contract (Wave 1, P0 / #155) plus the stable process exit-code contract and CI install path requested in #176 / #177. Supersedes #182 by folding its remaining extras (
setup-cosmosdb-shellaction +docs/ci.md) onto this branch with the unified exit map.The shell can be safely consumed by CI/CD pipelines, automation tools, and agentic wrappers without output corruption or ambiguous failure states.
Key Changes
1. Global output controls
--output(-o) global option with four formats:user,json,table,csv(aliasesjs,tbl). Tokens are case-insensitive and canonicalized in one place.--quiet(-q) global option that suppresses banners, connection logs, and other informational chatter.--formatis honored alongside the global option; when a command sets it explicitly it wins, otherwise the session default (from--output) is applied once at print time.COSMOSDB_SHELL_FORMATremains supported as a format-only fallback, checked after--output/--formatwhen neither is supplied. Unlike--output, setting it never enters machine mode on its own (no banner/color suppression), so it's safe to export in an interactive shell profile. Seedocs/navigation.md/README for the precedence order.2. Output-rendering architecture (the core refactor)
Replaced the old single
IsPrinted"already printed" flag with a two-delegate rendering model onCommandState:RenderUser— optional human-facing renderer. Invoked only foruserformat on an interactive terminal; never for redirected, piped, or machine-mode output.RenderTabular— optionalTabularDataprovider that feeds both CSV and Table from one source.Result(ShellJson/ShellText) is always available forjson/machine consumption independent of the interactive renderer.list,dir,info,sproc,udf,trigger,throughput,bucket,theme,connect,disconnect,help,watch, delete/create family,pwd,cls,exit,edit,ftab,filter, and more).3. Centralized policy
OutputPolicy— shared machine-mode / structured-format decisions for startup and runtime.OutputFormats.TryParse— canonical format vocabulary/aliases.json/csvare machine formats;user/tableare human-facing.4. Unified process exit codes (
ShellExitCode)Classification is centralized in
ShellExitCode.FromException/FromCommandState(used byErrorCommandState,ParserErrorCommandState, andProgram):0Success1GeneralFailure2UsageError3AuthFailure401/403,AuthenticationFailed,CredentialUnavailable4ConnectionError503/408/504, Cosmos timeout messages5NotFound4046Throttled429/ RU budget exceededPublic contract: existing codes are never repurposed; new categories get new codes. Codes propagate to
%ERRORLEVEL%/$LASTEXITCODE.5. Machine-mode protections
--quiet, structured--output json|csv, or bare-c(defaults to JSON).{"status":"error","error":"..."}on STDERR in machine mode (honors2>redirection).6. CI install path (ported from #182)
.github/actions/setup-cosmosdb-shellcomposite action: download/cache self-contained release binary, addcosmosdbshelltoPATH(no .NET SDK on the runner).docs/ci.md— install guide, exit-code contract (0–6), CI auth patterns, retry guidance.Tests
OutputPolicyTests/ expandedOutputFormatTestsShellExitCodeTests— unit coverage for the 0–6 classifier (auth vs connection, not-found, throttle, usage, wrappers)ShellProcessTests— process-level exit codes, ANSI-free STDOUT, JSON-on-STDERROutputRedirectionTests— stdout/stderr redirection in machine modeDocs
docs/navigation.md— machine mode + exit tabledocs/ci.md— CI install, auth, failure handlingREADME.md—--output/--quiet, exit table, setup action.github/actions/setup-cosmosdb-shell/README.mdCHANGELOG.mdUnreleased entriesValidation
-c/ structured--output json|csvproduce parseable machine output; bare-cdefaults to JSONSupersedes
Closes the remaining scope of #182 (setup action + CI docs). Exit-code numbering here replaces #182's earlier 0–4 map — do not merge #182 after this.
Follow-ups already applied on branch
RenderTabularcleared at statement boundariesconnect <endpoint>success payload normalized to{ "connected": true, "endpoint": "..." }main; welcome command reconciled withRenderUserShellExitCodehelper (auth ≠ connection; keep NotFound/Throttled)