Skip to content

[PM-45308] perf(cli): Exit once a command has finished - #23953

Merged
quexten merged 3 commits into
cli-perf/00-harnessfrom
cli-perf/01-exit-after-command
Oct 21, 2026
Merged

quexten merged 3 commits into
cli-perf/00-harnessfrom
cli-perf/01-exit-after-command

Conversation

@quexten

@quexten quexten commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-45308

📔 Objective

After printing its output, every command idled until leftover timers expired (the desktop IPC discovery timeout and RxJS intervals), ~1.7 s per invocation. The CLI now exits once the command's action resolves, except serve, which keeps running. stdout and stderr are flushed first: a pipe is asynchronous on macOS, and exiting straight away could truncate large output such as list items.

Fixes #14976

⏱️ Benchmark

Before = the previous PR in this stack, after = this PR.

Command Output before Output after Change Exit before Exit after Change
bw get item <id> 2,413 ms 2,304 ms −4% 4,224 ms 2,323 ms −45%
bw get password <id> 2,395 ms 2,317 ms −3% 4,214 ms 2,328 ms −45%
bw list items 3,109 ms 2,939 ms −5% 4,902 ms 2,957 ms −40%
bw status 1,471 ms 1,447 ms −2% 3,217 ms 1,458 ms −55%

Prod build (npm run build:oss:prod) run as node build/bw.js, Node 25.9.0, Apple M5 Pro. Account with 11,996 items on vault.usdev.bitwarden.pw (data.json ~19 MB), Bitwarden Desktop running. Harness apps/cli/perf/bench.mjs: 3 interleaved rounds of 1 warmup + 5 runs per command; fastest run per round, median across rounds. Every run's output is checked.

@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 35.71429% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.29%. Comparing base (ad1c08a) to head (a4008c0).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
apps/cli/src/commands/serve.command.ts 37.50% 10 Missing ⚠️
bitwarden_license/bit-cli/src/bw.ts 0.00% 3 Missing ⚠️
apps/cli/src/bw.ts 0.00% 2 Missing ⚠️
apps/cli/src/serve.program.ts 0.00% 2 Missing ⚠️
apps/cli/src/tools/export.command.ts 0.00% 1 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           cli-perf/00-harness   #23953   +/-   ##
====================================================
  Coverage                59.29%   59.29%           
====================================================
  Files                     4698     4699    +1     
  Lines                   148683   148700   +17     
  Branches                 23712    23713    +1     
====================================================
+ Hits                     88164    88175   +11     
- Misses                   54357    54364    +7     
+ Partials                  6162     6161    -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dani-garcia

Copy link
Copy Markdown
Member

Looks like this will solve this ticket: https://bitwarden.atlassian.net/browse/PM-22141 and the associated GH issue #14976

@quexten
quexten requested a review from dani-garcia October 19, 2026 13:40
@quexten
quexten marked this pull request as ready for review October 19, 2026 13:40
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Bitwarden Claude Code Review

Overall Assessment: APPROVE

I reviewed the new exitAfterCommand helper and its spec, plus the changes to both CLI entry points (apps/cli/src/bw.ts and bitwarden_license/bit-cli/src/bw.ts, which moves from parse to parseAsync). Every registered command action awaits its work before resolving, and processResponse sets process.exitCode rather than exiting. So calling process.exit() with no argument after stdout and stderr flush keeps each command's exit code, including BW_CLEANEXIT. Commander 14 puts the subcommand name at program.args[0] even when global options come before it, so serve is still excluded. State writes go through lowdb's synchronous write(), so exiting early does not drop persisted state.

@quexten
quexten force-pushed the cli-perf/01-exit-after-command branch from 8a0ede1 to ae27c97 Compare October 19, 2026 14:04
@quexten quexten added the t:bugfix Change Type - Bugfix label Oct 19, 2026

@dani-garcia dani-garcia left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The exit looks like a reasonable solution to me, but the handling of long running commands seems more complicated than it needs to be.

Instead of the LONG_RUNNING_COMMANDS allowlist, could serve stay pending until the server stops? Then every command exits the same way: the action resolves, then the CLI flushes and exits.

// serve.command.ts
/** Resolves when the server stops, so `serve` stays pending while it is serving. */
export function untilStopped(source: EventEmitter, description: string): Promise<Response> {
  return new Promise((resolve) => {
    source.once("error", (error: Error) =>
      resolve(Response.error(`Cannot serve on ${description}: ${error.message}`)),
    );
    source.once("close", () => resolve(Response.success()));
  });
}

// in run(): fd+connected ends with its connection
return await untilStopped(socket, hostname);

// other branches: keep the http.Server that koa's listen() returns
const httpServer = server.listen(port, hostname === "all" ? null : hostname);
httpServer.once("listening", () => {
  this.serviceContainer.logService.info("Listening on " + description);
});
return await untilStopped(httpServer, description);
// serve.program.ts
const response = await command.run(cmd);
this.processResponse(response);

The forced exit also could be problematic if there are any unawaited floating promises. I've found these two which now will might not be done on time:

  • export.command.ts:89: eventCollectionService.collect(...).
  • import.command.ts:140: syncService.fullSync(true).

@quexten
quexten requested a review from a team as a code owner October 20, 2026 09:32
@quexten

quexten commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@dani-garcia Makes sense; updated. I also simply awaited the two floating promises. It seems reasonable in the context to await these.

@harr1424 harr1424 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.

Changes to Tools Team owned files look good. Thank you for addressing this!

After printing its output, every command left the process idle until
leftover timers expired: the desktop IPC discovery timeout and RxJS
intervals kept the event loop alive for ~1.7 s per invocation.

Exit explicitly after the command's action resolves, except for serve,
which keeps running. stdout and stderr are flushed first, since a pipe
is asynchronous on macOS and exiting straight away could truncate
large output.
Replace the LONG_RUNNING_COMMANDS allowlist. serve now resolves when
its server closes or errors, so every command exits the same way:
the action resolves, then the CLI flushes and exits.

Await the export event collection and the import sync. The forced
exit could otherwise cut them short.
An earlier commit overwrote the existing serve.command spec. Restore
it and move the untilStopped tests to their own spec.
@quexten
quexten force-pushed the cli-perf/01-exit-after-command branch from 78a3af5 to a4008c0 Compare October 21, 2026 10:42
@quexten
quexten merged commit 0355076 into main Oct 21, 2026
73 of 74 checks passed
@quexten
quexten deleted the cli-perf/01-exit-after-command branch October 21, 2026 11:50
@djsmith85 djsmith85 added the cli CLI Application label Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI Application t:bugfix Change Type - Bugfix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bw list items needs 1s to finish process after output given

4 participants