Skip to content

[API Proposal]: Lazy subcommand registration and lookup on System.CommandLine.Command #2894

In review

Description

@JeremyKuhne

Background and motivation

System.CommandLine.Command currently requires every subcommand subtree to be instantiated up front and added to Command.Subcommands before Command.Parse(...) runs. Constructing a Command in a large CLI typically allocates all of its Option<T> and Argument<T> symbols, nested subcommands, validators, action/completion delegates, and localized .resx Description / HelpName strings—even though CommandLineParser.Tokenize only reads direct child Name and Aliases strings when building ValidTokens(), and ParseOperation never visits unmatched sibling subtrees during parsing, validation, or subcommand --help.

dotnet/command-line-api#1956 previously requested lazy subcommand initialization and was closed pending profiling from a real-world application because the synthetic startup benchmark had no subcommands and no localized strings.

We prototyped this proposal end-to-end in dotnet/command-line-api and dotnet/sdk (dotnet, dotnet-aot, and dotnet-watch), replacing eager top-level subcommand construction and removing dotnet/sdk#56267's two-token <command> --help workaround. In dotnet, DotNetCommandDefinition and Parser define 32 top-level commands, nested subtrees (11 under workload, 8 under tool, 4 under solution), hundreds of options and arguments, localized .resx strings, and Template Engine / NuGet command wiring.

Prototype measurements (dotnet/sdk, Windows x64 Release ReadyToRun)

  1. Exact thread-allocated bytes (GC.GetAllocatedBytesForCurrentThread, warm JIT):

    • Parser.CreateCommand() alone drops from 427,952 B to 14,688 B (-96.6%, 29.1x smaller).
    • Full CreateCommand() + Parse(...) + IsDotnetBuiltInCommand():
      • dotnet --version: 440,600 B -> 27,752 B (-93.7%)
      • dotnet externalcheck --help (external dotnet-* tool dispatch): 441,480 B -> 28,520 B (-93.5%)
      • dotnet sln list: 445,528 B -> 37,080 B (-91.7%)
      • dotnet build app.csproj -c Release: 456,664 B -> 73,472 B (-83.9%)
    • dotnet-watch (CommandLineOptions.Parse(["--quiet", "run", "-c", "Release"])): 453,464 B -> 68,416 B (-84.9%).
  2. Cold-process EventPipe gc-verbose allocation traces & 30-sample interleaved wall-clock latency (comparing pre-dotnet/sdk#56267 eager baseline, dotnet/sdk#56267's 2-token <command> --help workaround, and the System.CommandLine lazy prototype):

    CLI Invocation Baseline Program.Main B dotnet/sdk#56267 Workaround Program.Main B Prototype Program.Main B (vs. Baseline) Baseline Median ms dotnet/sdk#56267 Median ms Prototype Median ms (vs. Baseline)
    dotnet --version 745,552 637,040 106,088 (-85.8%) 230.8 230.2 208.7 (-22.1 ms, -9.6%)
    dotnet build --help 745,320 212,176 212,176 (-71.5%) 251.6 229.9 234.0 (-17.6 ms, -7.0%)
    dotnet build --help --no-restore 753,496 753,520 212,176 (-71.8%) 251.8 251.7 235.0 (-16.8 ms, -6.7%)
    dotnet sln list --help 745,296 637,040 106,088 (-85.8%) 250.7 251.3 232.1 (-18.7 ms, -7.4%)
    dotnet sln list (command execution) 745,320 744,392 106,088 (-85.8%) 249.3 248.6 229.0 (-20.3 ms, -8.1%)
    dotnet reference --help — — — 308.1 285.0 288.8 (-19.2 ms, -6.2%)
    dotnet externalcheck --help 755,808 743,152 212,176 (-71.9%) 294.5 293.3 271.9 (-22.5 ms, -7.6%)

    (Full-process sampled allocations drop by 38.2%–45.8%, from ~1.40 MB to 755–862 KB, where ~545 KB is fixed NativeRuntimeEventSource tracing overhead. NativeAOT dotnet-aot binary size changes by +0.08%, and all 54/54 Managed + NativeAOT output parity scenarios and 3,200+ System.CommandLine / dotnet / dotnet-aot / dotnet-watch tests pass with zero regressions.)

Without support in System.CommandLine, dotnet/sdk#56267 could only optimize exact two-token dotnet <command> <help-option> invocations by constructing a separate minimal RootCommand. As the table shows, that workaround leaves ordinary invocations (dotnet --version, dotnet sln list, external tools, dotnet-watch, and multi-token help) paying the full 32-command cost, breaks ReferenceEquals(cmd, Parser.RootCommand) and global option lookups (DiagOption, CliSchemaOption), and requires duplicate command/alias switches that caused parity regressions during review (dotnet/sdk#57103).

First-class lazy subcommand registration on Command lets ValidTokens() route on (name, aliases) without instantiating unselected subcommands, while keeping a single canonical RootCommand tree across managed, NativeAOT, and nested subcommand paths.

(Related upstream issues: directly addresses dotnet/command-line-api#1956 and avoids eager .resx lookups on unselected subtrees noted in dotnet/command-line-api#1008 and dotnet/command-line-api#1915. HelpBuilder invoking CompletionSources when HelpName is unset—dotnet/command-line-api#1584 / dotnet/command-line-api#2035—is intentionally kept separate from this proposal.)

API Proposal

namespace System.CommandLine;

public partial class Command
{
    public void AddSubcommand(string name, Func<Command> subcommandFactory);
    public void AddSubcommand(string name, ReadOnlySpan<string> aliases, Func<Command> subcommandFactory);
    public bool ContainsSubcommand(string nameOrAlias);
    public bool ContainsSubcommand(string nameOrAlias, StringComparison comparisonType);
    public bool TryGetSubcommand(string nameOrAlias, [NotNullWhen(true)] out Command? subcommand);
    public bool TryGetSubcommand(string nameOrAlias, StringComparison comparisonType, [NotNullWhen(true)] out Command? subcommand);
}

Behavioral specification

  • Registration (AddSubcommand):
    • Validates name and each element of aliases using existing Symbol non-null / non-empty / non-whitespace rules (ArgumentNullException / ArgumentException) and throws ArgumentNullException when subcommandFactory is null.
    • Appends a deferred subcommand entry to Subcommands at the current index without invoking subcommandFactory.
  • Tokenization, parsing, and string-based result lookup:
    • ValidTokens() registers each deferred entry's name and aliases (StringComparison.Ordinal, matching AliasSet and eager Command tokenization) without invoking subcommandFactory.
    • When Tokenize matches a token to a deferred subcommand entry, only that entry is materialized, attached to this as parent (AddParent), and used to tokenize and parse remaining tokens. Unmatched sibling entries and nested deferred subcommands remain unmaterialized.
    • ParseResult.GetResult(string) / GetValue<T>(string) (SymbolResultTree.GetResult(string)) indexes symbols along the parsed CommandResult chain first (falling back to full-tree indexing only when name is absent from all parsed commands), so string-based lookups on parsed commands do not materialize sibling subcommands while preserving existing ArgumentException behavior on unknown names.
  • Materialization invariants and thread safety:
    • Each deferred entry is materialized at most once using LazyThreadSafetyMode.ExecutionAndPublication, preserving thread-safe concurrent Command.Parse(...) calls on a shared static RootCommand.
    • Materialization throws InvalidOperationException if subcommandFactory returns null, returns a Command whose Name does not equal name (StringComparison.Ordinal), returns a Command whose Aliases contain an alias not declared in aliases, or re-enters itself recursively.
    • Any declared aliases not yet present on the returned Command.Aliases are added automatically before publication, so inline factories do not need to repeat aliases while mismatches cannot silently drift.
  • Subcommands (IList<Command>) and Children semantics:
    • Subcommands.Count includes both eager and deferred entries without materializing.
    • Subcommands[index] (getter), Subcommands.GetEnumerator(), Children, and Subcommands.CopyTo materialize accessed deferred entries on demand in registration order. Parent-level help (dotnet workload --help) and parent-level completions (dotnet <TAB>) therefore materialize only direct children of that parent, leaving sibling trees and lazy grandchildren unmaterialized.
    • Subcommands[index] = value, Subcommands.RemoveAt(index), and Subcommands.Clear() mutate slots (detaching Parent on already-materialized entries) without invoking unmaterialized factories. Contains(Command), IndexOf(Command), and Remove(Command) inspect materialized entries without forcing uninvoked factories.
  • Non-enumerating lookup (ContainsSubcommand / TryGetSubcommand):
    • Throws ArgumentNullException if nameOrAlias is null and ArgumentException if comparisonType is not a valid StringComparison. Overloads without comparisonType default to StringComparison.Ordinal.
    • ContainsSubcommand checks direct eager and deferred subcommand names and aliases without materializing any deferred entry.
    • TryGetSubcommand locates a direct subcommand by name or alias, materializes only that entry if deferred, and returns false without materializing anything when unmatched. (Case-insensitive overloads support hosts such as dotnet on Windows/macOS that parse ordinally but check StringComparison.OrdinalIgnoreCase so built-in command names take precedence over external dotnet-* executables on PATH.)

API Usage

1. Multi-command CLI with aliases and nested lazy subcommands

using System.CommandLine;

RootCommand root = new("dotnet");
root.AddSubcommand("build", static () => CreateBuildCommand());
root.AddSubcommand("solution", ["sln"], static () =>
{
    Command solution = new("solution", "Modify solution files");
    solution.AddSubcommand("list", static () => CreateSolutionListCommand());
    solution.AddSubcommand("add", static () => CreateSolutionAddCommand());
    return solution;
});

// Tokenizes "sln" -> materializes only "solution", then "list" -> materializes only "list".
// "build" and "solution add" are never allocated.
ParseResult result = root.Parse(["sln", "list"]);
return result.Invoke();

2. Shared command definitions layered with host-specific configuration (dotnet, dotnet-aot, dotnet-watch)

internal sealed class DotNetCommandDefinition : RootCommand
{
    private readonly Func<Command, Command>? _configureSubcommand;

    public DotNetCommandDefinition(Func<Command, Command>? configureSubcommand = null)
        : base("dotnet")
    {
        _configureSubcommand = configureSubcommand;
        Add(DiagOption);
        Add(VersionOption);

        RegisterSubcommand("build", static () => new BuildCommandDefinition());
        RegisterSubcommand("new", static () => new NewCommandDefinition());
        RegisterSubcommand("solution", ["sln"], static () => new SolutionCommandDefinition());
        // ... remaining top-level commands
    }

    private void RegisterSubcommand(string name, Func<Command> factory) =>
        AddSubcommand(name, _configureSubcommand is null ? factory : () => _configureSubcommand(factory()));

    private void RegisterSubcommand(string name, ReadOnlySpan<string> aliases, Func<Command> factory) =>
        AddSubcommand(name, aliases, _configureSubcommand is null ? factory : () => _configureSubcommand(factory()));
}

// Managed CLI wires handlers, completions, or replacement commands (e.g., `dotnet new`)
// only for the command actually matched during Parse:
RootCommand root = new DotNetCommandDefinition(ConfigureManagedSubcommand);

// Non-enumerating case-insensitive check for built-in vs. external `dotnet-*` tool dispatch:
if (root.TryGetSubcommand(candidateName, StringComparison.OrdinalIgnoreCase, out Command? builtIn))
{
    // Materializes at most `candidateName`; external tools materialize zero subcommands.
}

Alternative Designs

  1. Command.Add(...) overloads instead of AddSubcommand(...):

    public void Add(string name, Func<Command> subcommandFactory);
    public void Add(string name, ReadOnlySpan<string> aliases, Func<Command> subcommandFactory);

    Command implements IEnumerable and exposes Add(Argument), Add(Option), and Add(Command) for C# collection initializers (new RootCommand { { "build", CreateBuildCommand } }). AddSubcommand was chosen as the primary name because existing Add overloads disambiguate child symbol kind by parameter type (Argument vs. Option vs. Command), whereas cmd.Add("build", Create) with a method group hides Command at the call site. Either naming (or both, with Add forwarding to AddSubcommand) works with the same underlying model.

  2. Command.Add(Lazy<Command>):
    Rejected because Lazy<Command> does not expose Name or Aliases without evaluating Lazy<Command>.Value. ValidTokens() would have to materialize every Lazy<Command> on the first token of every parse, defeating lazy initialization.

  3. LazyCommand : Command wrapper or protected virtual void Initialize():
    Rejected for three reasons:

    • Subclass field initializers (such as public readonly Option<string> FrameworkOption = new(...) across SDK *CommandDefinition types) execute when new TCommand() runs, before any virtual Initialize() hook can defer them.
    • A wrapper Command breaks runtime type checks against CommandResult.Command (for example, command is ICustomHelp or command is MSBuildCommandDefinition).
    • Host layers that replace a command definition with a derived or composite Command instance (such as NewCommandFactory.Create(...) in dotnet new) require a Func<Command> factory rather than in-place mutation.
  4. Accepting string? description and bool hidden in AddSubcommand:
    Rejected because passing description: Resources.MyCommandDescription at registration time re-introduces eager .resx ResourceManager lookups on every invocation (dotnet/command-line-api#1008) and duplicates metadata that can drift from the constructed Command. Parent --help and parent-level completions are infrequent interactive operations where materializing only direct children of that parent (without materializing sibling trees or lazy grandchildren) is already bounded.

  5. IEnumerable<string> alias overloads:
    ReadOnlySpan<string> accepts C# collection expressions (["sln"]), string[] (via implicit conversion), and slices across both modern .NET and netstandard2.0 (System.CommandLine already references System.Memory on netstandard2.0), avoiding array allocations when empty or stack-backed.

Risks

  • Deferred factory failures: Invalid Command construction or a Name/alias mismatch inside subcommandFactory throws InvalidOperationException when that subcommand is first materialized rather than during RootCommand construction. Strict Name and Aliases validation on materialization ensures mismatches fail deterministically in command help, schema, or parser tests instead of silently misrouting tokens.
  • Unintended full enumeration via LINQ or missing string-based option lookups: Existing code calling command.Subcommands.FirstOrDefault(...) remains source- and binary-compatible (IList<Command> is unchanged), but enumerating Subcommands materializes entries as visited. Similarly, calling ParseResult.GetResult(string) with an option name that does not exist anywhere along the parsed CommandResult chain must still scan unparsed subtrees to preserve its existing null vs. ArgumentException contract (prototyping in dotnet/sdk caught both Parser.GetBuiltInCommand and ResultNavigationExtensions.SafelyGetValueForOption(string) doing this). ContainsSubcommand, TryGetSubcommand, and CommandResult.Children / typed Option<T> lookups provide explicit non-enumerating paths for startup-critical callers.
  • NativeAOT / trimming: The API uses explicit Func<Command> delegates with no reflection or dynamic code generation, preserving IsAotCompatible and IsTrimmable across System.CommandLine (+0.08% binary delta on dotnet-aot).

Activity

  1. dotnet-policy-service commented on Nov 13, 2026

    @dotnet-policy-service

    Tagging subscribers to this area: @dotnet/area-system-console
    See info in area-owners.md if you want to be subscribed.

  2. JeremyKuhne commented on Nov 13, 2026

    @JeremyKuhne
    MemberAuthor
  3. JeremyKuhne commented on Nov 13, 2026

    @JeremyKuhne
    MemberAuthor

    Additional Measurements: Commands Staying Entirely in NativeAOT (dotnet-aot)

    We also measured commands handled end-to-end inside dotnet-aot without falling back to the managed CLI (--version, sdk check, sln list, build --help, and sln list --help).

    Heap allocations inside CLI_AOT (GC.GetAllocatedBytesForCurrentThread)

    Because Parser.ConfigureAotActions previously iterated rootCommand.Subcommands and walked every subtree (SetAotFallbackRecursively), lazy subcommands cut CLI_AOT heap allocations by 68%–93% (~358–384 KB saved per invocation):

    AOT-Handled Command Variant Parser.CreateCommand() CreateCommand + Parse Full Create + Parse + Invoke Delta vs. Baseline
    dotnet --version Baseline -> Prototype 399,384 B -> 14,704 B 408,864 B -> 24,624 B 411,632 B -> 27,392 B -93.3% (-384 KB)
    dotnet sln list Baseline -> Prototype 399,384 B -> 14,704 B 413,440 B -> 34,296 B 433,184 B -> 54,040 B -87.5% (-379 KB)
    dotnet sln list --help Baseline -> Prototype 399,384 B -> 14,704 B 413,744 B -> 34,608 B 434,504 B -> 55,176 B -87.3% (-379 KB)
    dotnet build --help Baseline -> Prototype 399,384 B -> 14,704 B 424,016 B -> 66,000 B 496,992 B -> 138,888 B -72.1% (-358 KB)
    dotnet sdk check Baseline -> Prototype 399,384 B -> 14,704 B 411,160 B -> 27,720 B 564,712 B -> 181,192 B -67.9% (-384 KB)

    (CreateCommand() alone drops -96.3% (27.2x), from 399,384 B to 14,704 B.)

    Unlike Managed ReadyToRun (which saves 17–22.5 ms), wall-clock time for commands that stay in NativeAOT is flat within ~1 ms measurement noise (~78–80 ms end-to-end process, ~41–43 ms inside dotnet_execute):

    • In Managed ReadyToRun (~230–308 ms): Eagerly instantiating all 32 command definitions and ConfigureManagedActions triggers assembly loads, type-loader/R2R fixups, and Tier-0 JIT across Microsoft.TemplateEngine.*, NuGet.CommandLine.XPlat, and .resx resources—costing ~17–22.5 ms of CPU time.
    • In NativeAOT (~78–80 ms process, ~41–43 ms in dotnet_execute): Every definition is already native x64 code in a single image (zero assembly load, zero type loader, zero JIT, and Template Engine / NuGet XPlat are excluded under CLI_AOT). Bump-allocating ~380 KB in Gen0 without triggering a GC takes < 1 ms in native code, while the ~41 ms inside dotnet_execute is dominated by TelemetryClient / OTel startup in NativeEntryPoint.cs.
  4. transferred this issue fromdotnet/runtimeon Nov 18, 2026
  5. JeremyKuhne commented on Nov 19, 2026

    @JeremyKuhne
    MemberAuthor

    @KathleenDollard @jonsequitur If you have any feedback it would be greatly appreciated :)

  6. adamsitnik commented on Nov 20, 2026

    @adamsitnik
    Member

    Hi @JeremyKuhne

    Thank you for your proposal. I totally see the benefits for dotnet/sdk, but at the same time I believe it's one of very few of our customers who have such large symbol trees. I am not against it, it just seems to be quite niche.

    public bool ContainsSubcommand(string nameOrAlias);
    public bool ContainsSubcommand(string nameOrAlias, StringComparison comparisonType);
    public bool TryGetSubcommand(string nameOrAlias, [NotNullWhen(true)] out Command? subcommand);
    public bool TryGetSubcommand(string nameOrAlias, StringComparison comparisonType, [NotNullWhen(true)] out Command? subcommand);

    Why would you like to expose those APIs? I am just wondering if we should add a possibility to add lazy symbols and make parser aware of them and use similar methods internally or also expose them.

    public void AddSubcommand(string name, Func subcommandFactory);

    In the past, Command was exposing following methods:

        public System.Void AddArgument(Argument argument)
        public System.Void AddCommand(Command command)
        public System.Void AddOption(Option option)

    We have removed them in #1989 in order to comply with the BCL API guidelines (#1987). The idea was simple: if we expose a collection, users can add, remove, iterate and whatever else they need:

    public System.Collections.Generic.IList<Argument> Arguments { get; }
    public System.Collections.Generic.IList<Option> Options { get; }
    public System.Collections.Generic.IList<Command> Subcommands { get; }

    All of them expose IList, because we need to set the parent when they are being added:

    public void Add(T item)
    {
    item.AddParent(_parent);
    _children.Add(item);
    }

    I know that this would be also a breaking change, but I wonder, if we could just expose the internal ChildSymbolList type instead of IList and extend it with the ability to add lazy symbol registrations.

            public void AddLazy(string name, Func<T> factory);
            public void AddLazy(string name, string[] aliases, Func<T> factory);

    Then just make all its methods (indexer, enumeration etc) materialize the symbols when requested via public API, but also expose some internal APIs that would allow the parser to avoid creating them if possible.

    Then all the public APIs should just work:

    public IEnumerable<Symbol> Children
    {
    get
    {
    foreach (var command in Subcommands)
    yield return command;
    foreach (var option in Options)
    yield return option;
    foreach (var argument in Arguments)
    yield return argument;
    }
    }

    This would of course be a breaking change, but 99.99% of users would not encounter any compilation or runtime errors because the type would still implement IList.

  7. adamsitnik commented on Nov 20, 2026

    @adamsitnik
    Member

    This is what I got: #2895

  8. JeremyKuhne commented on Nov 21, 2026

    @JeremyKuhne
    MemberAuthor

    Thanks @adamsitnik! I've dug into this more and I propose narrowing the API in response to your comments: add lazy registration, keep lookup inside the parser, and preserve the existing IList<Command> getter to retain binary compatibility.

    Your collection suggestion supplies the useful mechanism: store registration metadata and materialize real commands when needed. It does not require exposing that collection.

    New proposed surface

    using System;
    using System.Collections.Generic;
    
    namespace System.CommandLine;
    
    public partial class Command
    {
        public IList<Command> Subcommands { get; } // Existing signature, unchanged.
    
        public void Add(string name, Func<Command> commandFactory);
        public void Add(
            string name,
            ReadOnlySpan<string> aliases,
            Func<Command> commandFactory);
    }

    Only the two Add overloads are new.

    An internal compact collection stores eager commands or deferred registrations containing a name, owned aliases, and factory/publication state. Registration validates its inputs and copies caller-mutable alias storage without invoking the factory. Parsing uses the metadata and constructs only the selected real command. The result must be non-null, match the registered name, and introduce no undeclared aliases; validation and parent attachment precede publication. Concurrent first use shares one command or cached failure; same-factory reentry is rejected.

    Count does not materialize commands. Indexing and enumeration materialize visited entries, so help and completion can obtain command metadata. Contains, IndexOf, and Remove inspect eager or published entries without running uncreated factories. Known unselected direct-child result lookup returns null without sibling construction; unknown-name lookup retains the existing compatibility fallback.

    The updated proposal reduces managed GC allocations in my tests by 69-83% and AOT by 51-62%.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions