Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions apps/cli/src/commands/experimental/compute/compute.format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,23 @@ export function renderComputeDetails(rows: ReadonlyArray<readonly [string, strin
const width = Math.max(...present.map(([label]) => label.length));
return `${present.map(([label, value]) => ` ${label.padEnd(width)} ${value}`).join("\n")}\n`;
}

/**
* A wait, for the deploy summary: `48s`, `3m21s`, `1h04m`.
*
* Whole seconds throughout — these measure a server-side build and rollout, where sub-second
* precision would imply the CLI polled far more tightly than it does.
*/
export function formatWaited(millis: number): string {
const total = Math.max(0, Math.round(millis / 1000));
const seconds = total % 60;
const minutes = Math.floor(total / 60) % 60;
const hours = Math.floor(total / 3600);
if (hours > 0) {
return `${hours}h${String(minutes).padStart(2, "0")}m`;
}
if (minutes > 0) {
return `${minutes}m${String(seconds).padStart(2, "0")}s`;
}
return `${seconds}s`;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { renderComputeDetails } from "./compute.format.ts";
import { formatWaited, renderComputeDetails } from "./compute.format.ts";

describe("renderComputeDetails", () => {
it("pads every label to the widest one", () => {
Expand Down Expand Up @@ -32,3 +32,24 @@ describe("renderComputeDetails", () => {
).toBe("");
});
});

describe("formatWaited", () => {
it("reports a sub-minute wait in seconds", () => {
expect(formatWaited(48_000)).toBe("48s");
});

it("pads the seconds so minute-scale waits align in a column", () => {
expect(formatWaited(201_000)).toBe("3m21s");
expect(formatWaited(184_000)).toBe("3m04s");
});

it("drops to minutes past an hour, where the seconds are noise", () => {
expect(formatWaited(3_840_000)).toBe("1h04m");
});

// Rounds rather than truncates, so a poll that lands at 1999ms is not reported as one second.
it("rounds to whole seconds", () => {
expect(formatWaited(1_600)).toBe("2s");
expect(formatWaited(0)).toBe("0s");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ const config = {
Flag.optional,
),
noWait: Flag.Boolean("no-wait").pipe(
// The deploy POST returns once the platform accepts the spec and context; the
// server-side build that follows can run for minutes. Waiting stays the
// default so a plain push reports the build's verdict; `--no-wait` opts out
// for callers that only need the deploy accepted.
// The deploy POST returns once the platform accepts the spec and context; the build and the
// rollout that follows it can run for minutes between them. Waiting stays the default so a
// plain push reports what is actually serving; `--no-wait` opts out for callers that only
// need the deploy accepted.
Flag.withDescription(
"Return once the deploy is accepted, without waiting for the server-side build to finish.",
"Return once the deploy is accepted, without waiting for the new code to roll out.",
),
Flag.withDefault(false),
),
Expand Down
104 changes: 80 additions & 24 deletions apps/cli/src/commands/experimental/compute/push/push.handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { cliConfigFormatForPath } from "@supabase/config/internal";
import { Effect, FileSystem, Option, Path, type Schedule } from "effect";
import { Clock, Effect, FileSystem, Option, Path, type Schedule } from "effect";
import { Output } from "../../../../shared/output/output.service.ts";
import { emitSuccessTrailer } from "../../../../shared/cli/success-trailer.ts";
import { renderComputeDetails } from "../compute.format.ts";
import { formatWaited, renderComputeDetails } from "../compute.format.ts";
import {
emitComputeMachineOutput,
rejectComputeEnvOutput,
Expand Down Expand Up @@ -42,12 +42,14 @@ import {
} from "../../../../shared/compute/compute-runtimes.ts";
import { computeUrl } from "../../../../shared/compute/compute-url.ts";
import {
awaitComputeBuild,
awaitComputeServing,
createComputeUpload,
deployCompute,
isComputeServing,
parseComputeSecretsScopeToAPIFormat,
uploadBuildContext,
type ComputeDeploySpec,
type ComputeRecord,
} from "../../../../shared/compute/compute-api.ts";
import {
NoComputeToDeployError,
Expand Down Expand Up @@ -76,8 +78,9 @@ import type { ComputePushFlags } from "./push.command.ts";
* `supabase compute push [name...]` — deploys the named compute
* (or every compute, if none are named), reading runtime, size, exposure, and
* source from `[compute.<name>]`; an unrecorded runtime is guessed and
* reported. Builds run server-side from an uploaded context and are waited on
* by default; `--no-wait` returns once the deploy is accepted.
* reported. Builds run server-side from an uploaded context, and a plain push waits for the
* deploy's code to actually be serving — the build landing is not the end of it; `--no-wait`
* returns once the deploy is accepted.
*/

const entryRef = ({ format }: ConfigFileRef, name: string): string =>
Expand Down Expand Up @@ -288,6 +291,29 @@ function addYourCode(sourceDisplay: string): string {
return `Add your compute's code to ${sourceDisplay}, then run this command again.`;
}

/**
* The instance row, and the progress line while waiting on a rollout.
*
* Falls back to the declared count alone whenever the tally is absent — it is omitted until the
* first image lands, and replaced by `instances_error` when the control plane's read-through
* fails, neither of which says anything about how many instances are up.
*/
function describeTally(compute: ComputeRecord): string {
const { instances } = compute;
if (instances === undefined) {
return `${compute.spec.instances} declared`;
}
const stale = instances.stale > 0 ? `, ${instances.stale} stale` : "";
return `${instances.ready}/${instances.declared} serving${stale}`;
Comment on lines +301 to +307

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

Push hides instances_error during rollout progress and timeout, obscuring a persistent control-plane tally read failure.

Evidence: apps/cli/src/commands/experimental/compute/push/push.handler.ts:229-235 falls back to ' declared' whenever instances is absent without inspecting instancesError. compute-api.ts:463-466 likewise emits a generic rollout timeout. In contrast, status.handler.ts:140-142 explicitly prints the instancesError value.

Suggested fix: Include instancesError in rollout progress and timeout details when the tally is unavailable.

}

/** `3m21s (1m04s building)`, or just the total when nothing was built. */
function describeWaited(waited: { readonly total: number; readonly build: number }): string {
const total = formatWaited(waited.total);
// Under a second is the poll cadence, not a build worth attributing.
return waited.build < 1000 ? total : `${total} (${formatWaited(waited.build)} building)`;
}

const deployOneCompute = Effect.fn("compute.push.deployOne")(function* (input: {
readonly project: ComputeProject;
readonly name: string;
Expand Down Expand Up @@ -483,25 +509,46 @@ const deployOneCompute = Effect.fn("compute.push.deployOne")(function* (input: {
Effect.tapError(() => deploying.fail()),
);

// Polled only when the deploy response left the build unresolved.
// `V2DeployAWorkerOutput` permits a terminal `active` or `failed` on the
// deploy itself, and that verdict is this deploy's — a fresh `GET` can only
// contradict it: `awaitComputeBuild` reads a post-deploy 404 as "still
// building", so an already-`failed` deploy could burn the whole poll budget
// and surface as a timeout, and a concurrent deployment could answer with a
// state that belongs to someone else's build.
const settled =
input.noWait || accepted.buildState !== "building"
? accepted
: yield* awaitComputeBuild(api, projectRef, name, {
schedule: input.pollSchedule,
retrySchedule: input.pollRetrySchedule,
refSuffix: input.refSuffix,
onPoll: (polled) =>
polled.buildState === "building"
? deploying.message("Building compute...")
: Effect.void,
}).pipe(Effect.tapError(() => deploying.fail()));
// A terminal `active` on the deploy response is no longer a reason to skip the poll. It is
// exactly the case where nothing was built — a bare-image redeploy, or a build skipped as
// unchanged — and the instances go on serving the previous code until the control plane
// recycles them. Stopping there is what let `push` report "Deployed" over a rollout that had
// not started. A `failed` response still short-circuits: that verdict is this deploy's, and a
// fresh `GET` can only contradict it — `awaitComputeServing` reads a post-deploy 404 as "not
// settled yet", so an already-failed deploy would burn the whole poll budget and surface as a
// timeout, and a concurrent deployment could answer with a state belonging to someone else's
// build.
Comment on lines +512 to +520

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 · comments · source: claude+codex

The new rollout comment violates the trusted repository comment policy by recording change history, spanning well beyond two lines, and using the prohibited word 'exactly'.

Evidence: apps/cli/src/commands/experimental/compute/push/push.handler.ts:399-407 describes previous behavior and uses 'exactly'. trusted/CLAUDE.md:98-107 limits inline comments to one or two lines, requires present-tense behavior, and prohibits provenance/history and 'exactly'.

Suggested fix: Replace the block with a short present-tense invariant and move longer rationale to SIDE_EFFECTS.md if needed.

const shortCircuit = input.noWait || accepted.buildState === "failed";

// Transitions as this deploy's own polls saw them, at the poll cadence's resolution. This is
// the only timing available to the CLI: the API publishes no per-stage stamps, so the build
// mark is "when we first observed the image landed", which includes the control plane's own
// detection lag rather than the build alone.
const startedAt = yield* Clock.currentTimeMillis;
let builtAt: number | undefined = accepted.buildState === "building" ? undefined : startedAt;

const settled = shortCircuit
? accepted
: yield* awaitComputeServing(api, projectRef, name, {
schedule: input.pollSchedule,
retrySchedule: input.pollRetrySchedule,
refSuffix: input.refSuffix,
onPoll: (polled) =>
Effect.gen(function* () {
if (polled.buildState === "building") {
return yield* deploying.message("Building compute...");
}
builtAt ??= yield* Clock.currentTimeMillis;
if (!isComputeServing(polled)) {
yield* deploying.message(`Starting instances... ${describeTally(polled)}`);
Comment on lines +538 to +543

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 · user-experience · source: claude

A failed poll briefly renders 'Starting instances...' before the build failure is raised.

Evidence: apps/cli/src/commands/experimental/compute/push/push.handler.ts:425 only special-cases building; failed then reaches lines 429-430 because isComputeServing is false. compute-api.ts:401-402 subsequently settles that failed record, and push.handler.ts:442-449 raises the build error.

Suggested fix: Only emit the instance-starting message when buildState is active.

}
}),
}).pipe(Effect.tapError(() => deploying.fail()));

const finishedAt = yield* Clock.currentTimeMillis;
const waited = shortCircuit
? undefined
: { total: finishedAt - startedAt, build: (builtAt ?? finishedAt) - startedAt };
Comment on lines +527 to +551

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 · correctness · source: codex

Elapsed rollout durations use wall-clock timestamps, so a system-clock adjustment can produce inaccurate or negative machine-output durations.

Evidence: apps/cli/src/commands/experimental/compute/push/push.handler.ts:414, :428, and :435 read Clock.currentTimeMillis, then lines 436-438 subtract those readings. Lines 519 emits the raw results as waited_ms and waited_build_ms; only text formatting clamps negative values.

Suggested fix: Measure elapsed time with a monotonic clock and convert the resulting duration to milliseconds.


yield* Effect.annotateCurrentSpan({
"compute.waited": !input.noWait && accepted.buildState === "building",
Expand Down Expand Up @@ -558,6 +605,11 @@ const deployOneCompute = Effect.fn("compute.push.deployOne")(function* (input: {
// empty-valued row.
["Image", imageVersion ?? ""],
["Access", settled.spec.exposure],
["Instances", describeTally(settled)],
// How long the wait actually took, and how much of it was over before the image
// landed. The API publishes no per-stage timing, so this is the only attribution a
// caller gets for a deploy that felt slow.
["Waited", waited === undefined ? "" : describeWaited(waited)],
Comment on lines +608 to +612

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 · test-coverage · source: claude

The new rendered Waited row and nonzero build split are not asserted by tests.

Evidence: apps/cli/src/commands/experimental/compute/push/push.integration.test.ts:1912-1913 checks only that machine durations are numbers. compute.format.unit.test.ts:36-54 tests formatWaited, but no test exercises describeWaited's 1000ms split or asserts the Waited row rendered at push.handler.ts:489.

Suggested fix: Add focused tests for the Waited row, the sub-second threshold, and a nonzero '(… building)' suffix.

["Secrets Scope", formatSecretsScope(settledSecretsScope ?? "")],
["URL", url ?? ""],
]),
Expand Down Expand Up @@ -586,6 +638,10 @@ const deployOneCompute = Effect.fn("compute.push.deployOne")(function* (input: {
// deploy completed. Same reason `url` is spread below.
...(imageVersion === undefined ? {} : { image_version: imageVersion }),
build_state: settled.buildState,
...(settled.instances === undefined ? {} : { instances_ready: settled.instances.ready }),
...(settled.instances === undefined ? {} : { instances_stale: settled.instances.stale }),
// Flat scalars rather than a nested object: `-o env` and `-o toml` both take this payload.
...(waited === undefined ? {} : { waited_ms: waited.total, waited_build_ms: waited.build }),
...(url === undefined ? {} : { url }),
};
});
Expand Down
Loading