Skip to content

fix(cli): keep db dump resources alive through streamed output - #7877

Open
mdonnalley wants to merge 11 commits into
developfrom
mdonnalley/3181
Open

mdonnalley wants to merge 11 commits into
developfrom
mdonnalley/3181

Conversation

@mdonnalley

@mdonnalley mdonnalley commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Moves db dump onto the managed command executor. The handler streams pg_dump output through a scoped byte sink and awaits each stdout write before releasing its resources.

Failure reporting in machine modes

In json and stream-json modes, stdout carries the dump, so db dump failures are reported as follows:

  • A failed pg_dump writes its message to stderr, including when stdout is still empty. No structured error is written to stdout.
  • A failure after partial SQL leaves only the SQL on stdout and writes the message to stderr. Behavior change: no JSON error is appended after the partial SQL.
  • A failure before any byte that is not a pg_dump failure, such as a flag validation error, a container launch error, or an unwritable --file path, is still a structured error on stdout.

Text-mode reporting is unchanged.

An error class opts in to the stderr report by declaring ReportOnStderrId; DbDumpRunError is the only one that does. The first non-empty write to a byte sink reserves stdout for bytes for the rest of the invocation. Both rules are documented in the Failure Reporting section of apps/cli/docs/code-structure.md.

Executor changes

  • Managed handlers without an output schema do not emit a final result.
  • A handler that returns a structured result cannot also write raw bytes to stdout; a non-empty write is rejected before anything reaches stdout.
  • Project cache and telemetry failures during cleanup no longer change the command's outcome, for handlers with or without an output schema.
  • Required resources are released before a failure is reported.

Telemetry

Telemetry now resolves short flag names from command declarations when the command supplies its flag config. This also records previously omitted shorthand, such as projects create -i, under the same name as the long flag. Value redaction is unchanged.

Refs CLI-3181.

@mdonnalley
mdonnalley requested a review from a team as a code owner November 30, 2026 20:13
@github-actions

Copy link
Copy Markdown
Contributor

CLI benchmark (Lightweight Commands): no changes found

Commit 9d792ef against develop at 5d9f611 · 10 runs each · report only, never blocks merging

Command Workload Before After Change
supabase --version version 291 ms 302 ms no real change
supabase --help help 321 ms 316 ms no real change
supabase init init 358 ms 379 ms no real change (+6%, within normal variation)
supabase migration new bench migration-new 343 ms 297 ms no real change (-13%, within normal variation)
supabase config convert config-convert 245 ms 280 ms no real change (+14%, within normal variation)
supabase config validate config-validate 305 ms 278 ms no real change (-9%, within normal variation)
supabase gen types --lang typescript --project-id replayfixtureprojref gen-types 263 ms 280 ms no real change (+7%, within normal variation)
supabase projects list projects-list 245 ms 236 ms no real change
supabase functions list --project-ref replayfixtureprojref functions-list 241 ms 238 ms no real change

API calls: unchanged for all 9 commands.

Binary size: 135.7 MB, unchanged.

Details: timing ranges, API calls per command, slowest phases

Timing ranges

Command Workload Before range After range Change Verdict
supabase --version version 249-486 ms 225-395 ms +11 ms (+4%) within noise
supabase --help help 273-490 ms 273-417 ms -5 ms (-2%) within noise
supabase init init 286-740 ms 302-720 ms +21 ms (+6%) within noise
supabase migration new bench migration-new 252-607 ms 233-367 ms -46 ms (-13%) within noise
supabase config convert config-convert 213-375 ms 233-425 ms +35 ms (+14%) within noise
supabase config validate config-validate 233-422 ms 253-361 ms -27 ms (-9%) within noise
supabase gen types --lang typescript --project-id replayfixtureprojref gen-types 238-333 ms 249-474 ms +17 ms (+7%) within noise
supabase projects list projects-list 206-257 ms 196-261 ms -9 ms (-4%) within noise
supabase functions list --project-ref replayfixtureprojref functions-list 221-367 ms 208-337 ms -3 ms (-1%) within noise

API calls per command

Command Workload Before After Endpoint changes
supabase --version version 0 0
supabase --help help 0 0
supabase init init 0 0
supabase migration new bench migration-new 0 0
supabase config convert config-convert 0 0
supabase config validate config-validate 0 0
supabase gen types --lang typescript --project-id replayfixtureprojref gen-types 2 2
supabase projects list projects-list 1 1
supabase functions list --project-ref replayfixtureprojref functions-list 2 2

Slowest phases

No command moved beyond noise, so there are no phase deltas.

Workflow run

Comment /bench to run the lightweight benchmark (this comment) again on the latest commit, or /bench full to also run the integration-heavy benchmark, which posts in its own comment.

@github-actions github-actions Bot 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.

Superseded by a newer AI review

🤖 AI Review

CLI reference prose guidance: snapshot supabase/supabase@25ceafc supplied to reviewers (advisory, not a style pass).

All four findings are confirmed by source inspection. The schema-backed executor can invoke its failure hook before required services are released and can mix raw bytes with a structured stdout result. Neither path is exercised by a current production schema-backed handler. The review also found that void handlers implicitly inherit db dump’s cleanup policy and that a new test import sits below the fixture declarations. The PR changes no CLI reference prose, and the db dump migration introduces no contradiction with its reference overlay.

Findings

Severity Location Category Sources Claim
🟡 MINOR apps/cli/src/command-internal/command-executor.ts:400 resource-lifecycle codex A schema-backed command can invoke its failure hook before releasing required services when telemetry rejects a flag.
🟡 MINOR apps/cli/src/command-internal/command-executor.ts:283 output-contract codex A schema-backed handler can write raw bytes to stdout and then have the executor append a structured result, producing invalid JSON or NDJSON.
🟡 MINOR apps/cli/src/command-internal/command-executor.ts:297 maintainability claude The executor uses the absence of an output schema to select db dump’s cleanup policy. Every future void managed handler would inherit that policy, so a cache or telemetry cleanup defect could fail an otherwise successful invocation.
⚪ NIT apps/cli/src/commands/db/pull/pull.removed-flag.integration.test.ts:33 style codex The new executor import sits between the fixture constants and the test helper.

Stats

Claude findings: 1 · Codex findings: 3 · Confirmed: 4 · Refuted: 0 · Uncertain: 0


Models: claude-opus-5-5 + gpt-6.2-sol · Trigger: auto · Workflow run

This review runs once per PR. A maintainer can request another with a /ai-review comment.

Comment thread apps/cli/docs/code-structure.md Resolved

@Prashansa-K Prashansa-K 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.

Approving to unblock this.
Added few nit suggestions as comments.

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

Approving so you're unblocked - left a couple of non-blocking comments, feel free to disagree with either

Two smaller things that didn't fit inline:

  • the comment above linkedProjectCache in dump.layers.ts still says the handler caches the linked project, but the executor owns that now
  • not from this PR, but in machine modes a DbDumpRunError still only prints its message, so the IPv6/CA suggestion gets dropped. develop does the same, so it's probably a follow-up rather than something for here

otherwise looks good to me!

An error class can declare ReportOnStderrId so the executor writes its message to
stderr in machine modes instead of a structured error on stdout. DbDumpRunError
declares it, so a failed pg_dump never puts JSON where a script expects SQL.
Removes the onFailureReady hook.
@mdonnalley mdonnalley changed the title chore(cli): keep db dump resources alive through streamed output fix(cli): keep db dump resources alive through streamed output Dec 1, 2026
# Conflicts:
#	apps/cli/src/command-internal/command-executor.ts
#	apps/cli/src/commands/db/dump/dump.handler.ts
#	apps/cli/src/shared/cli/run-output.integration.test.ts
#	apps/cli/src/shared/cli/terminal-response.service.ts
terminalWriter owns the attempt state, writer-defect marking and failure reporting.
byteSink builds withByteSink. No behavior change.
@mdonnalley

Copy link
Copy Markdown
Contributor Author

/ai-review

@github-actions github-actions Bot 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.

🤖 AI Review

CLI reference prose guidance: snapshot supabase/supabase@fcfcd2e supplied to reviewers (advisory, not a style pass).

Confirmed eight distinct findings from both reviews. In machine modes, dump failures can lose recovery guidance, and a failure before the first SQL chunk can send JSON to stdout if cleanup also defects. Optional cache and telemetry work can delay streamed failure diagnostics, and db dump --file announces completion before invocation cleanup finishes. The remaining findings cover three test gaps and a stale telemetry comment. The diff changes no CLI reference prose or overlay behavior and shows no fundamental conflict with pending work on next. Verification was static.

Findings

Severity Location Category Sources Claim
🟡 MINOR apps/cli/src/shared/cli/run.ts:950 error-handling claude Both machine-mode stderr paths discard normalized error suggestions. For example, a bundled Postgres client read failure after partial SQL loses its recovery hint.
🟡 MINOR apps/cli/src/command-internal/command-executor.ts:276 error-handling codex Before the first SQL chunk, a machine-mode dump failure can put a structured error on stdout if cleanup also defects.
🟡 MINOR apps/cli/src/command-internal/command-executor.ts:275 error-handling codex Optional cache and telemetry work can delay the CLI diagnostic for a failed stream.
🟡 MINOR apps/cli/src/commands/db/dump/dump.handler.ts:444 lifecycle codex db dump --file prints its completion message while invocation cleanup is still pending.
🟡 MINOR apps/cli/src/command-internal/command-executor.integration.test.ts:174 test-coverage codex The rejected-output-flag test passes with automatic scope cleanup alone, so it cannot verify the added explicit close or the timing of error reporting.
🟡 MINOR apps/cli/src/commands/db/dump/dump.integration.test.ts:1399 test-coverage codex The dump test for a typed failure after partial output never verifies stderr delivery or the process exit code through the CLI runner.
🟡 MINOR apps/cli/src/telemetry/command-telemetry.unit.test.ts:507 test-coverage codex The rewritten telemetry test drops coverage for db dump -x as dump switches to declaration-based shorthand discovery.
⚪ NIT apps/cli/src/telemetry/command-telemetry.ts:360 documentation claude The global-alias comment now describes a generic helper, and the aliases option omits automatic discovery from command config.

Stats

Claude findings: 2 · Codex findings: 6 · Confirmed: 8 · Refuted: 0 · Uncertain: 0


Models: claude-opus-5-5 + gpt-6.2-sol · Trigger: manual · Workflow run

This review runs once per PR. A maintainer can request another with a /ai-review comment.

Comment on lines +950 to +953
} else if (response === "streaming" && shouldReportFailure(exitCode)) {
yield* Effect.suspend(() =>
output.raw(`${normalizeCause(cause, suggestionContext).message}\n`, "stderr"),
).pipe(Effect.ignoreCause);

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.

🟡 MINOR · error-handling · source: claude

Both machine-mode stderr paths discard normalized error suggestions. For example, a bundled Postgres client read failure after partial SQL loses its recovery hint.

Evidence: apps/cli/src/shared/cli/run.ts:950–953 and apps/cli/src/command-internal/command-executor.ts:279–282 write only message. apps/cli/src/shared/output/normalize-error.ts:188–195 preserves suggestion. apps/cli/src/command-internal/bundled-postgres-client.ts:119–123 and :164–182 attach a suggestion to typed errors from pipe reads and exit-code retrieval.

Suggested fix: Use a shared renderer that includes the normalized suggestion when present and sends the complete diagnostic to stderr.

Comment on lines +276 to +286
if (isMachine(output) && !Cause.hasDies(cause) && !Cause.hasInterrupts(cause)) {
const typed = Cause.findErrorOption(cause);
if (Option.isSome(typed)) {
const error = normalizeCliError(typed.value);
return yield* reportsOnStderr(typed.value)
? writeTerminal(() => output.raw(`${error.message}\n`, "stderr"))
: ignoreStdoutClosed(writeTerminal(() => output.fail(error)));
}
}
const report = response.reportFailure(cause);
yield* isMachine(output) ? report.pipe(Effect.tapCause(markWriterDefect)) : report;

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.

🟡 MINOR · error-handling · source: codex

Before the first SQL chunk, a machine-mode dump failure can put a structured error on stdout if cleanup also defects.

Evidence: apps/cli/src/commands/db/dump/dump.errors.ts:49–56 declares DbDumpRunError as stderr-only. apps/cli/src/command-internal/command-executor.ts:387–392 and :430–434 close the scopes before reporting. The presence of a defect bypasses the stderr check at :276–286. The runner calls output.fail at apps/cli/src/shared/cli/run.ts:884–896, which writes structured output to stdout through apps/cli/src/shared/output/output.layer.ts:662–674 and :761–772.

Suggested fix: Check the typed failures in the cause for a stderr declaration when selecting the destination. Keep the full cause for exit-code selection and diagnostics.

write(response.markAttempt, deliver);
const reportFailure = (cause: Cause.Cause<unknown>) =>
Effect.gen(function* () {
if (yield* Ref.get(attempted)) return;

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.

🟡 MINOR · error-handling · source: codex

Optional cache and telemetry work can delay the CLI diagnostic for a failed stream.

Evidence: apps/cli/src/command-internal/command-executor.ts:265–275 and :296 mark a stream write as an attempt and skip executor reporting after it. The executor awaits cache and telemetry finalization at :370–375 and :406–407 before apps/cli/src/shared/cli/run.ts:888–905 and :938–957 report the failure. The cache can issue a Management API request at apps/cli/src/telemetry/linked-project-cache.layer.ts:113–128.

Suggested fix: Deliver the stream failure after required cleanup and before optional finalization. Record delivery so the runner reports it only once.

}
// Report the absolute output path on stderr.
if (Option.isSome(resolvedFile)) {
yield* writeStderrLine(`Dumped schema to ${bold(resolvedFile.value)}.`);

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.

🟡 MINOR · lifecycle · source: codex

db dump --file prints its completion message while invocation cleanup is still pending.

Evidence: apps/cli/src/commands/db/dump/dump.handler.ts:354–369 scopes the file handle, then :442–445 prints Dumped schema to ... inside the handler. apps/cli/src/commands/db/dump/dump.command.ts:92–96 registers the void handler. apps/cli/src/command-internal/command-executor.ts:387–392 and :430–434 close the handler and required scopes after the message. A local managed-stack dump also opens a scoped stack handle at apps/cli/src/commands/db/dump/dump.handler.ts:154–169, and packages/stack/src/effect.ts:449–458 attaches its owner connection to that scope.

Suggested fix: Deliver the real file-completion message from an executor callback that runs after invocation cleanup succeeds.

Comment on lines +174 to +179
return Effect.gen(function* () {
const error = yield* Effect.flip(
Command.runWith(command, { version: "test" })(["-o", "table"]),
);
expect(error).toBeInstanceOf(InvalidOutputFormatError);
expect(events).toEqual(["acquire", "release"]);

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.

🟡 MINOR · test-coverage · source: codex

The rejected-output-flag test passes with automatic scope cleanup alone, so it cannot verify the added explicit close or the timing of error reporting.

Evidence: apps/cli/src/command-internal/command-executor.integration.test.ts:156–179 records acquisition and release and checks them after Command.runWith returns. apps/cli/src/command-internal/command-executor.ts:346 and :454 already scope the required resources to the executor call. The explicit close is at :419–426.

Suggested fix: Record when the CLI actually delivers the error and assert that release has already occurred. Use a separate assertion if the explicit close is meant to enforce an earlier boundary than the enclosing scope.

Comment on lines +1399 to +1407
it.effect.each(["json", "stream-json"] as const)(
"%s mode: keeps stdout to the partial dump when the container fails mid-stream",
(format) => {
const { layer, out } = setup({ format, isLocal: true, runFails: true, stdout: "partial\n" });
return Effect.gen(function* () {
const exit = yield* dbDump(flags()).pipe(Effect.exit);
expect(failMessage(exit)).toBe("failed to run docker: not found");
expect(out.stdoutText).toBe("partial\n");
expect(out.failures).toEqual([]);

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.

🟡 MINOR · test-coverage · source: codex

The dump test for a typed failure after partial output never verifies stderr delivery or the process exit code through the CLI runner.

Evidence: apps/cli/src/commands/db/dump/dump.integration.test.ts:383–390 emits bytes and then returns the mock's docker: not found error. The test at :1399–1407 invokes the executor through :557–560 and asserts the returned failure and retained bytes. The diagnostic path at apps/cli/src/shared/cli/run.ts:950–953 is outside that helper.

Suggested fix: Use a read or transport failure after a child emits bytes, then assert the partial stdout, stderr diagnostic, and exit code through the CLI runner.

Comment on lines +507 to +521
withCommandTelemetry({
flags: { password: Option.some("secret"), file: Option.some("out.sql") },
config: {
password: Flag.String("password").pipe(Flag.withAlias("p"), Flag.optional),
file: Flag.String("file").pipe(Flag.withAlias("f"), Flag.optional),
},
}),
Effect.provide(
Layer.mergeAll(
analytics.layer,
mockProcessControl().layer,
mockOutput({ format: "text" }).layer,
Stdio.layerTest({
args: Effect.succeed(["db", "dump", "-p", "secret", "-f", "out.sql"]),
}),

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.

🟡 MINOR · test-coverage · source: codex

The rewritten telemetry test drops coverage for db dump -x as dump switches to declaration-based shorthand discovery.

Evidence: The previous test invoked -x public.users and asserted a redacted exclude field. Its replacement at apps/cli/src/telemetry/command-telemetry.unit.test.ts:507–528 tests optional -p and -f. The real -x at apps/cli/src/commands/db/dump/dump.command.ts:35–43 wraps an alias in Flag.atLeast(0) and Flag.mapTryCatch.

Suggested fix: Exercise -x with the same repeatable and mapped flag declaration as db dump and assert that telemetry records exclude with a redacted value.

// "output" }`). Merged ahead of each command's own `aliases` in `extractChangedFlagNames`, so a
// command's own alias still wins on conflict.
const GLOBAL_SHORT_ALIASES: Readonly<Record<string, string>> = (() => {
function shortAliases(params: ReadonlyArray<Param.Any>): Record<string, string> {

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.

⚪ NIT · documentation · source: claude

The global-alias comment now describes a generic helper, and the aliases option omits automatic discovery from command config.

Evidence: apps/cli/src/telemetry/command-telemetry.ts:356–372 places the global-only comment above shortAliases(params). Lines :480–484 apply globals, then aliases derived from command config, then explicit aliases. The option comment at :103–106 mentions only the global merge.

Suggested fix: Move the global-only comment to GLOBAL_SHORT_ALIASES and document that explicit aliases override shorthands discovered from command config.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants