Skip to content
Merged
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
8 changes: 8 additions & 0 deletions apps/cli/scripts/api-command-reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ const commandSection = (
"",
entry.summary,
"",
...(entry.examples ?? []).flatMap((example) => [
example.description,
"",
"```sh",
example.command,
"```",
"",
]),
...(entry.description === undefined ? [] : [entry.description, ""]),
`- Access: ${entry.readOnly ? "read-only, no consent" : "mutation, consent defaults to No (`--yes` when it cannot prompt)"}.`,
...experimentalLine(entry, input),
Expand Down
27 changes: 26 additions & 1 deletion apps/cli/src/commands/api/api-command-policy.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ApiCommandEntry } from "./api-command.model.ts";
import type { OpenApiOperationId } from "@supabase/api/effect";
import type { ExperimentalFeature } from "../../shared/config/experimental-feature.ts";

Expand Down Expand Up @@ -26,19 +27,43 @@ export const generatedOperations: ReadonlyArray<OpenApiOperationId> = [
"v2-add-warehouse-replication",
"v2-remove-warehouse-replication",
"v2-resync-warehouse-replication",
"v2-restart-warehouse-replication",
];

export interface ApiCommandPolicy {
readonly confirmDescription?: true;
readonly examples?: ApiCommandEntry["examples"];
}

/** CLI presentation choices, independent of the API's operation metadata. */
export const commandPolicies = {
"v2-disable-warehouse": { confirmDescription: true },
"v2-update-warehouse-table-layout": { confirmDescription: true },
"v2-update-warehouse-table-layout": {
confirmDescription: true,
examples: [
{
command: `supabase warehouse tables layout update <table-id> --partition-by '[{"column":"event_at","transform":{"kind":"day"}}]' --sort-by '{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}'`,
description:
"Partition new files by event day and sort within files; preserve historical files.",
},
{
command: `supabase warehouse tables layout update <table-id> --partition-by '[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]' --dry-run`,
description: "Preview eight hash buckets locally without changing the Warehouse.",
},
{
command: `supabase warehouse tables layout update <table-id> --partition-by '[]' --sort-by '{"kind":"none"}'`,
description: "Clear partitioning and sorting for future writes.",
},
{
command: `supabase warehouse tables layout update <table-id> --partition-by 'null' --sort-by 'null'`,
description: "Stop managing both settings; omitted flags preserve their saved values.",
},
],
},
"v2-add-warehouse-replication": { confirmDescription: true },
"v2-remove-warehouse-replication": { confirmDescription: true },
"v2-resync-warehouse-replication": { confirmDescription: true },
"v2-restart-warehouse-replication": { confirmDescription: true },
} satisfies Partial<Record<OpenApiOperationId, ApiCommandPolicy>>;

export const nouns = {
Expand Down
2 changes: 2 additions & 0 deletions apps/cli/src/commands/api/api-command.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ export interface ApiCommandEntry {
readonly name: string;
readonly description?: string;
};
/** Concrete invocation examples maintained by the CLI command policy. */
readonly examples?: readonly { readonly command: string; readonly description: string }[];
readonly flags: readonly ApiCommandFlag[];
readonly bindings: readonly ApiCommandBinding[];
readonly wait?: ApiCommandWait;
Expand Down
197 changes: 196 additions & 1 deletion apps/cli/src/commands/api/api-commands.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,64 @@ describe("generated warehouse commands", () => {
});
});

describe("warehouse replication restart", () => {
const argv = ["warehouse", "replication", "restart"];
const response = {
data: {
type: "warehouse_replication_restart",
id: "pipeline-1",
attributes: {
pipeline_id: "pipeline-1",
action: "start",
application_status: "accepted",
pipeline_status_before: "stopped",
},
},
};

it.effect("sends one restart and returns acceptance without polling old readiness", () => {
const { sent, out, run } = setup(argv, {
yes: true,
route: () => ({ status: 202, body: response }),
outputFormat: "json",
});
return Effect.gen(function* () {
yield* run;
expect(sent).toEqual([
{
method: "POST",
path: `/v2/projects/${VALID_REF}/warehouse/replication/restart`,
search: "",
body: undefined,
},
]);
expect(decodeJson(out.stdoutText)).toEqual(response);
});
});

it.effect("does not retry an uncertain restart", () => {
const { sent, run } = setup(argv, {
yes: true,
route: () => ({
status: 503,
body: { message: "Inspect pipeline state before retrying." },
}),
});
return Effect.gen(function* () {
expect(Exit.isFailure(yield* Effect.exit(run))).toBe(true);
expect(sent).toHaveLength(1);
});
});

it.effect("rejects --wait without sending a request", () => {
const { sent, run } = setup([...argv, "--wait"], { yes: true, route: accepted });
return Effect.gen(function* () {
expect(Exit.isFailure(yield* Effect.exit(run))).toBe(true);
expect(sent).toEqual([]);
});
});
});

describe("consolidated warehouse status", () => {
const attributes = {
project_ref: VALID_REF,
Expand All @@ -475,6 +533,7 @@ describe("generated warehouse commands", () => {
unavailable_reason: null,
observed_at: "2026-11-17T10:00:00Z",
items: [],
progress: null,
},
replication: {
status: "unavailable",
Expand All @@ -487,6 +546,7 @@ describe("generated warehouse commands", () => {
query_explain: false,
replication_add: false,
replication_remove: true,
replication_restart: true,
table_layout_read: true,
table_layout_update: false,
table_resync: false,
Expand Down Expand Up @@ -556,11 +616,75 @@ describe("generated warehouse commands", () => {
});
});

it.effect("shows runtime diagnostics beside last-known table errors and progress", () => {
const response = {
data: {
...body.data,
attributes: {
...attributes,
pipeline: {
id: "pipeline-1",
status: "failed",
diagnostic: {
code: "process_exited",
message: "The pipeline process exited unsuccessfully.",
exit_code: 1,
},
observed_at: attributes.observed_at,
unavailable_reason: null,
},
tables: {
...attributes.tables,
progress: {
observation: "last_known",
selected: 1,
queued: 0,
copying_table: 0,
copied_table: 0,
following_wal: 0,
error: 1,
unknown: 0,
},
items: [
{
id: 16385,
schema: "public",
name: "orders",
replication_state: "error",
state_observation: "last_known",
sync_lag: null,
error: {
reason: "The table layout could not be applied.",
solution: "Inspect the saved layout.",
retry_policy: { policy: "manual_retry" },
},
},
],
},
},
},
};
const { out, run } = setup(["warehouse", "status"], {
route: ok(response),
stdoutIsTty: true,
});
return Effect.gen(function* () {
yield* run;
expect(out.stdoutText).toContain("process_exited");
expect(out.stdoutText).toContain("The table layout could not be applied.");
expect(out.stdoutText).toContain("manual_retry");
expect(out.stdoutText).toMatch(/Observation\s+last_known/);
expect(out.stdoutText).toMatch(/Selected\s+1/);
});
});

it.effect("lists every table of a large warehouse in terminal output", () => {
const items = Array.from({ length: 12 }, (_, index) => ({
id: 20000 + index,
schema: "public",
name: `table_${index}`,
error: null,
state_observation: "current" as const,
replication_state: index === 0 ? ("error" as const) : ("following_wal" as const),
sync_lag:
index === 1
Expand All @@ -586,7 +710,7 @@ describe("generated warehouse commands", () => {
return Effect.gen(function* () {
yield* run;
expect(out.stdoutText).toMatch(
/ID\s+20000\n\s+Schema\s+public\n\s+Name\s+table_0\n\s+Replication state\s+error\n/,
/ID\s+20000\n\s+Schema\s+public\n\s+Name\s+table_0\n\s+Error\s+-\n\s+State observation\s+current\n\s+Replication state\s+error\n/,
);
for (const item of items) expect(out.stdoutText).toContain(String(item.id));
expect(out.stdoutText).not.toContain("omitted");
Expand Down Expand Up @@ -1094,6 +1218,48 @@ describe("generated warehouse commands", () => {
});
});

it.effect("accepts every displayed layout JSON example through the parser", () => {
const examples = entryOf("warehouse tables layout update").examples ?? [];
const expected = [
{
partition_by: [{ column: "event_at", transform: { kind: "day" } }],
sort_by: {
kind: "columns",
columns: [
{ name: "tenant_id", direction: "asc" },
{ name: "event_at", direction: "desc", nulls: "last" },
],
},
},
{ partition_by: [{ column: "tenant_id", transform: { kind: "bucket", count: 8 } }] },
{ partition_by: [], sort_by: { kind: "none" } },
{ partition_by: null, sort_by: null },
];
expect(examples).toHaveLength(expected.length);
return Effect.gen(function* () {
for (const [index, example] of examples.entries()) {
const args =
example.command
.replace(/^supabase /, "")
.replace("<table-id>", "16385")
.match(/'[^']*'|\S+/g)
?.map((token) => token.replace(/^'|'$/g, "")) ?? [];
const preview = args.includes("--dry-run");
const { sent, out, run } = setup(args, { yes: true, route: accepted });
yield* run;
const body = preview
? (yield* Schema.decodeEffect(
Schema.fromJsonString(Schema.Struct({ body: Schema.Unknown })),
)(out.stdoutText)).body
: sent[0]?.body;
expect(body).toEqual({
data: { type: "warehouse_table_layout", attributes: expected[index] },
});
expect(sent).toHaveLength(preview ? 0 : 1);
}
});
});

it.effect("keeps a JSON null from --sort-by as unmanaged sorting", () => {
const { sent, out, run } = setup([...argv, "--sort-by", "null", "--dry-run"], {
route: accepted,
Expand Down Expand Up @@ -1996,6 +2162,16 @@ describe("generated warehouse commands", () => {
});

describe("help", () => {
it.effect("distinguishes Management API capabilities from SQL EXPLAIN in status help", () => {
const { console, calls } = fakeConsole();
const { run } = setup(["warehouse", "status", "--help"], { route: accepted });
return Effect.gen(function* () {
yield* run.pipe(Effect.provideService(Console.Console, console));
expect(calls.join("\n")).toContain("Capabilities describe Management API operations");
expect(calls.join("\n")).toContain("SQL EXPLAIN");
});
});

it.effect("shows a body file in the layout update example", () => {
const { console, calls } = fakeConsole();
const { run } = setup(["warehouse", "tables", "layout", "update", "--help"], {
Expand All @@ -2006,6 +2182,10 @@ describe("generated warehouse commands", () => {
expect(calls.join("\n")).toContain(
"supabase warehouse tables layout update <table-id> --file <path>",
);
expect(calls.join("\n")).toContain(
`--partition-by '[{"column":"event_at","transform":{"kind":"day"}}]'`,
);
expect(calls.join("\n")).toContain(`--sort-by '{"kind":"none"}'`);
});
});

Expand Down Expand Up @@ -2827,3 +3007,18 @@ describeHostedConsent("warehouse replication resync", {
};
},
});

describeHostedConsent("warehouse replication restart", {
command: commandTreeFor({ apiFeatures: ["warehouse"] }).get("warehouse replication restart")!
.command,
invoke: ({ workdir, yes }) => {
const { args, sent, run } = execute(["warehouse", "replication", "restart"], {
yes,
route: accepted,
});
return {
run: run.pipe(Effect.provide(cliServices(workdir, args))),
mutations: () => sent.filter((request) => request.method !== "GET").length,
};
},
});
37 changes: 36 additions & 1 deletion apps/cli/src/commands/api/generated.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,17 @@ Removes one selected source table or all selected tables in a schema as a batch.
| `--schema <schema>` | string | yes, unless `--body` or `--file` has the field | no | body `/data/attributes/schema` |
| `--table <table>` | string | no | no | body `/data/attributes/table` |

## `supabase warehouse replication restart`

Start or restart Warehouse replication

Starts a stopped managed pipeline or restarts a starting, started or failed pipeline, preserving the selected tables and saved layouts. Restart interrupts replication; in-progress initial copies may restart from scratch. If lost-slot recreation is configured, startup can rebuild destination tables. The response confirms acceptance only. Inspect warehouse status for runtime diagnostics and observed table progress; these observations do not identify completion of this request. Inspect state before retrying an uncertain response.

- Access: mutation, consent defaults to No (`--yes` when it cannot prompt).
- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`.
- Consent: prints the API description before the interactive confirmation.
- Request: `POST /v2/projects/{ref}/warehouse/replication/restart` (`v2-restart-warehouse-replication`), success 202 json.

## `supabase warehouse replication resync`

Reset and rebuild one Warehouse table
Expand All @@ -177,7 +188,7 @@ Resets replication for one selected source table using its currently saved layou

Get consolidated Warehouse status and capabilities

Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions.
Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions. Runtime diagnostics classify current failures. Table errors and progress are explicitly current, last-known or unavailable; they do not establish completion of a particular restart or resync. Capabilities describe Management API operations: workload_metrics includes query-stats and capacity; query_explain does not describe SQL EXPLAIN through the Warehouse connection.

- Access: read-only, no consent.
- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`.
Expand Down Expand Up @@ -209,6 +220,30 @@ Returns the sorting and partitioning rules saved for one replicated table, by so

Update the layout of a table replicated to Warehouse

Partition new files by event day and sort within files; preserve historical files.

```sh
supabase warehouse tables layout update <table-id> --partition-by '[{"column":"event_at","transform":{"kind":"day"}}]' --sort-by '{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}'
```

Preview eight hash buckets locally without changing the Warehouse.

```sh
supabase warehouse tables layout update <table-id> --partition-by '[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]' --dry-run
```

Clear partitioning and sorting for future writes.

```sh
supabase warehouse tables layout update <table-id> --partition-by '[]' --sort-by '{"kind":"none"}'
```

Stop managing both settings; omitted flags preserve their saved values.

```sh
supabase warehouse tables layout update <table-id> --partition-by 'null' --sort-by 'null'
```

Updates saved sorting and partitioning rules for one source table object identifier (OID). Provide sort_by or partition_by; empty and reset-only patches are rejected. Omitted settings are preserved. Null makes a setting unmanaged. An empty partition list clears partitioning, and the none sort selector clears sorting. The backend validates the source schema and preserves other tables. When the layout changes, an active pipeline is restarted. A stopped pipeline stays stopped. reset_table defaults to false, preserving historical files and replication progress. When the layout changes, --reset-table resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never restarts the pipeline or resets the table. Acceptance and application_status report orchestration. Run warehouse tables layout get to compare the desired and observed rules. Run warehouse tables get to check table replication status. These reads do not establish completion of this specific update. There is no revision, idempotency, resolved preview, or durable operation contract. A failed update can leave partial effects, including a completed reset. Inspect the saved layout, pipeline, and table state before retrying.

- Access: mutation, consent defaults to No (`--yes` when it cannot prompt).
Expand Down
Loading