From 527533270a93550ec1b540337b57dca19b2bc4e8 Mon Sep 17 00:00:00 2001 From: Colum Ferry Date: Wed, 28 Oct 2026 09:38:54 +0000 Subject: [PATCH 1/2] fix(cli): start the local stack when Docker cannot exec health checks On nested or sandboxed Docker hosts every HEALTHCHECK fails to exec (ExitCode -1, "OCI runtime exec failed"), so container health never reaches healthy and `supabase start` / `db start` time out and roll back. - Gate Postgres readiness on a host-side connect probe for start, db start, db reset and the db diff / migration squash shadows, then wait up to 15s for Docker's first health verdict so `status` keeps working. - When a container's health check cannot exec, fall back to probing its Kong route (or any Kong response for Kong itself), else accept it as running, and print one warning naming the unverified containers. - Accept an exec-failed db in `status` and the already-running gate. - Include the last health-check output in not-ready errors. - Bound gateway probes with one timeout and cap the service wait in wall-clock time. Closes #7325 --- .../db-bootstrap/health-check.ts | 266 +++++-- .../db-bootstrap/health-check.unit.test.ts | 657 +++++++++++++++++- .../db-bootstrap/recreate-local-database.ts | 40 +- .../db-bootstrap/shadow-cache.ts | 4 +- .../db-bootstrap/start-database.ts | 19 +- .../db-bootstrap/start-local-database.ts | 5 + .../src/command-internal/docker-lifecycle.ts | 78 ++- .../docker-lifecycle.unit.test.ts | 291 ++++++++ apps/cli/src/commands/db/diff/SIDE_EFFECTS.md | 2 +- apps/cli/src/commands/db/diff/diff.handler.ts | 4 +- .../commands/db/diff/diff.integration.test.ts | 75 +- .../cli/src/commands/db/reset/SIDE_EFFECTS.md | 10 + .../db/reset/reset.integration.test.ts | 60 +- .../db/shared/pgdelta-next-shadow.layer.ts | 4 +- .../src/commands/db/shared/shadow-source.ts | 4 +- .../cli/src/commands/db/start/SIDE_EFFECTS.md | 21 +- .../db/start/start.integration.test.ts | 98 ++- .../commands/migration/squash/SIDE_EFFECTS.md | 2 +- .../migration/squash/squash.handler.ts | 4 +- .../squash/squash.integration.test.ts | 32 +- apps/cli/src/commands/start/SIDE_EFFECTS.md | 85 ++- apps/cli/src/commands/start/start.handler.ts | 41 +- .../commands/start/start.integration.test.ts | 393 +++++++++-- apps/cli/src/commands/start/start.services.ts | 44 +- .../start/start.services.unit.test.ts | 1 + apps/cli/src/commands/status/SIDE_EFFECTS.md | 7 +- .../cli/src/commands/status/status.handler.ts | 13 +- .../status/status.integration.test.ts | 38 + apps/cli/tests/helpers/command-mocks.ts | 27 +- apps/cli/tests/helpers/docker-health.ts | 48 ++ 30 files changed, 2121 insertions(+), 252 deletions(-) create mode 100644 apps/cli/tests/helpers/docker-health.ts diff --git a/apps/cli/src/command-internal/db-bootstrap/health-check.ts b/apps/cli/src/command-internal/db-bootstrap/health-check.ts index fdd1e16c51..f03b365d5d 100644 --- a/apps/cli/src/command-internal/db-bootstrap/health-check.ts +++ b/apps/cli/src/command-internal/db-bootstrap/health-check.ts @@ -17,8 +17,13 @@ import { } from "../../shared/telemetry/error-actionability.ts"; import { ChildTracePropagation } from "../../shared/telemetry/spans.ts"; import { spawnContainerCliWithRuntime, type ContainerRuntime } from "../container-cli.ts"; +import { yellow } from "../colors.ts"; import { DbConnection, type PgConnInput } from "../db-connection.service.ts"; -import { inspectContainerState } from "../docker-lifecycle.ts"; +import { + formatNotReadyReason, + healthCheckCannotExec, + inspectContainerState, +} from "../docker-lifecycle.ts"; import { kongAuthHeaders } from "../kong-auth.ts"; type Spawner = ChildProcessSpawner["Service"]; @@ -79,18 +84,31 @@ export class HealthCheckTimeoutError extends Data.TaggedError("HealthCheckTimeou } /** - * PostgREST's local Kong gateway coordinates. TLS/CA trust for a local https gateway is the - * caller's responsibility when composing the `HttpClient.HttpClient` layer this module requires - * — when `api.tls.enabled`, the caller resolves the local Kong CA and overrides the HTTP client - * around the health-check call, so `checkHttpReady` trusts it instead of exhausting the full - * retry budget on a TLS verification failure. + * The local Kong gateway coordinates. TLS/CA trust for a local https gateway is the caller's + * responsibility when composing the `HttpClient.HttpClient` layer this module requires — when + * `api.tls.enabled`, the caller resolves the local Kong CA and overrides the HTTP client around + * the health-check call, so `checkHttpReady` trusts it instead of exhausting the full retry + * budget on a TLS verification failure. */ -export interface HealthCheckPostgrestGateway { - readonly containerId: string; +interface HealthCheckGateway { readonly apiExternalUrl: string; readonly secretKey: string; } +/** A {@link HealthCheckGateway} that probes one specific container instead of its Docker health. */ +export interface HealthCheckPostgrestGateway extends HealthCheckGateway { + readonly containerId: string; +} + +/** + * How to judge a container whose Docker health check cannot run: accept it as `running`, probe + * its route through the gateway, or (for the gateway itself) accept any HTTP response from it. + */ +export type ExecFallbackProbe = + | { readonly kind: "running" } + | { readonly kind: "gateway"; readonly gateway: HealthCheckGateway; readonly path: string } + | { readonly kind: "gateway-reachable"; readonly gateway: HealthCheckGateway }; + export interface WaitForHealthyServicesOptions { readonly timeoutSeconds?: number; readonly postgrest?: HealthCheckPostgrestGateway; @@ -98,6 +116,15 @@ export interface WaitForHealthyServicesOptions { readonly edgeRuntime?: HealthCheckPostgrestGateway; /** Each watched container's already-resolved image, keyed by container name. */ readonly images?: ReadonlyMap; + /** Per-container fallback used only when Docker cannot run that container's health check. */ + readonly execFallbacks?: ReadonlyMap; +} + +export interface WaitForHealthyServicesResult { + /** Containers whose Docker health check could not run, at any point during the wait. */ + readonly execUnavailable: ReadonlyArray; + /** The subset accepted on `running` alone, with no readiness verification. */ + readonly readinessAssumed: ReadonlyArray; } /** The container runtime's message when an image cannot be executed by the host kernel. */ @@ -156,42 +183,99 @@ function execFormatRecoveryHint( ].join("\n"); } +interface ExecFallbackSeen { + readonly execUnavailable: Set; + readonly assumed: Set; +} + /** Not-running/not-ready gating, via the same {@link inspectContainerState} primitive `status.handler.ts` uses. */ -function checkContainerReady(spawner: Spawner, containerId: string): Effect.Effect { +function checkContainerReady( + spawner: Spawner, + containerId: string, + fallback: ExecFallbackProbe | undefined, + seen: ExecFallbackSeen, +): Effect.Effect { return inspectContainerState(spawner, containerId).pipe( Effect.mapError((cause) => cause.message), - Effect.flatMap((state) => { + Effect.flatMap((state): Effect.Effect => { if (!state.running) { return Effect.fail(`container is not running: ${state.status}`); } - if (state.health !== undefined && state.health !== "healthy") { - return Effect.fail(`container is not ready: ${state.health}`); + if (state.health === undefined || state.health === "healthy") { + return Effect.void; } - return Effect.void; + if (healthCheckCannotExec(state)) { + seen.execUnavailable.add(containerId); + if (fallback?.kind === "running") { + seen.assumed.add(containerId); + return Effect.void; + } + if (fallback?.kind === "gateway") { + return checkHttpReady(fallback.gateway, fallback.path, "GET").pipe( + Effect.mapError((reason) => `container is not ready: ${fallback.path}: ${reason}`), + ); + } + if (fallback?.kind === "gateway-reachable") { + return checkHttpReady(fallback.gateway, "/", "GET", true).pipe( + Effect.mapError((reason) => `container is not ready: ${reason}`), + ); + } + } + return Effect.fail(formatNotReadyReason(state)); }), ); } -/** An HTTP HEAD through the local Kong gateway, expecting exactly 200. */ +/** An HTTP request through the local Kong gateway, expecting exactly 200 unless `anyStatus`. */ function checkHttpReady( - gateway: HealthCheckPostgrestGateway, + gateway: HealthCheckGateway, path: string, + method: "HEAD" | "GET" = "HEAD", + anyStatus = false, ): Effect.Effect { return Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; - const request = HttpClientRequest.head(`${gateway.apiExternalUrl}${path}`).pipe( - HttpClientRequest.setHeaders(kongAuthHeaders(gateway.secretKey)), - ); - const response = yield* httpClient.execute(request).pipe( + const url = `${gateway.apiExternalUrl}${path}`; + const request = ( + method === "GET" ? HttpClientRequest.get(url) : HttpClientRequest.head(url) + ).pipe(HttpClientRequest.setHeaders(kongAuthHeaders(gateway.secretKey))); + const status = yield* Effect.gen(function* () { + const response = yield* httpClient.execute(request); + if (method === "GET") { + yield* response.text.pipe(Effect.ignore); + } + return response.status; + }).pipe( Effect.timeout(`${HTTP_PROBE_TIMEOUT_SECONDS} seconds`), Effect.mapError((cause) => String(cause)), ); - if (response.status !== 200) { - return yield* Effect.fail(`unexpected status ${response.status}`); + if (!anyStatus && status !== 200) { + return yield* Effect.fail(`unexpected status ${status}`); } }); } +function execUnavailableHint(containerIds: ReadonlyArray): string | undefined { + const [first] = containerIds; + if (first === undefined) return undefined; + return [ + `Docker could not run the health check inside ${containerIds.join(", ")} ("OCI runtime exec failed"), so it cannot report them healthy.`, + "This happens when Docker runs nested or sandboxed.", + `Check with: docker exec ${first} true`, + ].join("\n"); +} + +/** The stderr warning for a start that proceeded although Docker cannot run health checks here. */ +export function healthCheckExecUnavailableWarning(unverified: ReadonlyArray): string { + return ( + `${yellow("WARNING:")} Docker cannot run health checks inside containers on this host (OCI runtime exec failed). ` + + (unverified.length > 0 + ? `Readiness of ${unverified.join(", ")} was not verified.` + : "Readiness was checked from the host instead.") + + "\n" + ); +} + /** * `docker logs `, teed to this process's stderr. Best-effort: a failure to stream logs must * never mask the timeout error it was printed alongside, so every failure here is swallowed. @@ -263,33 +347,39 @@ function dumpContainerLogs( } /** - * Waits for every container in `containerIds` to become ready. Resolves once all are ready; - * fails with {@link HealthCheckTimeoutError} (carrying every still-unhealthy container's - * last-seen reason) once the retry budget is exhausted. The caller decides whether - * `--ignore-health-check` turns that failure into a warning instead of a hard exit. + * Waits for every container in `containerIds` to become ready. Resolves once all are ready, + * reporting which containers Docker could not health-check; fails with + * {@link HealthCheckTimeoutError} (carrying every still-unhealthy container's last-seen reason) + * once the retry budget is exhausted. The caller decides whether `--ignore-health-check` turns + * that failure into a warning instead of a hard exit. */ export function waitForHealthyServices( spawner: Spawner, containerIds: ReadonlyArray, opts: WaitForHealthyServicesOptions = {}, -): Effect.Effect { +): Effect.Effect { const postgrest = opts.postgrest; const edgeRuntime = opts.edgeRuntime; - const checkOne = (containerId: string): Effect.Effect => { + const checkOne = ( + containerId: string, + seen: ExecFallbackSeen, + ): Effect.Effect => { if (postgrest !== undefined && containerId === postgrest.containerId) { return checkHttpReady(postgrest, POSTGREST_READY_PATH); } if (edgeRuntime !== undefined && containerId === edgeRuntime.containerId) { return checkHttpReady(edgeRuntime, EDGE_RUNTIME_READY_PATH); } - return checkContainerReady(spawner, containerId); + return checkContainerReady(spawner, containerId, opts.execFallbacks?.get(containerId), seen); }; return Effect.gen(function* () { const timeoutSeconds = opts.timeoutSeconds ?? (yield* HealthCheckTimeoutSeconds); let stillWatching = containerIds; + let lastFailures: ReadonlyArray | undefined; let attempts = 0; + const seen: ExecFallbackSeen = { execUnavailable: new Set(), assumed: new Set() }; // Each round narrows `stillWatching` to just the containers that failed, so a container // that becomes healthy mid-run stops being probed on later rounds. @@ -299,7 +389,7 @@ export function waitForHealthyServices( const outcomes = yield* Effect.forEach( stillWatching, (containerId) => - checkOne(containerId).pipe( + checkOne(containerId, seen).pipe( Effect.match({ onFailure: (reason): HealthCheckFailure | undefined => ({ containerId, @@ -315,6 +405,7 @@ export function waitForHealthyServices( ); stillWatching = failures.map((failure) => failure.containerId); if (failures.length > 0) { + lastFailures = failures; return yield* new HealthCheckProbeError({ failures }); } }, @@ -323,8 +414,28 @@ export function waitForHealthyServices( // A 1-second constant delay, capped at `timeoutSeconds` retries after the initial attempt. const schedule = Schedule.max([Schedule.spaced("1 seconds"), Schedule.recurs(timeoutSeconds)]); + const boundSeconds = (timeoutSeconds + 1) * (1 + HTTP_PROBE_TIMEOUT_SECONDS); + yield* probe.pipe( Effect.retry(schedule), + Effect.timeoutOrElse({ + duration: Duration.seconds(boundSeconds), + orElse: () => + Effect.annotateCurrentSpan("health.probe_bound_reached", true).pipe( + Effect.andThen( + Effect.fail( + new HealthCheckProbeError({ + failures: + lastFailures ?? + stillWatching.map((containerId) => ({ + containerId, + reason: `container is not ready: readiness probe hung after ${boundSeconds}s`, + })), + }), + ), + ), + ), + }), Effect.catch((probeError) => Effect.gen(function* () { // An interrupted fiber never reaches this `Effect.catch` handler, so no separate @@ -337,17 +448,24 @@ export function waitForHealthyServices( const execFormatErrors = scans .filter((scan) => scan.found) .map((scan) => scan.containerId); - const suggestion = execFormatRecoveryHint( - execFormatErrors, - opts.images, - scans.find((scan) => scan.runtime !== undefined)?.runtime ?? "docker", - ); + const hints = [ + execFormatRecoveryHint( + execFormatErrors, + opts.images, + scans.find((scan) => scan.runtime !== undefined)?.runtime ?? "docker", + ), + execUnavailableHint( + probeError.failures + .map((failure) => failure.containerId) + .filter((containerId) => seen.execUnavailable.has(containerId)), + ), + ].filter((hint) => hint !== undefined); return yield* new HealthCheckTimeoutError({ message: probeError.failures .map((failure) => `${failure.containerId} ${failure.reason}`) .join("\n"), unhealthy: probeError.failures, - ...(suggestion === undefined ? {} : { suggestion }), + ...(hints.length === 0 ? {} : { suggestion: hints.join("\n\n") }), }); }), ), @@ -356,10 +474,16 @@ export function waitForHealthyServices( Effect.annotateCurrentSpan({ "retry.attempt_count": attempts, "health.unhealthy_count": stillWatching.length, + "health.exec_unavailable_count": seen.execUnavailable.size, + "health.readiness_assumed_count": seen.assumed.size, }), ), ), ); + return { + execUnavailable: [...seen.execUnavailable], + readinessAssumed: [...seen.assumed], + }; }).pipe( Effect.withSpan("HealthCheck.waitHealthyServices", { attributes: { "health.container_count": containerIds.length }, @@ -368,18 +492,18 @@ export function waitForHealthyServices( } /** Caps a hung dial so one probe cannot swallow the whole poll budget. */ -const SHADOW_READY_CONNECT_TIMEOUT_SECONDS = 2; +const POSTGRES_READY_CONNECT_TIMEOUT_SECONDS = 2; /** * One round's verdict. `fatal` makes an exited container fail fast instead of burning the * remaining budget: nothing about a dead container can change on a later round. */ -interface ShadowReadyFailure { +interface PostgresReadyFailure { readonly reason: string; readonly fatal: boolean; } -const shadowNotReady = (reason: string): ShadowReadyFailure => ({ +const postgresNotReady = (reason: string): PostgresReadyFailure => ({ reason, fatal: false, }); @@ -390,36 +514,36 @@ const shadowNotReady = (reason: string): ShadowReadyFailure => ({ * the real connection too. `Effect.scoped` closes the session the moment the probe resolves; the * caller opens its own connection afterwards. */ -const probeShadowConnect = ( +const probePostgresConnect = ( connConfig: PgConnInput, -): Effect.Effect => +): Effect.Effect => Effect.scoped( Effect.gen(function* () { const dbConnection = yield* DbConnection; yield* dbConnection.connect( - { ...connConfig, connectTimeoutSeconds: SHADOW_READY_CONNECT_TIMEOUT_SECONDS }, + { ...connConfig, connectTimeoutSeconds: POSTGRES_READY_CONNECT_TIMEOUT_SECONDS }, { isLocal: true, dnsResolver: "native" }, ); }), - ).pipe(Effect.mapError((cause) => shadowNotReady(cause.message))); + ).pipe(Effect.mapError((cause) => postgresNotReady(`container is not ready: ${cause.message}`))); -export interface WaitForShadowReadyOptions { +export interface WaitForPostgresReadyOptions { readonly timeoutSeconds?: number; - /** The shadow container's already-resolved postgres image, named in the exec-format recovery hint. */ + /** The container's already-resolved postgres image, named in the exec-format recovery hint. */ readonly image?: string; } /** - * Shadow readiness: inspect + connect probe, polled every 500ms. Docker's - * healthcheck is `interval=10s` with no start period, so Postgres is connectable - * ~6.5s before `Health.Status` flips. Same error shape as the health gate, - * plus a wall-clock cap so a hung 2s dial cannot overrun the retry budget. + * Postgres readiness: inspect + connect probe, polled every 500ms. Docker's health status needs + * `docker exec`, which some hosts cannot do, and it lags connectability by up to one 10s + * interval. Same error shape as the health gate, plus a wall-clock cap so a hung 2s dial cannot + * overrun the retry budget. */ -export function waitForShadowReady( +export function waitForPostgresReady( spawner: Spawner, containerId: string, connConfig: PgConnInput, - opts: WaitForShadowReadyOptions = {}, + opts: WaitForPostgresReadyOptions = {}, ): Effect.Effect { return Effect.gen(function* () { const timeoutSeconds = opts.timeoutSeconds ?? (yield* HealthCheckTimeoutSeconds); @@ -430,17 +554,17 @@ export function waitForShadowReady( Schedule.spaced("500 millis"), Schedule.recurs(timeoutSeconds * 2), ]); - const boundSeconds = timeoutSeconds + SHADOW_READY_CONNECT_TIMEOUT_SECONDS; + const boundSeconds = timeoutSeconds + POSTGRES_READY_CONNECT_TIMEOUT_SECONDS; // Per-evaluation state: the retry rounds within one evaluation share the latest failure for // the timeout diagnostic, while re-evaluating the returned Effect starts from a fresh slot. - let lastFailure: ShadowReadyFailure | undefined; + let lastFailure: PostgresReadyFailure | undefined; let attempts = 0; - const probe: Effect.Effect = Effect.gen(function* () { + const probe: Effect.Effect = Effect.gen(function* () { attempts += 1; const state = yield* inspectContainerState(spawner, containerId).pipe( - Effect.mapError((cause) => shadowNotReady(cause.message)), + Effect.mapError((cause) => postgresNotReady(cause.message)), ); if (!state.running) { return yield* Effect.fail({ @@ -448,7 +572,7 @@ export function waitForShadowReady( fatal: true, }); } - yield* probeShadowConnect(connConfig); + yield* probePostgresConnect(connConfig); }).pipe( Effect.withTracerEnabled(false), Effect.provideService(ChildTracePropagation, false), @@ -466,7 +590,9 @@ export function waitForShadowReady( orElse: () => Effect.fail( lastFailure ?? - shadowNotReady(`not ready after ${boundSeconds}s: connection attempt hung`), + postgresNotReady( + `container is not ready: connection attempt hung after ${boundSeconds}s`, + ), ), }), Effect.catch((failure) => @@ -491,5 +617,31 @@ export function waitForShadowReady( Effect.suspend(() => Effect.annotateCurrentSpan("retry.attempt_count", attempts)), ), ); - }).pipe(Effect.withSpan("HealthCheck.waitShadowReady")); + }).pipe(Effect.withSpan("HealthCheck.waitPostgresReady")); +} + +/** + * Waits up to `maxSeconds` for Docker's first health verdict on a container, so a caller that + * reads `Health.Status` right after a host-side readiness probe does not see `starting`. + * Best-effort: a timeout or an inspect failure ends the wait without failing. + */ +export function awaitDockerHealthSettled( + spawner: Spawner, + containerId: string, + maxSeconds = 15, +): Effect.Effect { + const stillStarting = inspectContainerState(spawner, containerId).pipe( + Effect.map( + (state) => state.running && state.health === "starting" && !healthCheckCannotExec(state), + ), + Effect.orElseSucceed(() => false), + Effect.withTracerEnabled(false), + Effect.provideService(ChildTracePropagation, false), + ); + return stillStarting.pipe( + Effect.repeat({ schedule: Schedule.spaced("1 seconds"), while: (starting) => starting }), + Effect.timeout(Duration.seconds(maxSeconds)), + Effect.ignore, + Effect.withSpan("HealthCheck.awaitDockerHealthSettled"), + ); } diff --git a/apps/cli/src/command-internal/db-bootstrap/health-check.unit.test.ts b/apps/cli/src/command-internal/db-bootstrap/health-check.unit.test.ts index 7a8a369dde..81aba24804 100644 --- a/apps/cli/src/command-internal/db-bootstrap/health-check.unit.test.ts +++ b/apps/cli/src/command-internal/db-bootstrap/health-check.unit.test.ts @@ -3,16 +3,27 @@ import { Deferred, Effect, Exit, Fiber, Layer, Sink, Stream, Tracer } from "effe import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/process"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as TestClock from "effect/testing/TestClock"; +import { + EXEC_FAILED_STATE, + EXEC_FAILURE_OUTPUT, + PROBE_TIMEOUT_OUTPUT, + inspectedState, +} from "../../../tests/helpers/docker-health.ts"; import { DbConnectError } from "../db-connection.errors.ts"; import { DbConnection, type DbSession, type PgConnInput } from "../db-connection.service.ts"; import { HealthCheckTimeoutError, + awaitDockerHealthSettled, + healthCheckExecUnavailableWarning, waitForHealthyServices, - waitForShadowReady, + waitForPostgresReady, + type ExecFallbackProbe, type HealthCheckPostgrestGateway, + type WaitForHealthyServicesOptions, } from "./health-check.ts"; /** Ends a scripted `logs` script, failing the stream after already-emitted chunks — the real "daemon dropped the pipe mid-dump" case. */ @@ -37,6 +48,8 @@ function mockHealthSpawner( opts: { readonly runtime?: "docker" | "podman"; readonly beforeInspect?: (containerId: string) => Effect.Effect; + /** Makes every `docker container inspect` exit non-zero, as when the daemon is unreachable. */ + readonly inspectFails?: boolean; } = {}, ) { const counts = new Map(); @@ -82,6 +95,7 @@ function mockHealthSpawner( let stdoutChunks: LogChunks = []; let stderrChunks: LogChunks = []; + let exitCode = 0; if (args[0] === "container" && args[1] === "inspect") { const containerId = args[2] ?? ""; if (opts.beforeInspect !== undefined) { @@ -89,7 +103,12 @@ function mockHealthSpawner( } const callIndex = counts.get(containerId) ?? 0; counts.set(containerId, callIndex + 1); - stdoutChunks = [inspectResponse(containerId, callIndex)]; + if (opts.inspectFails === true) { + exitCode = 1; + stderrChunks = ["Cannot connect to the Docker daemon\n"]; + } else { + stdoutChunks = [inspectResponse(containerId, callIndex)]; + } } else if (args[0] === "logs") { const script = logs[args[1] ?? ""]; if (script !== undefined) { @@ -103,7 +122,7 @@ function mockHealthSpawner( } const exitDeferred = yield* Deferred.make(); - yield* Deferred.succeed(exitDeferred, ChildProcessSpawner.ExitCode(0)); + yield* Deferred.succeed(exitDeferred, ChildProcessSpawner.ExitCode(exitCode)); return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), stdout: toStream(stdoutChunks), @@ -332,6 +351,73 @@ describe("waitForHealthyServices", () => { }), ); + it.effect( + "fails with a hung-probe reason once the wall-clock bound passes when the first round never completes", + () => + withSilencedStderr( + Effect.gen(function* () { + const mock = mockHealthSpawner( + () => runningHealthy, + {}, + { beforeInspect: () => Effect.never }, + ); + + const fiber = yield* waitForHealthyServices(mock.spawner, ["supabase_kong_proj"], { + timeoutSeconds: 1, + }).pipe( + Effect.provide(unusedHttpClientLayer), + Effect.forkChild({ startImmediately: true }), + ); + for (let second = 0; second < 21; second++) { + yield* TestClock.adjust("1 seconds"); + } + const pendingAt21Seconds = fiber.pollUnsafe(); + yield* TestClock.adjust("1 seconds"); + const error = yield* Fiber.join(fiber).pipe(Effect.flip); + + const reason = "container is not ready: readiness probe hung after 22s"; + expect(pendingAt21Seconds).toBeUndefined(); + expect(error).toBeInstanceOf(HealthCheckTimeoutError); + expect(error.unhealthy).toEqual([{ containerId: "supabase_kong_proj", reason }]); + expect(error.message).toBe(`supabase_kong_proj ${reason}`); + }), + ), + ); + + it.effect( + "reports the last completed round's reason when a later round hangs past the wall-clock bound", + () => + withSilencedStderr( + Effect.gen(function* () { + let inspects = 0; + const mock = mockHealthSpawner( + () => runningStarting, + {}, + { beforeInspect: () => (++inspects > 1 ? Effect.never : Effect.void) }, + ); + + const fiber = yield* waitForHealthyServices(mock.spawner, ["supabase_kong_proj"], { + timeoutSeconds: 1, + }).pipe( + Effect.provide(unusedHttpClientLayer), + Effect.forkChild({ startImmediately: true }), + ); + for (let second = 0; second < 21; second++) { + yield* TestClock.adjust("1 seconds"); + } + const pendingAt21Seconds = fiber.pollUnsafe(); + yield* TestClock.adjust("1 seconds"); + const error = yield* Fiber.join(fiber).pipe(Effect.flip); + + expect(pendingAt21Seconds).toBeUndefined(); + expect(error).toBeInstanceOf(HealthCheckTimeoutError); + expect(error.unhealthy).toEqual([ + { containerId: "supabase_kong_proj", reason: "container is not ready: starting" }, + ]); + }), + ), + ); + describe("exec format error recovery advice", () => { /** * The dumped logs are teed to the real `process.stderr`; swallow them so @@ -880,7 +966,7 @@ function withSilencedStderr(effect: Effect.Effect): Effect.Eff const inspectCalls = (mock: ReturnType) => mock.spawned.filter((args) => args[0] === "container" && args[1] === "inspect"); -describe("waitForShadowReady", () => { +describe("waitForPostgresReady", () => { it.effect( "resolves on the first successful connect, while Docker still reports the healthcheck as starting", () => @@ -891,7 +977,7 @@ describe("waitForShadowReady", () => { const mock = mockHealthSpawner(() => runningStarting); const db = mockShadowDbConnection(); - const exit = yield* waitForShadowReady( + const exit = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -913,9 +999,14 @@ describe("waitForShadowReady", () => { const mock = mockHealthSpawner(() => runningStarting); const db = mockShadowDbConnection({ failTimes: 2 }); - const fiber = yield* waitForShadowReady(mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, { - timeoutSeconds: 30, - }).pipe(Effect.provide(db.layer), Effect.forkChild({ startImmediately: true })); + const fiber = yield* waitForPostgresReady( + mock.spawner, + SHADOW_CONTAINER_ID, + shadowConnConfig, + { + timeoutSeconds: 30, + }, + ).pipe(Effect.provide(db.layer), Effect.forkChild({ startImmediately: true })); yield* TestClock.adjust("1 seconds"); yield* TestClock.adjust("1 seconds"); @@ -938,7 +1029,7 @@ describe("waitForShadowReady", () => { const error = yield* withSilencedStderr( Effect.gen(function* () { - const fiber = yield* waitForShadowReady( + const fiber = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -953,9 +1044,14 @@ describe("waitForShadowReady", () => { expect(error).toBeInstanceOf(HealthCheckTimeoutError); expect(error.unhealthy).toEqual([ - { containerId: SHADOW_CONTAINER_ID, reason: "connection refused" }, + { + containerId: SHADOW_CONTAINER_ID, + reason: "container is not ready: connection refused", + }, ]); - expect(error.message).toBe(`${SHADOW_CONTAINER_ID} connection refused`); + expect(error.message).toBe( + `${SHADOW_CONTAINER_ID} container is not ready: connection refused`, + ); // 1 initial attempt plus `timeoutSeconds * 2` retries at 500ms intervals. expect(db.attempts).toHaveLength(5); expect( @@ -975,7 +1071,7 @@ describe("waitForShadowReady", () => { const error = yield* withSilencedStderr( Effect.gen(function* () { - const fiber = yield* waitForShadowReady( + const fiber = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -995,9 +1091,11 @@ describe("waitForShadowReady", () => { // Same failure the exhausted path produces: the last completed attempt's own reason, // the same ` ` message, and the same log dump. expect(error).toBeInstanceOf(HealthCheckTimeoutError); - expect(error.message).toBe(`${SHADOW_CONTAINER_ID} connection refused`); + expect(error.message).toBe( + `${SHADOW_CONTAINER_ID} container is not ready: connection refused`, + ); expect(error.unhealthy).toEqual([ - { containerId: SHADOW_CONTAINER_ID, reason: "connection refused" }, + { containerId: SHADOW_CONTAINER_ID, reason: "container is not ready: connection refused" }, ]); expect( mock.spawned.some((args) => args[0] === "logs" && args[1] === SHADOW_CONTAINER_ID), @@ -1015,7 +1113,7 @@ describe("waitForShadowReady", () => { const error = yield* withSilencedStderr( Effect.gen(function* () { - const fiber = yield* waitForShadowReady( + const fiber = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -1040,6 +1138,36 @@ describe("waitForShadowReady", () => { }), ); + it.effect("reports a first dial that never returns as not ready, naming the wall-clock cap", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => runningStarting); + const db = mockShadowDbConnection({ + failTimes: Number.POSITIVE_INFINITY, + connectMillis: 60_000, + }); + + const error = yield* withSilencedStderr( + Effect.gen(function* () { + const fiber = yield* waitForPostgresReady( + mock.spawner, + SHADOW_CONTAINER_ID, + shadowConnConfig, + { timeoutSeconds: 1 }, + ).pipe(Effect.provide(db.layer), Effect.forkChild({ startImmediately: true })); + + yield* TestClock.adjust("3 seconds"); + return yield* Fiber.join(fiber).pipe(Effect.flip); + }), + ); + + const reason = "container is not ready: connection attempt hung after 3s"; + expect(error).toBeInstanceOf(HealthCheckTimeoutError); + expect(error.message).toBe(`${SHADOW_CONTAINER_ID} ${reason}`); + expect(error.unhealthy).toEqual([{ containerId: SHADOW_CONTAINER_ID, reason }]); + expect(db.attempts).toHaveLength(1); + }), + ); + describe("exec format error recovery advice", () => { it.effect("names the shadow's image when its dumped logs show exec format error", () => Effect.gen(function* () { @@ -1050,7 +1178,7 @@ describe("waitForShadowReady", () => { const error = yield* withSilencedStderr( Effect.gen(function* () { - const fiber = yield* waitForShadowReady( + const fiber = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -1081,7 +1209,7 @@ describe("waitForShadowReady", () => { const error = yield* withSilencedStderr( Effect.gen(function* () { - const fiber = yield* waitForShadowReady( + const fiber = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -1105,7 +1233,7 @@ describe("waitForShadowReady", () => { const error = yield* withSilencedStderr( Effect.gen(function* () { - const fiber = yield* waitForShadowReady( + const fiber = yield* waitForPostgresReady( mock.spawner, SHADOW_CONTAINER_ID, shadowConnConfig, @@ -1123,3 +1251,496 @@ describe("waitForShadowReady", () => { ); }); }); + +describe("waitForHealthyServices where Docker cannot exec health checks", () => { + const STUDIO = "supabase_studio_proj"; + const STORAGE = "supabase_storage_proj"; + const GATEWAY_URL = "http://127.0.0.1:54321"; + const STORAGE_STATUS_PATH = "/storage/v1/status"; + + const orderlyUnhealthy = inspectedState({ + health: "unhealthy", + probes: [{ exitCode: 1, output: "pg_isready: no response" }], + }); + const probeTimedOut = inspectedState({ + health: "unhealthy", + probes: [{ exitCode: -1, output: PROBE_TIMEOUT_OUTPUT }], + }); + + const runningFallback = (...containerIds: ReadonlyArray) => + new Map(containerIds.map((id) => [id, { kind: "running" }])); + const gatewayFallback = (containerId: string, path: string) => + new Map([ + [ + containerId, + { + kind: "gateway", + gateway: { apiExternalUrl: GATEWAY_URL, secretKey: "sb_secret_local" }, + path, + }, + ], + ]); + + const KONG = "supabase_kong_proj"; + const reachableFallback = (containerId: string) => + new Map([ + [ + containerId, + { + kind: "gateway-reachable", + gateway: { apiExternalUrl: GATEWAY_URL, secretKey: "sb_secret_local" }, + }, + ], + ]); + + function recordingGateway(statusByPath: Readonly> = {}) { + const requests: Array<{ + readonly method: string; + readonly url: string; + readonly headers: Readonly>; + }> = []; + const layer = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push({ + method: request.method, + url: request.url, + headers: { ...request.headers }, + }); + const status = statusByPath[new URL(request.url).pathname] ?? 200; + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response("{}", { status }))); + }), + ); + return { layer, requests }; + } + + const settled = ( + mock: ReturnType, + containerIds: ReadonlyArray, + opts: WaitForHealthyServicesOptions = {}, + http: Layer.Layer = unusedHttpClientLayer, + ) => + waitForHealthyServices(mock.spawner, containerIds, { timeoutSeconds: 1, ...opts }).pipe( + Effect.provide(http), + ); + + const timeoutFailure = ( + mock: ReturnType, + containerIds: ReadonlyArray, + opts: WaitForHealthyServicesOptions = {}, + http: Layer.Layer = unusedHttpClientLayer, + ) => + withSilencedStderr( + Effect.gen(function* () { + const fiber = yield* settled(mock, containerIds, opts, http).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust("1 seconds"); + return yield* Fiber.join(fiber).pipe(Effect.flip); + }), + ); + + it.effect("names the probe's OCI error and the exec check when no fallback is configured", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + + const error = yield* timeoutFailure(mock, [STUDIO]); + + const reason = `container is not ready: unhealthy (last health check exit code -1: ${EXEC_FAILURE_OUTPUT})`; + expect(error).toBeInstanceOf(HealthCheckTimeoutError); + expect(error.unhealthy).toEqual([{ containerId: STUDIO, reason }]); + expect(error.message).toBe(`${STUDIO} ${reason}`); + expect(error.suggestion).toBe( + [ + `Docker could not run the health check inside ${STUDIO} ("OCI runtime exec failed"), so it cannot report them healthy.`, + "This happens when Docker runs nested or sandboxed.", + `Check with: docker exec ${STUDIO} true`, + ].join("\n"), + ); + }), + ); + + it.effect("names an ordinary failing probe without the exec-unavailable suggestion", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => orderlyUnhealthy); + + const error = yield* timeoutFailure(mock, [STUDIO]); + + expect(error.message).toBe( + `${STUDIO} container is not ready: unhealthy (last health check exit code 1: pg_isready: no response)`, + ); + expect(error.suggestion).toBeUndefined(); + }), + ); + + it.effect("still fails a probe timeout (exit -1) when a running fallback is configured", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => probeTimedOut); + + const error = yield* timeoutFailure(mock, [STUDIO], { + execFallbacks: runningFallback(STUDIO), + }); + + expect(error.message).toBe( + `${STUDIO} container is not ready: unhealthy (last health check exit code -1: Health check exceeded timeout (2s))`, + ); + expect(error.suggestion).toBeUndefined(); + }), + ); + + it.effect("still fails a restarting container whose last probe was an exec failure", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => + inspectedState({ + status: "restarting", + health: "unhealthy", + probes: [{ exitCode: -1, output: EXEC_FAILURE_OUTPUT }], + }), + ); + + const error = yield* timeoutFailure(mock, [STUDIO], { + execFallbacks: runningFallback(STUDIO), + }); + + expect(error.message).toContain(`${STUDIO} container is not ready: unhealthy (last health`); + expect(error.suggestion).toBeUndefined(); + }), + ); + + it.effect( + "accepts an exec-failed container on a running fallback and reports it as assumed", + () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + + const result = yield* settled(mock, [STUDIO], { execFallbacks: runningFallback(STUDIO) }); + + expect(result).toEqual({ execUnavailable: [STUDIO], readinessAssumed: [STUDIO] }); + }), + ); + + it.effect("verifies an exec-failed container through the gateway with an authenticated GET", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + const gateway = recordingGateway(); + + const result = yield* settled( + mock, + [STORAGE], + { execFallbacks: gatewayFallback(STORAGE, STORAGE_STATUS_PATH) }, + gateway.layer, + ); + + expect(result).toEqual({ execUnavailable: [STORAGE], readinessAssumed: [] }); + expect(gateway.requests).toEqual([ + { + method: "GET", + url: `${GATEWAY_URL}${STORAGE_STATUS_PATH}`, + headers: expect.objectContaining({ apikey: "sb_secret_local" }), + }, + ]); + }), + ); + + for (const status of [503, 404]) { + it.effect(`fails with the gateway's ${status} and the exec suggestion when it is not 200`, () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + const gateway = recordingGateway({ [STORAGE_STATUS_PATH]: status }); + + const error = yield* timeoutFailure( + mock, + [STORAGE], + { execFallbacks: gatewayFallback(STORAGE, STORAGE_STATUS_PATH) }, + gateway.layer, + ); + + expect(error.unhealthy).toEqual([ + { + containerId: STORAGE, + reason: `container is not ready: ${STORAGE_STATUS_PATH}: unexpected status ${status}`, + }, + ]); + expect(error.suggestion).toContain(`Check with: docker exec ${STORAGE} true`); + }), + ); + } + + it.effect("accepts the gateway's 404 as proof that an exec-failed Kong is up", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + const gateway = recordingGateway({ "/": 404 }); + + const result = yield* settled( + mock, + [KONG], + { execFallbacks: reachableFallback(KONG) }, + gateway.layer, + ); + + expect(result).toEqual({ execUnavailable: [KONG], readinessAssumed: [] }); + expect(gateway.requests).toEqual([ + { + method: "GET", + url: `${GATEWAY_URL}/`, + headers: expect.objectContaining({ apikey: "sb_secret_local" }), + }, + ]); + }), + ); + + it.effect("fails an exec-failed Kong whose gateway does not answer", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + const unreachable = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + cause: new Error("connect ECONNREFUSED"), + }), + }), + ), + ), + ); + + const error = yield* timeoutFailure( + mock, + [KONG], + { execFallbacks: reachableFallback(KONG) }, + unreachable, + ); + + expect(error.unhealthy).toEqual([ + { + containerId: KONG, + reason: `container is not ready: HttpClientError: Transport error (GET ${GATEWAY_URL}/)`, + }, + ]); + expect(error.suggestion).toContain(`Check with: docker exec ${KONG} true`); + }), + ); + + it.effect("fails a gateway GET whose body never completes once one probe timeout elapses", () => + withSilencedStderr( + Effect.gen(function* () { + const mock = mockHealthSpawner(() => EXEC_FAILED_STATE); + const stalledBody = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response( + new ReadableStream({ + start: (controller) => controller.enqueue(new TextEncoder().encode("{")), + }), + { status: 200 }, + ), + ), + ), + ), + ); + + const fiber = yield* settled( + mock, + [STORAGE], + { timeoutSeconds: 0, execFallbacks: gatewayFallback(STORAGE, STORAGE_STATUS_PATH) }, + stalledBody, + ).pipe(Effect.forkChild({ startImmediately: true })); + for (let second = 0; second < 9; second++) { + yield* TestClock.adjust("1 seconds"); + } + const pendingAtNineSeconds = fiber.pollUnsafe(); + yield* TestClock.adjust("1 seconds"); + const error = yield* Fiber.join(fiber).pipe(Effect.flip); + + expect(pendingAtNineSeconds).toBeUndefined(); + expect(error).toBeInstanceOf(HealthCheckTimeoutError); + expect(error.unhealthy).toEqual([ + { + containerId: STORAGE, + reason: expect.stringMatching( + /^container is not ready: \/storage\/v1\/status: TimeoutError/u, + ), + }, + ]); + }), + ), + ); + + it.effect("joins the exec-format and exec-unavailable advice for different containers", () => + Effect.gen(function* () { + const broken = "supabase_inbucket_proj"; + const mock = mockHealthSpawner( + (containerId) => (containerId === broken ? notRunning : EXEC_FAILED_STATE), + { [broken]: ["exec /mailpit: exec format error\n"] }, + ); + + const error = yield* timeoutFailure(mock, [broken, STUDIO], { + images: new Map([[broken, "public.ecr.aws/supabase/mailpit:v1.30.2"]]), + }); + + const suggestion = error.suggestion ?? ""; + expect(suggestion).toContain(`${broken}'s image public.ecr.aws/supabase/mailpit:v1.30.2`); + expect(suggestion).toContain( + `architecture.\n\nDocker could not run the health check inside ${STUDIO} (`, + ); + expect(suggestion).not.toContain(`inside ${broken}`); + }), + ); + + it.effect("does not blame exec for an ordinary failure beside an accepted exec-failed one", () => + Effect.gen(function* () { + const mock = mockHealthSpawner((containerId) => + containerId === STUDIO ? EXEC_FAILED_STATE : orderlyUnhealthy, + ); + + const error = yield* timeoutFailure(mock, [STUDIO, STORAGE], { + execFallbacks: runningFallback(STUDIO), + }); + + expect(error.unhealthy.map((failure) => failure.containerId)).toEqual([STORAGE]); + expect(error.suggestion).toBeUndefined(); + }), + ); + + it.effect("reports nothing as exec-unavailable while Docker's health check works", () => + Effect.gen(function* () { + const orderlyStarting = inspectedState({ + health: "starting", + probes: [{ exitCode: 1, output: "pg_isready: no response" }], + }); + const mock = mockHealthSpawner((_id, callIndex) => + callIndex === 0 ? orderlyStarting : runningHealthy, + ); + + const fiber = yield* settled(mock, [STUDIO], { + execFallbacks: runningFallback(STUDIO), + }).pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("1 seconds"); + const result = yield* Fiber.join(fiber); + + expect(result).toEqual({ execUnavailable: [], readinessAssumed: [] }); + }), + ); +}); + +describe("healthCheckExecUnavailableWarning", () => { + it("names every container whose readiness was not verified", () => { + const warning = healthCheckExecUnavailableWarning([ + "supabase_realtime_proj", + "supabase_studio_proj", + ]); + + expect(warning).toContain("WARNING:"); + expect(warning).toContain("(OCI runtime exec failed)"); + expect(warning).toContain( + "Readiness of supabase_realtime_proj, supabase_studio_proj was not verified.", + ); + expect(warning.endsWith("\n")).toBe(true); + }); + + it("says readiness was checked from the host when every container was verified", () => { + const warning = healthCheckExecUnavailableWarning([]); + + expect(warning).toContain("Readiness was checked from the host instead."); + expect(warning).not.toContain("was not verified"); + }); +}); + +describe("awaitDockerHealthSettled", () => { + const DB = "supabase_db_proj"; + + const run = (mock: ReturnType) => + Effect.gen(function* () { + const fiber = yield* awaitDockerHealthSettled(mock.spawner, DB).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust("1 seconds"); + return yield* Fiber.await(fiber); + }); + + const settlesImmediately: ReadonlyArray = [ + ["Docker already reports it healthy", runningHealthy], + ["its health check cannot run on this host", EXEC_FAILED_STATE], + [ + "an exec failure is recorded while Docker still reports starting", + inspectedState({ + health: "starting", + probes: [{ exitCode: -1, output: EXEC_FAILURE_OUTPUT }], + }), + ], + ["it is no longer running", notRunning], + [ + "Docker reports it unhealthy", + inspectedState({ health: "unhealthy", probes: [{ exitCode: 1, output: "no response" }] }), + ], + ["it has no health check", inspectedState()], + ]; + for (const [scenario, state] of settlesImmediately) { + it.effect(`returns after a single inspect when ${scenario}`, () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => state); + + const exit = yield* run(mock); + + expect(Exit.isSuccess(exit)).toBe(true); + expect(inspectCalls(mock)).toHaveLength(1); + }), + ); + } + + it.effect("succeeds without retrying when the inspect itself fails", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => runningStarting, {}, { inspectFails: true }); + + const exit = yield* run(mock); + + expect(Exit.isSuccess(exit)).toBe(true); + expect(inspectCalls(mock)).toHaveLength(1); + }), + ); + + it.effect("keeps polling while Docker reports starting and returns once it settles", () => + Effect.gen(function* () { + const mock = mockHealthSpawner((_id, callIndex) => + callIndex < 2 ? runningStarting : runningHealthy, + ); + + const fiber = yield* awaitDockerHealthSettled(mock.spawner, DB).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust("1 seconds"); + yield* TestClock.adjust("1 seconds"); + const exit = yield* Fiber.await(fiber); + + expect(Exit.isSuccess(exit)).toBe(true); + expect(inspectCalls(mock)).toHaveLength(3); + }), + ); + + it.effect("gives up without failing after 15 seconds of starting, and stops polling", () => + Effect.gen(function* () { + const mock = mockHealthSpawner(() => runningStarting); + + const fiber = yield* awaitDockerHealthSettled(mock.spawner, DB).pipe( + Effect.forkChild({ startImmediately: true }), + ); + for (let second = 0; second < 14; second++) { + yield* TestClock.adjust("1 seconds"); + } + const pendingAt14Seconds = fiber.pollUnsafe(); + yield* TestClock.adjust("1 seconds"); + const exit = yield* Fiber.await(fiber); + const pollsAtCap = inspectCalls(mock).length; + yield* TestClock.adjust("10 seconds"); + + expect(pendingAt14Seconds).toBeUndefined(); + expect(Exit.isSuccess(exit)).toBe(true); + expect(inspectCalls(mock)).toHaveLength(pollsAtCap); + }), + ); +}); diff --git a/apps/cli/src/command-internal/db-bootstrap/recreate-local-database.ts b/apps/cli/src/command-internal/db-bootstrap/recreate-local-database.ts index 8e5bd3549c..0e13168419 100644 --- a/apps/cli/src/command-internal/db-bootstrap/recreate-local-database.ts +++ b/apps/cli/src/command-internal/db-bootstrap/recreate-local-database.ts @@ -2,7 +2,7 @@ * `db reset --local`'s container-recreate composition — not a thin wrapper over * {@link startDatabase}, since the shared `StartDatabase`-equivalent primitive is never called * from a reset either. Reuses the same underlying primitives (`ensureNetwork`, - * `buildPostgresStartContainerSpec`, `createContainer`, `waitForHealthyServices`, + * `buildPostgresStartContainerSpec`, `createContainer`, `waitForPostgresReady`, * `startSetupLocalDatabase`) with a distinct sequence per major version: PG >= 15 recreates the * container/volume/network and re-runs setup; PG <= 14 recreates the two databases in place and * reinitializes the schema. Neither path probes for an existing volume, supports @@ -53,7 +53,11 @@ import { type FreshDbSetupInput, type StartSetupLocalDatabaseError, } from "./db-setup.ts"; -import { waitForHealthyServices, type HealthCheckTimeoutError } from "./health-check.ts"; +import { + awaitDockerHealthSettled, + waitForPostgresReady, + type HealthCheckTimeoutError, +} from "./health-check.ts"; import type { ImagePrepullError } from "./image-prepull.ts"; import { startInternalDbPassword } from "./internal-db-connection.ts"; import { @@ -284,10 +288,18 @@ const recreateLocalDatabase15 = ( yield* createContainer(spawner, postgresSpec, input.containerOpts); // Never swallowed — reset has no `--from-backup`-equivalent gate. - yield* waitForHealthyServices(spawner, [postgresSpec.containerName], { - timeoutSeconds: input.dbHealthTimeoutSeconds, - images: new Map([[postgresSpec.containerName, resolvedPostgresImage]]), - }); + yield* waitForPostgresReady( + spawner, + postgresSpec.containerName, + { + host: input.hostname, + port: input.dbPort, + user: "postgres", + password: startInternalDbPassword(input.setup.dbUrl), + database: "postgres", + }, + { timeoutSeconds: input.dbHealthTimeoutSeconds, image: resolvedPostgresImage }, + ); // No fresh-volume gate needed: a reset just removed the volume above, so it's always fresh. // Passes the resolved reset `version`/`seedFlags`, unlike `db start`'s own call. @@ -378,9 +390,18 @@ const recreateLocalDatabase14 = ( // the satellite restarts inside `restartServicesAndReloadKong`. yield* output.raw("Restarting containers...\n", "stderr"); yield* restartContainer(spawner, input.dbContainerId); - yield* waitForHealthyServices(spawner, [input.dbContainerId], { - timeoutSeconds: input.dbHealthTimeoutSeconds, - }); + yield* waitForPostgresReady( + spawner, + input.dbContainerId, + { + host: input.hostname, + port: input.dbPort, + user: "postgres", + password: dbPassword, + database: "postgres", + }, + { timeoutSeconds: input.dbHealthTimeoutSeconds }, + ); yield* restartServicesAndReloadKong(spawner, input.projectId); // Final connect as `postgres`/`postgres` to migrate and seed. @@ -421,6 +442,7 @@ export const recreateLocalDatabase = ( ? recreateLocalDatabase14(spawner, input) : recreateLocalDatabase15(spawner, input) ).pipe( + Effect.tap(() => awaitDockerHealthSettled(spawner, input.dbContainerId)), Effect.withSpan("DbBootstrap.recreateLocalDatabase", { attributes: { "db.major_version": input.setup.majorVersion }, }), diff --git a/apps/cli/src/command-internal/db-bootstrap/shadow-cache.ts b/apps/cli/src/command-internal/db-bootstrap/shadow-cache.ts index 8ecf4f3542..75513e6f8e 100644 --- a/apps/cli/src/command-internal/db-bootstrap/shadow-cache.ts +++ b/apps/cli/src/command-internal/db-bootstrap/shadow-cache.ts @@ -40,7 +40,7 @@ import { START_DB_SCHEMA_SQL } from "./templates/db-schema.sql.ts"; import { START_DB_SUPABASE_SQL } from "./templates/db-supabase.sql.ts"; import { START_DB_WEBHOOK_SQL } from "./templates/db-webhook.sql.ts"; import { CREATE_VAULT_KV, READ_VAULT_KV, UPDATE_VAULT_KV, type VaultSecret } from "../vault.ts"; -import { waitForShadowReady } from "./health-check.ts"; +import { waitForPostgresReady } from "./health-check.ts"; import { exportPgDataTar, pgDataRestoreArchive, @@ -532,7 +532,7 @@ const awaitShadowReady = ( containerId: string, what: string, ): Effect.Effect => - waitForShadowReady(spawner, containerId, shadowConnConfig(input), { + waitForPostgresReady(spawner, containerId, shadowConnConfig(input), { timeoutSeconds: input.healthTimeoutSeconds, image: input.image, }).pipe( diff --git a/apps/cli/src/command-internal/db-bootstrap/start-database.ts b/apps/cli/src/command-internal/db-bootstrap/start-database.ts index 87268aef9c..383617d528 100644 --- a/apps/cli/src/command-internal/db-bootstrap/start-database.ts +++ b/apps/cli/src/command-internal/db-bootstrap/start-database.ts @@ -44,7 +44,8 @@ import { type StartSetupLocalDatabaseError, } from "./db-setup.ts"; import type { ImagePrepullError } from "./image-prepull.ts"; -import { waitForHealthyServices, type HealthCheckTimeoutError } from "./health-check.ts"; +import { waitForPostgresReady, type HealthCheckTimeoutError } from "./health-check.ts"; +import { startInternalDbPassword } from "./internal-db-connection.ts"; import { buildPostgresStartContainerSpec, type PostgresStartServiceInput, @@ -180,17 +181,23 @@ export const startDatabase = ( }); yield* createContainer(spawner, postgresSpec, input.containerOpts); - const postgresHealthResult = yield* waitForHealthyServices( + // A host connect, not Docker's HEALTHCHECK: that needs `docker exec`, which nested or + // sandboxed Docker cannot do. + const postgresHealthResult = yield* waitForPostgresReady( spawner, - [postgresSpec.containerName], + postgresSpec.containerName, { - timeoutSeconds: input.dbHealthTimeoutSeconds, - images: new Map([[postgresSpec.containerName, resolvedPostgresImage]]), + host: input.hostname, + port: input.dbPort, + user: "postgres", + password: startInternalDbPassword(input.setup.dbUrl), + database: "postgres", }, + { timeoutSeconds: input.dbHealthTimeoutSeconds, image: resolvedPostgresImage }, ).pipe(Effect.result); if (Result.isFailure(postgresHealthResult)) { // Discarded only when `fromBackup` is set — the log dump to stderr already happened - // inside `waitForHealthyServices` regardless. Any other failure propagates bare; see this + // inside `waitForPostgresReady` regardless. Any other failure propagates bare; see this // module's header for why `--ignore-health-check` is entirely the caller's concern. if (fromBackup === undefined) { return yield* postgresHealthResult.failure; diff --git a/apps/cli/src/command-internal/db-bootstrap/start-local-database.ts b/apps/cli/src/command-internal/db-bootstrap/start-local-database.ts index 6997ef6b94..5d042f9392 100644 --- a/apps/cli/src/command-internal/db-bootstrap/start-local-database.ts +++ b/apps/cli/src/command-internal/db-bootstrap/start-local-database.ts @@ -51,6 +51,7 @@ import { goUrlParse } from "../storage-url.ts"; import { loadLocalProjectContext } from "../local-project-context.ts"; import { cliProjectFilterValue } from "../docker-ids.ts"; import { buildLocalDbContainerInputs } from "./local-container-inputs.ts"; +import { awaitDockerHealthSettled } from "./health-check.ts"; import { isLocalDbRunning } from "./local-db-running.ts"; import { rollbackStart } from "./rollback.ts"; import { startDatabase } from "./start-database.ts"; @@ -722,5 +723,9 @@ export const startLocalDatabase = Effect.fn("DbBootstrap.startLocalDatabase")(fu ), ); + // The connect probe returns before Docker's first health probe, and `status` and the + // already-running gate still read Docker health. + yield* awaitDockerHealthSettled(spawner, dbContainerId); + return { status: "started" } satisfies StartLocalDatabaseResult; }); diff --git a/apps/cli/src/command-internal/docker-lifecycle.ts b/apps/cli/src/command-internal/docker-lifecycle.ts index 07878356a6..621c77e78a 100644 --- a/apps/cli/src/command-internal/docker-lifecycle.ts +++ b/apps/cli/src/command-internal/docker-lifecycle.ts @@ -235,13 +235,75 @@ export const inspectContainerState = (spawner: Spawner, containerId: string) => }), ).pipe(Effect.withTracerEnabled(false), Effect.provideService(ChildTracePropagation, false)); -function parseContainerState(stdout: string): { +/** The most recent health-check probe Docker recorded for a container. */ +interface ContainerHealthProbe { + readonly exitCode: number; + readonly output: string; +} + +export interface ContainerState { readonly running: boolean; readonly status: string; readonly exitCode: number; readonly oomKilled: boolean; readonly health?: string; -} { + readonly lastHealthProbe?: ContainerHealthProbe; +} + +const HEALTH_PROBE_OUTPUT_MAX = 300; + +function parseLastHealthProbe(health: unknown): ContainerHealthProbe | undefined { + if (!isJsonRecord(health)) return undefined; + const log = health["Log"]; + if (!Array.isArray(log)) return undefined; + const last: unknown = log[log.length - 1]; + if (!isJsonRecord(last)) return undefined; + const exitCode = last["ExitCode"]; + const output = last["Output"]; + if (typeof exitCode !== "number" || typeof output !== "string") return undefined; + return { exitCode, output: output.replace(/\s+/gu, " ").trim() }; +} + +// runc reports a bad healthcheck command as a Go `exec.Error` or as an `os.PathError`. +const EXEC_IMAGE_FAULT_PATTERNS: ReadonlyArray = [ + /exec: \\?"[^"]*": (?:executable file not found in \$PATH|stat \S+: no such file or directory|permission denied)/u, + /(?:^|: )exec [^\s:]+: (?:no such file or directory|exec format error|permission denied)/u, +]; + +/** + * True when Docker could not launch the health check inside a running container. moby records an + * exec-start failure as probe exit code -1 with the runtime error as output; a probe timeout also + * uses -1 but its output never names the OCI runtime. Image faults in the healthcheck command are + * excluded: they are the image's problem, not the host's. + */ +export function healthCheckCannotExec(state: ContainerState): boolean { + const probe = state.lastHealthProbe; + if (!state.running || state.status !== "running" || state.health === "healthy") return false; + if (probe === undefined || probe.exitCode !== -1) return false; + const out = probe.output; + return ( + out.includes("OCI runtime exec failed") && + (out.includes("unable to start container process") || + out.includes("starting container process caused")) && + !EXEC_IMAGE_FAULT_PATTERNS.some((pattern) => pattern.test(out)) + ); +} + +/** The not-ready reason for an unhealthy container, naming its last health-check probe. */ +export function formatNotReadyReason(state: ContainerState): string { + const base = `container is not ready: ${state.health}`; + const probe = state.lastHealthProbe; + if (probe === undefined) return base; + const output = + probe.output.length > HEALTH_PROBE_OUTPUT_MAX + ? `${probe.output.slice(0, HEALTH_PROBE_OUTPUT_MAX - 1)}…` + : probe.output; + return output.length > 0 + ? `${base} (last health check exit code ${probe.exitCode}: ${output})` + : `${base} (last health check exit code ${probe.exitCode})`; +} + +function parseContainerState(stdout: string): ContainerState { const trimmed = stdout.trim(); let parsed: unknown; try { @@ -262,9 +324,15 @@ function parseContainerState(stdout: string): { const health = state["Health"]; const healthStatus = isJsonRecord(health) && typeof health["Status"] === "string" ? health["Status"] : undefined; - return healthStatus !== undefined - ? { running, status, exitCode, oomKilled, health: healthStatus } - : { running, status, exitCode, oomKilled }; + const lastHealthProbe = parseLastHealthProbe(health); + return { + running, + status, + exitCode, + oomKilled, + ...(healthStatus === undefined ? {} : { health: healthStatus }), + ...(lastHealthProbe === undefined ? {} : { lastHealthProbe }), + }; } function isJsonRecord(value: unknown): value is { readonly [key: string]: unknown } { diff --git a/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts b/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts index fe41ca0d35..136bac59fc 100644 --- a/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts +++ b/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts @@ -2,14 +2,22 @@ import { describe, expect, it } from "@effect/vitest"; import { Deferred, Effect, Sink, Stream } from "effect"; import { ChildProcessSpawner } from "effect/process"; +import { + EXEC_FAILURE_OUTPUT, + PROBE_TIMEOUT_OUTPUT, + inspectedState, +} from "../../tests/helpers/docker-health.ts"; import { classifyCliErrorActionability } from "../shared/telemetry/error-actionability.ts"; import { DockerLifecycleInspectError, DockerLifecycleListError, + formatNotReadyReason, + healthCheckCannotExec, inspectContainerState, listContainerIdsAndNames, listContainersByLabel, listVolumesByLabel, + type ContainerState, } from "./docker-lifecycle.ts"; function mockSpawner( @@ -371,6 +379,289 @@ describe("inspectContainerState", () => { }); }); +describe("inspectContainerState health probe", () => { + const inspectLastProbe = (stdout: string) => + inspectContainerState(mockSpawner({ stdout }).spawner, "supabase_db_my-app"); + + it.live("reads the exec-start failure Docker recorded for a probe it could not launch", () => + inspectLastProbe( + inspectedState({ + health: "unhealthy", + probes: [{ exitCode: -1, output: EXEC_FAILURE_OUTPUT }], + }), + ).pipe( + Effect.map((state) => { + expect(state.health).toBe("unhealthy"); + expect(state.lastHealthProbe).toEqual({ exitCode: -1, output: EXEC_FAILURE_OUTPUT }); + expect(healthCheckCannotExec(state)).toBe(true); + }), + ), + ); + + it.live("keeps only the most recent entry of Health.Log", () => + inspectLastProbe( + inspectedState({ + health: "unhealthy", + probes: [ + { exitCode: 1, output: "first" }, + { exitCode: 2, output: "second" }, + { exitCode: 3, output: "third" }, + ], + }), + ).pipe( + Effect.map((state) => { + expect(state.lastHealthProbe).toEqual({ exitCode: 3, output: "third" }); + }), + ), + ); + + it.live("collapses whitespace runs and newlines in the probe output", () => + inspectLastProbe( + inspectedState({ + health: "unhealthy", + probes: [{ exitCode: 1, output: " pg_isready:\n\tno response\r\n " }], + }), + ).pipe( + Effect.map((state) => { + expect(state.lastHealthProbe?.output).toBe("pg_isready: no response"); + }), + ), + ); + + it.live("keeps probe output of exactly 300 characters whole", () => { + const output = "x".repeat(300); + return inspectLastProbe( + inspectedState({ health: "unhealthy", probes: [{ exitCode: 1, output }] }), + ).pipe( + Effect.map((state) => { + expect(state.lastHealthProbe?.output).toBe(output); + expect(formatNotReadyReason(state)).toContain(`: ${output})`); + }), + ); + }); + + it.live("keeps the full probe output and cuts only the rendered reason at 300 characters", () => + inspectLastProbe( + inspectedState({ + health: "unhealthy", + probes: [{ exitCode: 1, output: "x".repeat(301) }], + }), + ).pipe( + Effect.map((state) => { + expect(state.lastHealthProbe?.output).toBe("x".repeat(301)); + expect(formatNotReadyReason(state)).toContain(`: ${"x".repeat(299)}…)`); + }), + ), + ); + + const validProbe = { Start: "s", End: "e", ExitCode: 1, Output: "ok" }; + const malformedLogs: ReadonlyArray]> = [ + ["has no Log", { Status: "unhealthy" }], + ["has a Log that is not an array", { Status: "unhealthy", Log: "oops" }], + ["has an empty Log", { Status: "unhealthy", Log: [] }], + ["ends in an entry that is not an object", { Status: "unhealthy", Log: [validProbe, null] }], + ["ends in an entry with a string ExitCode", { Status: "unhealthy", Log: [{ ExitCode: "-1" }] }], + [ + "ends in an entry with no Output", + { Status: "unhealthy", Log: [validProbe, { ExitCode: -1 }] }, + ], + [ + "ends in an entry with a non-string Output", + { Status: "unhealthy", Log: [{ ExitCode: -1, Output: 7 }] }, + ], + ]; + for (const [scenario, health] of malformedLogs) { + it.live(`reports no probe when Health ${scenario}`, () => + inspectLastProbe(JSON.stringify({ Status: "running", Running: true, Health: health })).pipe( + Effect.map((state) => { + expect(state).toEqual({ + running: true, + status: "running", + exitCode: 0, + oomKilled: false, + health: "unhealthy", + }); + expect(state).not.toHaveProperty("lastHealthProbe"); + }), + ), + ); + } +}); + +describe("healthCheckCannotExec", () => { + const OLDER_RUNC_EXEC_FAILURE = + "OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: process_linux.go:103: executing setns process caused: exit status 1: unknown"; + + const state = (overrides: Partial = {}): ContainerState => ({ + running: true, + status: "running", + exitCode: 0, + oomKilled: false, + health: "unhealthy", + lastHealthProbe: { exitCode: -1, output: EXEC_FAILURE_OUTPUT }, + ...overrides, + }); + const probe = (exitCode: number, output: string) => ({ + lastHealthProbe: { exitCode, output }, + }); + const imageFaultPastTheDisplayedReason = `OCI runtime exec failed: exec failed: unable to start container process: ${"x".repeat(300)} exec: "/healthcheck.sh": permission denied: unknown`; + + const accepted: ReadonlyArray = [ + ["the exec-start failure Docker records on a sandboxed host", state()], + [ + "the same failure while Docker still reports the health as starting", + state({ health: "starting" }), + ], + ["the older runc wording of the same failure", state(probe(-1, OLDER_RUNC_EXEC_FAILURE))], + [ + "a cgroup path the host never created", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: unable to start container process: error adding pid 123 to cgroups: failed to write 123: openat2 /sys/fs/cgroup/docker/abc/cgroup.procs: no such file or directory: unknown", + ), + ), + ], + [ + "a namespace file the host never exposed", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: unable to start container process: error executing setns process: open /proc/123/ns/mnt: no such file or directory: unknown", + ), + ), + ], + [ + "runc unable to re-exec itself to enter the container", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: unable to start container process: error executing setns process: fork/exec /proc/self/exe: permission denied: unknown", + ), + ), + ], + ]; + for (const [scenario, input] of accepted) { + it(`detects ${scenario}`, () => { + expect(healthCheckCannotExec(input)).toBe(true); + }); + } + + const rejected: ReadonlyArray = [ + ["a probe that outlived its timeout", state(probe(-1, PROBE_TIMEOUT_OUTPUT))], + [ + "a missing healthcheck binary", + state( + probe( + -1, + 'OCI runtime exec failed: exec failed: unable to start container process: exec: "pg_isready": executable file not found in $PATH: unknown', + ), + ), + ], + [ + "a healthcheck binary path that does not exist", + state( + probe( + -1, + 'OCI runtime exec failed: exec failed: unable to start container process: exec: "/usr/bin/pg_isready": stat /usr/bin/pg_isready: no such file or directory: unknown', + ), + ), + ], + [ + "a healthcheck binary built for another architecture", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: unable to start container process: exec /usr/bin/pg_isready: exec format error: unknown", + ), + ), + ], + [ + "a healthcheck script that is not executable", + state( + probe( + -1, + 'OCI runtime exec failed: exec failed: unable to start container process: exec: "/healthcheck.sh": permission denied: unknown', + ), + ), + ], + [ + "a healthcheck script the kernel cannot open", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: unable to start container process: exec /healthcheck.sh: permission denied: unknown", + ), + ), + ], + [ + "a healthcheck script whose shebang interpreter is missing", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: unable to start container process: exec /healthcheck.sh: no such file or directory: unknown", + ), + ), + ], + [ + "an image fault that only appears after the first 300 characters", + state(probe(-1, imageFaultPastTheDisplayedReason)), + ], + [ + "an exec into a stopped container", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: cannot exec in a stopped container: unknown", + ), + ), + ], + ["a stopped container that once failed to exec", state({ running: false, status: "exited" })], + ["a restarting container", state({ status: "restarting" })], + ["a container Docker already reports healthy", state({ health: "healthy" })], + ["a probe that failed with an ordinary exit code", state(probe(1, EXEC_FAILURE_OUTPUT))], + ["a container with no recorded probe", state({ lastHealthProbe: undefined })], + ]; + for (const [scenario, input] of rejected) { + it(`does not mistake ${scenario} for an exec failure`, () => { + expect(healthCheckCannotExec(input)).toBe(false); + }); + } +}); + +describe("formatNotReadyReason", () => { + const unhealthy: ContainerState = { + running: true, + status: "running", + exitCode: 0, + oomKilled: false, + health: "unhealthy", + }; + + it("is the bare health status when Docker recorded no probe", () => { + expect(formatNotReadyReason({ ...unhealthy, health: "starting" })).toBe( + "container is not ready: starting", + ); + }); + + it("appends the last probe's exit code and output", () => { + expect( + formatNotReadyReason({ + ...unhealthy, + lastHealthProbe: { exitCode: -1, output: PROBE_TIMEOUT_OUTPUT }, + }), + ).toBe( + "container is not ready: unhealthy (last health check exit code -1: Health check exceeded timeout (2s))", + ); + }); + + it("appends only the exit code when the probe printed nothing", () => { + expect( + formatNotReadyReason({ ...unhealthy, lastHealthProbe: { exitCode: 1, output: "" } }), + ).toBe("container is not ready: unhealthy (last health check exit code 1)"); + }); +}); + describe("listVolumesByLabel", () => { it.live("returns volume names for a successful listing", () => { const mock = mockSpawner({ stdout: "supabase_db_my-app\n" }); diff --git a/apps/cli/src/commands/db/diff/SIDE_EFFECTS.md b/apps/cli/src/commands/db/diff/SIDE_EFFECTS.md index 58bd4dc5dd..56b1d5f7ed 100644 --- a/apps/cli/src/commands/db/diff/SIDE_EFFECTS.md +++ b/apps/cli/src/commands/db/diff/SIDE_EFFECTS.md @@ -72,7 +72,7 @@ it, and JSON `null` disables formatting without disabling safe compaction. (`pgdelta-next-shadow.layer.ts`), which builds on the same shadow-baseline cache primitives (`acquireShadowDatabase`), with no declarative-schema-override branch. `--use-pgadmin` provisions its OWN shadow via a - narrower composition — `createShadowDatabase` -> health-wait -> `migrateShadowDatabase` + narrower composition — `createShadowDatabase` -> readiness wait (host Postgres connect probe) -> `migrateShadowDatabase` directly (`diff.handler.ts`'s pgadmin branch) — with no declarative-schema-override branch and no `targetUrlOverride`. - When `[experimental].stack` / `SUPABASE_EXPERIMENTAL_STACK=1` is on, `--local` inspects the diff --git a/apps/cli/src/commands/db/diff/diff.handler.ts b/apps/cli/src/commands/db/diff/diff.handler.ts index 73e815dd97..7e9c4a447b 100644 --- a/apps/cli/src/commands/db/diff/diff.handler.ts +++ b/apps/cli/src/commands/db/diff/diff.handler.ts @@ -45,7 +45,7 @@ import { stackWithShadowDatabase, } from "../../../command-internal/stack-shadow.ts"; import { isLocalDbRunning } from "../../../command-internal/db-bootstrap/local-db-running.ts"; -import { waitForHealthyServices } from "../../../command-internal/db-bootstrap/health-check.ts"; +import { waitForPostgresReady } from "../../../command-internal/db-bootstrap/health-check.ts"; import { withShadowDatabase } from "../../../command-internal/db-bootstrap/shadow-cache.ts"; import { createShadowDatabase, @@ -658,7 +658,7 @@ export const dbDiff = Effect.fn("db.diff")(function* (flags: DbDiffFlags) { createShadowDatabase(spawner, shadowBase), (handle) => Effect.gen(function* () { - yield* waitForHealthyServices(spawner, [handle.containerId], { + yield* waitForPostgresReady(spawner, handle.containerId, shadowConnConfig, { timeoutSeconds: shadowBase.healthTimeoutSeconds, }); yield* migrateShadowDatabase(spawner, { diff --git a/apps/cli/src/commands/db/diff/diff.integration.test.ts b/apps/cli/src/commands/db/diff/diff.integration.test.ts index ae20831f95..341c4cf8ab 100644 --- a/apps/cli/src/commands/db/diff/diff.integration.test.ts +++ b/apps/cli/src/commands/db/diff/diff.integration.test.ts @@ -17,7 +17,6 @@ import { } from "effect"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; -import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { vi } from "vitest"; vi.mock("node:net", (importOriginal) => @@ -122,12 +121,10 @@ interface SetupOpts { // Fails the first `writeFileString` call whose path matches; prefer over // `failWriteOnCall` when shadow setup writes extra files first. readonly failWriteMatching?: (path: string) => boolean; - // Makes the shadow container never report healthy; only the `--use-pgadmin` branch - // gates on this (the shadow-source branch uses `neverConnectableShadow` instead). - readonly neverHealthyShadow?: boolean; - // Refuses every connect to the shadow's port, so `waitForShadowReady` keeps - // polling — the shadow-source branch's equivalent of `neverHealthyShadow`. + // Refuses every connect to the shadow's port, so `waitForPostgresReady` keeps polling. readonly neverConnectableShadow?: boolean; + // Docker reports every container's health check as unable to exec, as on a nested or sandboxed host. + readonly execFailedHealth?: boolean; // `CommandSettings.projectId`; defaults to `Option.some("test")`. Pass // `Option.none()` to exercise the config.toml/workdir-basename fallback // (`resolveLocalProjectId`). @@ -181,7 +178,7 @@ const SHADOW_PORT = 54320; /** * Records every `DbConnection.connect` target's database name and every `exec`/`query` run * against it. `neverConnectableShadow` fails every connect to the shadow port, leaving local - * connects untouched — this keeps a provisioning fiber suspended in `waitForShadowReady`'s + * connects untouched — this keeps a provisioning fiber suspended in `waitForPostgresReady`'s * retry loop. */ function fakeShadowDbConnection(opts: { readonly neverConnectableShadow?: boolean } = {}) { @@ -221,30 +218,10 @@ function setup(workdir: string, opts: SetupOpts = {}) { // A docker-spawner fake backs container lifecycle; a fake Postgres session backs // shadow setup. const shadowSpawner = mockShadowContainerCliSpawner({ - neverHealthy: opts.neverHealthyShadow ?? false, + execFailedHealth: opts.execFailedHealth ?? false, dbNotRunning: opts.dbNotRunning ?? false, dbInspectFailsWith: opts.dbInspectFailsWith, }); - const shadowHealthProbed = Deferred.makeUnsafe(); - const shadowSpawnerLayer = Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - Effect.map(ChildProcessSpawner.ChildProcessSpawner, (inner) => - ChildProcessSpawner.make((command) => - inner - .spawn(command) - .pipe( - Effect.tap(() => - ChildProcess.isStandardCommand(command) && - command.args[0] === "container" && - command.args[1] === "inspect" && - command.args[2] === FAKE_SHADOW_CONTAINER_ID - ? Deferred.succeed(shadowHealthProbed, undefined) - : Effect.void, - ), - ), - ), - ), - ).pipe(Layer.provide(shadowSpawner.layer)); // Cache tests need the stateful Docker model since `docker cp` needs real container state. const dockerDaemon = opts.statefulDocker === true ? mockDockerDaemonCliSpawner() : undefined; const shadowDbConnection = fakeShadowDbConnection({ @@ -478,7 +455,7 @@ function setup(workdir: string, opts: SetupOpts = {}) { edge, docker, shadowDbConnection.layer, - dockerDaemon?.layer ?? shadowSpawnerLayer, + dockerDaemon?.layer ?? shadowSpawner.layer, mockLocalDockerEngineUnavailableLayer, alwaysReadyHttpClientLayer, opts.realLayers === true @@ -538,7 +515,6 @@ function setup(workdir: string, opts: SetupOpts = {}) { differRegistryEnvAtCall, shadowSetupJobCalls, shadowSpawned: shadowSpawner.spawned, - shadowHealthProbed, dockerDaemon, shadowConnectedDatabases: shadowDbConnection.connectedDatabases, shadowExecCalls: shadowDbConnection.execCalls, @@ -640,6 +616,21 @@ describe("db diff", () => { }).pipe(Effect.provide(s.layer), (body) => withEnvVar("GITHUB_HEAD_REF", undefined, body)); }); + it.effect( + "diffs when Docker cannot exec the shadow's health check but the shadow accepts connections", + () => { + const s = setup(tmp.current, { + diffSql: "create table players ();\n", + execFailedHealth: true, + }); + return Effect.gen(function* () { + yield* dbDiff(flags()); + expect(stdout(s.out)).toBe("create table players ();\n\n"); + expect(s.shadowSpawned.filter((c) => c.args[0] === "rm")).toHaveLength(1); + }).pipe(Effect.provide(s.layer)); + }, + ); + it.effect("forwards SUPABASE_SSL_DEBUG=TRUE to the migra script as true", () => { const s = setup(tmp.current, { diffSql: "create table players ();\n" }); return Effect.gen(function* () { @@ -2119,7 +2110,7 @@ describe("db diff", () => { Effect.forkChild({ startImmediately: true }), ); // Waits until the shadow's readiness gate has refused a connect at least once, - // proving the fiber is suspended in `waitForShadowReady`'s retry loop. + // proving the fiber is suspended in `waitForPostgresReady`'s retry loop. yield* Deferred.await(s.shadowConnectRefused); // `Fiber.interrupt` only resolves once finalizers complete; this would hang (the readiness // timeout never elapses under the test clock) if `acquire` still covered the readiness wait. @@ -2165,6 +2156,21 @@ describe("db diff", () => { }, ); + it.effect( + "diffs when Docker cannot exec the shadow's health check but the shadow accepts connections", + () => { + const s = setup(tmp.current, { + pgadminStdout: [JSON.stringify([pgadminEntry()])], + execFailedHealth: true, + }); + return Effect.gen(function* () { + yield* dbDiff(flags({ usePgAdmin: Option.some(true) })); + expect(stdout(s.out)).toContain("ALTER TABLE test;"); + expect(s.shadowSpawned.filter((c) => c.args[0] === "rm")).toHaveLength(1); + }).pipe(Effect.provide(s.layer)); + }, + ); + it.effect("writes a timestamped migration for --use-pgadmin --file instead of printing", () => { const s = setup(tmp.current, { pgadminStdout: [JSON.stringify([pgadminEntry()])] }); return Effect.gen(function* () { @@ -2643,16 +2649,13 @@ describe("db diff", () => { it.effect( "removes the shadow container on interruption during the health wait for --use-pgadmin too", () => { - const s = setup(tmp.current, { neverHealthyShadow: true }); + const s = setup(tmp.current, { neverConnectableShadow: true }); return Effect.gen(function* () { const fiber = yield* dbDiff(flags({ usePgAdmin: Option.some(true) })).pipe( Effect.provide(s.layer), Effect.forkChild({ startImmediately: true }), ); - // Waits for the shadow's own health probe (its 64-hex id); the pgadmin path's - // separate `supabase_db_test` probe fires first and would satisfy a looser - // check immediately. - yield* Deferred.await(s.shadowHealthProbed); + yield* Deferred.await(s.shadowConnectRefused); yield* Fiber.interrupt(fiber); expect(s.shadowSpawned.filter((c) => c.args[0] === "create")).toHaveLength(1); expect(s.shadowSpawned.filter((c) => c.args[0] === "rm")).toHaveLength(1); diff --git a/apps/cli/src/commands/db/reset/SIDE_EFFECTS.md b/apps/cli/src/commands/db/reset/SIDE_EFFECTS.md index 4b83d29bfe..68f8ba9e2b 100644 --- a/apps/cli/src/commands/db/reset/SIDE_EFFECTS.md +++ b/apps/cli/src/commands/db/reset/SIDE_EFFECTS.md @@ -103,6 +103,16 @@ equivalent, PG15) or `InitSchema14`/`ApplyApiPrivileges` (PG14). | `docker container inspect ` + `docker exec kong reload --nginx-conf /home/kong/custom_nginx.template` | local path, both PG14 and PG15 | reload Kong so it re-resolves the restarted containers' addresses (issue #6016) — the `--nginx-conf` flag is load-bearing: a bare `kong reload` regenerates nginx.conf from Kong's default template and drops the custom `email_templates` server (#6059) | | `docker container inspect supabase_storage_` | local path | storage-health gate before bucket seeding | +The recreated database's readiness (PG15 after `docker start`, PG14 after `docker restart`) is not +read from Docker's health status, which needs `docker exec` that some hosts cannot do. It polls +every 500ms within `db.health_timeout`: `docker container inspect supabase_db_` (a +container that is not running fails at once), then a short-lived host connect as `postgres` to the +published Postgres address (2s dial cap). Before the command returns, it waits up to 15s for +Docker's first health verdict on the database container (polling `docker container inspect` every +1s until the status leaves `starting`, the container stops running, or Docker cannot launch its +health check), so a following `supabase status` does not see `starting`. That wait never fails the +reset. + No subprocess delegation remains on either target — the remote path's `--experimental` schema-files apply (formerly delegated to a `supabase-go db reset` child) is fully native as of CLI-1958. diff --git a/apps/cli/src/commands/db/reset/reset.integration.test.ts b/apps/cli/src/commands/db/reset/reset.integration.test.ts index bf82f8350d..453dc96a51 100644 --- a/apps/cli/src/commands/db/reset/reset.integration.test.ts +++ b/apps/cli/src/commands/db/reset/reset.integration.test.ts @@ -50,6 +50,7 @@ import { sequentialExecBatch, transportFailure, } from "../../../../tests/helpers/command-mocks.ts"; +import { EXEC_FAILED_STATE } from "../../../../tests/helpers/docker-health.ts"; import { assertPermissionDrift } from "../../../../tests/helpers/permission-drift.ts"; import { asRecordedRequests, @@ -101,7 +102,7 @@ import type { DbConfigFlags, ResolvedDbConfig } from "../../../command-internal/ import { DbConfigConnectTempRoleError } from "../../../command-internal/db-config.errors.ts"; import { generateGoJwt } from "../../../command-internal/go-jwt.ts"; import { LocalDockerEngine } from "../../../command-internal/db-bootstrap/local-db-running.ts"; -import { DbExecError } from "../../../command-internal/db-connection.errors.ts"; +import { DbConnectError, DbExecError } from "../../../command-internal/db-connection.errors.ts"; import { DbConnection, type PgConnInput, @@ -207,6 +208,8 @@ function mockConnection( /** When set, an `exec` whose SQL contains this substring fails instead of succeeding. */ execFailsOn?: string; execFailsMessage?: string; + /** Refuses every connect, so the local recreate's Postgres readiness probe never succeeds. */ + neverConnectable?: boolean; } = {}, ) { const execs: Array = []; @@ -214,6 +217,9 @@ function mockConnection( let replicationCallIndex = 0; const layer = Layer.succeed(DbConnection, { connect: () => { + if (opts.neverConnectable === true) { + return Effect.fail(new DbConnectError({ message: "connection refused" })); + } const session: DbSession = { extensionExists: () => Effect.succeed(false), copyToCsv: () => Effect.succeed(new Uint8Array()), @@ -283,7 +289,6 @@ const KONG_ID = `supabase_kong_${PROJECT_ID}`; const STORAGE_ID = `supabase_storage_${PROJECT_ID}`; const HEALTHY_STATE = '{"Running":true,"Status":"running","Health":{"Status":"healthy"}}'; -const STARTING_STATE = '{"Running":true,"Status":"running","Health":{"Status":"starting"}}'; const STOPPED_STATE = '{"Running":false,"Status":"exited"}'; interface SpawnRecord { @@ -381,7 +386,6 @@ const dbSetupJobCalls = (spawned: ReadonlyArray): ReadonlyArray>; execFailsOn?: string; execFailsMessage?: string; + neverConnectable?: boolean; yes?: boolean; omitRef?: boolean; resolveFails?: boolean; @@ -1158,6 +1162,28 @@ describe("db reset", () => { ); }); + it.effect( + "recreates when Docker cannot exec the database's health check but it accepts connections", + () => { + const base = defaultLocalResetRoute(); + const { layer, out, child } = setup(tmp.current, { + toml: 'project_id = "test"\n', + args: ["db", "reset", "--local"], + isLocal: true, + route: (args) => + args[0] === "container" && args[1] === "inspect" && args[2] === DB_ID + ? { stdout: [EXEC_FAILED_STATE] } + : base(args), + }); + return Effect.gen(function* () { + yield* dbReset(DEFAULT_FLAGS).pipe(Effect.provide(layer)); + + expect(dbSetupJobCalls(child.spawned)).toHaveLength(3); + expect(out.stderrText).toContain("Finished supabase db reset.\n"); + }); + }, + ); + it.effect( "passes the resolved --version through to the setup pipeline's seed/migrate step", () => { @@ -2195,6 +2221,28 @@ describe("db reset", () => { }); describe("local reset — PG14", () => { + it.effect( + "resets when Docker cannot exec the restarted database's health check but it accepts connections", + () => { + const base = defaultLocalResetRoute(); + const { layer, out, child } = setup(tmp.current, { + toml: PG14_TOML, + args: ["db", "reset", "--local"], + isLocal: true, + route: (args) => + args[0] === "container" && args[1] === "inspect" && args[2] === DB_ID + ? { stdout: [EXEC_FAILED_STATE] } + : base(args), + }); + return Effect.gen(function* () { + yield* dbReset(DEFAULT_FLAGS).pipe(Effect.provide(layer)); + + expect(restartedContainers(child.spawned)).toContain(DB_ID); + expect(out.stderrText).toContain("Finished supabase db reset.\n"); + }); + }, + ); + it.effect( "recreates via the four-statement DROP/CREATE sequence, then initDatabase + RestartDatabase", () => { @@ -2552,12 +2600,12 @@ describe("db reset", () => { }); describe("local reset — health timeouts", () => { - it.live("a container health-check timeout fails the whole recreate", () => { + it.live("a database that never accepts connections fails the whole recreate", () => { const { layer } = setup(tmp.current, { toml: `project_id = "test"\n${FAST_HEALTH_TOML}`, args: ["db", "reset", "--local"], isLocal: true, - routeOpts: { neverHealthy: true }, + neverConnectable: true, }); return Effect.gen(function* () { const exit = yield* dbReset(DEFAULT_FLAGS).pipe(Effect.provide(layer), Effect.exit); diff --git a/apps/cli/src/commands/db/shared/pgdelta-next-shadow.layer.ts b/apps/cli/src/commands/db/shared/pgdelta-next-shadow.layer.ts index f9ac1ef9d4..cb7ee7ae13 100644 --- a/apps/cli/src/commands/db/shared/pgdelta-next-shadow.layer.ts +++ b/apps/cli/src/commands/db/shared/pgdelta-next-shadow.layer.ts @@ -17,7 +17,7 @@ import { buildLocalDbContainerInputs, type LocalDbContainerInputs, } from "../../../command-internal/db-bootstrap/local-container-inputs.ts"; -import { waitForShadowReady } from "../../../command-internal/db-bootstrap/health-check.ts"; +import { waitForPostgresReady } from "../../../command-internal/db-bootstrap/health-check.ts"; import { acquireShadowDatabase, peekShadowBaseline, @@ -249,7 +249,7 @@ export const pgDeltaNextShadowLayer = Layer.effect( ); const awaitShadowReady = (input: NativeShadowInput, handle: ShadowAcquiredHandle) => - waitForShadowReady(input.spawner, handle.containerId, shadowConnConfig(input.base), { + waitForPostgresReady(input.spawner, handle.containerId, shadowConnConfig(input.base), { timeoutSeconds: input.base.healthTimeoutSeconds, image: input.base.image, }); diff --git a/apps/cli/src/commands/db/shared/shadow-source.ts b/apps/cli/src/commands/db/shared/shadow-source.ts index b2eeaa4f09..bf69091097 100644 --- a/apps/cli/src/commands/db/shared/shadow-source.ts +++ b/apps/cli/src/commands/db/shared/shadow-source.ts @@ -28,7 +28,7 @@ import { import type { DockerRun } from "../../../command-internal/docker-run.service.ts"; import type { ImagePrepullError } from "../../../command-internal/db-bootstrap/image-prepull.ts"; import type { HealthCheckTimeoutError } from "../../../command-internal/db-bootstrap/health-check.ts"; -import { waitForShadowReady } from "../../../command-internal/db-bootstrap/health-check.ts"; +import { waitForPostgresReady } from "../../../command-internal/db-bootstrap/health-check.ts"; import { seedGlobals } from "../../../command-internal/migration-apply.ts"; import { BAD_PATTERN_MESSAGE, pathMatch } from "../../../command-internal/path-match.ts"; import { toPostgresURL } from "../../../command-internal/postgres-url.ts"; @@ -95,7 +95,7 @@ export const prepareShadowSource = Effect.fn("ShadowSource.prepare")(function* < database: "postgres", }; - yield* waitForShadowReady(spawner, containerId, connConfig, { + yield* waitForPostgresReady(spawner, containerId, connConfig, { timeoutSeconds: input.healthTimeoutSeconds, image: input.image, }); diff --git a/apps/cli/src/commands/db/start/SIDE_EFFECTS.md b/apps/cli/src/commands/db/start/SIDE_EFFECTS.md index 10b9290306..35858029a5 100644 --- a/apps/cli/src/commands/db/start/SIDE_EFFECTS.md +++ b/apps/cli/src/commands/db/start/SIDE_EFFECTS.md @@ -42,9 +42,14 @@ composition reuses too — see that command's `SIDE_EFFECTS.md`): `ghcr.io/supabase/cli/postgres`; a historical `.temp/postgres-version` pin, PG14, OrioleDB tags the catalog does not pin, and flag-off majors 13/15 (`15.8.1.085`) stay on docker.io. The restore entrypoint is the same on both families. -6. Wait for the container to become healthy (`db.health_timeout`, default `2m`). A timeout - fails the command UNLESS `--from-backup` is set, in which case it is swallowed (a large - restore can exceed the timeout) — the container-logs dump to stderr still happens +6. Wait for Postgres to accept connections (`db.health_timeout`, default `2m`): every 500ms, + `docker container inspect` (a container that is not running fails the wait at once), then a + short-lived host connect to the published Postgres address (2s dial cap) — Docker's health + status is not read, because it needs `docker exec`, which nested or sandboxed Docker cannot + do, and lags connectability by up to one 10s interval. A timeout fails the command with + ` container is not ready: ` UNLESS `--from-backup` is set, in + which case it is swallowed (a large restore can exceed the timeout) — the container-logs dump + to stderr, and the `exec format error` recovery advice when the logs show it, still happen either way. 7. On a fresh volume with `--from-backup` unset: run the `SetupLocalDatabase`-equivalent pipeline (`command-internal/db-bootstrap/db-setup.ts`) — initial schema (PG<=14: SQL over a @@ -60,6 +65,10 @@ composition reuses too — see that command's `SIDE_EFFECTS.md`): that reaches this point (fresh volume, existing volume, and a swallowed `--from-backup` health-check timeout), but NOT on the already-running short-circuit or the `backup volume already exists` guard. +9. Wait up to 15s for Docker's first health verdict, so `supabase db start && supabase status` + does not see `starting`: poll `docker container inspect` every 1s until the health status + leaves `starting`, the container stops running, or Docker cannot launch its health check. Never + fails the command, whatever the outcome, and is not covered by the rollback below. Any failure from step 1 onward rolls back via `rollbackStart` (stop + prune every container/network this project's label matches; volumes are pruned too, but ONLY when the @@ -107,7 +116,7 @@ only spawns on fallback. | `docker image inspect` / `docker pull` (registry-fallback resolve) | when not already running — resolves the Postgres image | | `docker volume create --label ...` | when not already running, unless a `--from-backup` restore onto an existing volume (fails first) | | `docker create` + optional `docker cp - :/` + `docker start` | when not already running — `cp` streams one in-memory tar archive containing the pgsodium root key at its exact path when the selected entrypoint needs it | -| `docker container inspect` (repeated) | health-wait polling, 1s constant backoff up to `db.health_timeout` | +| `docker container inspect` (repeated) | readiness polling every 500ms up to `db.health_timeout`, then health-settle polling every 1s for up to 15s | | `docker logs ` | on a health-check timeout (either path — swallowed or not) | | `docker run --rm ...` | fresh volume, no `--from-backup`, `db.major_version >= 15`: up to 3 one-shot migrate jobs (realtime/storage/auth) | | `docker ps` / `docker stop` / `docker container prune` / `docker volume prune` (fresh-volume runs only) / `docker network prune` | on ANY failure from network-ensure through `_current_branch` — the rollback | @@ -217,8 +226,8 @@ The resident owner process manages the database beyond the CLI invocation. Stack migration history owns it; existing volumes with webhooks disabled DROP a `pg_net` that migration history does not own. `pg_net` installed outside migrations (Studio SQL editor) is dropped on the next start — accepted, documented edge. -- `--from-backup` restores the database from a logical backup file on start; the health - check is skipped (not failed) for backups — a large restore can exceed +- `--from-backup` restores the database from a logical backup file on start; a readiness-wait + timeout is swallowed (not failed) for backups — a large restore can exceed `db.health_timeout`. - No `cli_stack_started` telemetry — that event belongs to `supabase start`, not `db start`. The only event is the standard `cli_command_executed`. diff --git a/apps/cli/src/commands/db/start/start.integration.test.ts b/apps/cli/src/commands/db/start/start.integration.test.ts index 2d4791b7d2..e94c1a53d7 100644 --- a/apps/cli/src/commands/db/start/start.integration.test.ts +++ b/apps/cli/src/commands/db/start/start.integration.test.ts @@ -2,8 +2,10 @@ import { BunServices } from "@effect/platform-bun"; import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest"; import { Cause, + Deferred, Effect, Exit, + Fiber, FileSystem, Layer, Option, @@ -16,6 +18,7 @@ import { import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vitest"; import { @@ -23,6 +26,7 @@ import { mockProcessControl, mockRuntimeInfo, } from "../../../../tests/helpers/mocks.ts"; +import { EXEC_FAILED_STATE } from "../../../../tests/helpers/docker-health.ts"; import { assertPermissionDrift } from "../../../../tests/helpers/permission-drift.ts"; import { unusedGateway } from "../../../../tests/helpers/unused-stack.ts"; import { @@ -176,7 +180,7 @@ function volumePruneWasAttempted(spawned: ReadonlyArray): boolean { } /** Stateful default route: only created containers inspect successfully, matching Docker across initial state detection and post-create health waits. Existing volume by default (a restart). */ -function defaultRoute(opts: { readonly neverHealthy?: boolean } = {}) { +function defaultRoute() { const created = new Set(); return (args: ReadonlyArray): RouteResult => { if (args[0] === "image" && args[1] === "inspect") return { exitCode: 0 }; @@ -196,7 +200,6 @@ function defaultRoute(opts: { readonly neverHealthy?: boolean } = {}) { if (!created.has(id)) { return { exitCode: 1, stderr: [`Error: No such container: ${id}`] }; } - if (opts.neverHealthy === true) return { stdout: [STARTING_STATE] }; return { stdout: [HEALTHY_STATE] }; } if (args[0] === "logs") return { exitCode: 0 }; @@ -217,6 +220,18 @@ function freshVolumeRoute( }; } +/** Docker's HEALTHCHECK can never launch on this host, so every created container reports exec-failed health. */ +function execFailedHealthRoute( + base: (args: ReadonlyArray) => RouteResult, +): (args: ReadonlyArray) => RouteResult { + return (args) => { + const result = base(args); + return args[0] === "container" && args[1] === "inspect" && result.stdout?.[0] === HEALTHY_STATE + ? { stdout: [EXEC_FAILED_STATE] } + : result; + }; +} + /** * Makes `isLocalDbRunning`'s pre-bring-up `container inspect` succeed unconditionally, * simulating an already-up local db — the already-running short-circuit returns before any @@ -311,8 +326,10 @@ interface SetupOpts { readonly experimental?: boolean; /** `--debug`. Defaults to `false`. */ readonly debug?: boolean; - /** Number of initial `DbConnection.connect` attempts that fail before succeeding. */ + /** Number of consecutive `DbConnection.connect` attempts that fail, from `connectFailuresStartAt`. */ readonly connectFailures?: number; + /** 1-based attempt number of the first failing connect. Attempt 1 is the Postgres readiness probe. Defaults to 1. */ + readonly connectFailuresStartAt?: number; /** Whether the mocked connect failures are dial-level (`retryable`). Defaults to `true`. */ readonly connectFailuresRetryable?: boolean; /** Record catalog apply targets instead of the default noop. */ @@ -353,11 +370,15 @@ function setup(opts: SetupOpts = {}) { let connectAttempts = 0; const connectFailures = opts.connectFailures ?? 0; + const connectFailuresStartAt = opts.connectFailuresStartAt ?? 1; const dbConnection = Layer.succeed(DbConnection, { connect: () => Effect.suspend(() => { connectAttempts += 1; - if (connectAttempts <= connectFailures) { + if ( + connectAttempts >= connectFailuresStartAt && + connectAttempts < connectFailuresStartAt + connectFailures + ) { return Effect.fail( new DbConnectError({ message: @@ -500,10 +521,14 @@ describe("db start", () => { it.live( "fresh volume: retries the host connect while the published port is not yet reachable (#6136)", () => { - const s = setup({ route: freshVolumeRoute(defaultRoute()), connectFailures: 2 }); + const s = setup({ + route: freshVolumeRoute(defaultRoute()), + connectFailuresStartAt: 2, + connectFailures: 2, + }); return Effect.gen(function* () { yield* dbStart(DEFAULT_FLAGS).pipe(Effect.provide(s.layer)); - expect(s.connectAttempts).toBe(3); + expect(s.connectAttempts).toBe(4); expect(yield* readCurrentBranch(tempRoot.current)).toBe("main"); }); }, @@ -513,13 +538,14 @@ describe("db start", () => { it.effect("fresh volume: a non-dial connect failure is not retried", () => { const s = setup({ route: freshVolumeRoute(defaultRoute()), + connectFailuresStartAt: 2, connectFailures: 1, connectFailuresRetryable: false, }); return Effect.gen(function* () { const exit = yield* dbStart(DEFAULT_FLAGS).pipe(Effect.provide(s.layer), Effect.exit); expect(Exit.isFailure(exit)).toBe(true); - expect(s.connectAttempts).toBe(1); + expect(s.connectAttempts).toBe(2); }); }); @@ -711,13 +737,63 @@ describe("db start", () => { }); }); + it.effect("starts when Docker's health check cannot exec but the host can connect", () => { + const s = setup({ route: execFailedHealthRoute(freshVolumeRoute(defaultRoute())) }); + return Effect.gen(function* () { + yield* dbStart(DEFAULT_FLAGS).pipe(Effect.provide(s.layer)); + expect(s.connectAttempts).toBeGreaterThan(0); + expect(rollbackWasAttempted(s.child.spawned)).toBe(false); + expect(yield* readCurrentBranch(tempRoot.current)).toBe("main"); + }); + }); + + it.effect("waits for Docker's first health verdict once the database accepts connections", () => { + const settleStarted = Deferred.makeUnsafe(); + const settleDone = Deferred.makeUnsafe(); + const base = freshVolumeRoute(defaultRoute()); + let inspectsAfterConnect = 0; + const s = setup({ + route: (args) => { + const result = base(args); + const isDbInspect = + args[0] === "container" && + args[1] === "inspect" && + result.stdout?.[0] === HEALTHY_STATE && + s.connectAttempts > 0; + if (!isDbInspect) return result; + inspectsAfterConnect += 1; + Deferred.doneUnsafe(settleStarted, Effect.void); + if (inspectsAfterConnect < 3) return { stdout: [STARTING_STATE] }; + Deferred.doneUnsafe(settleDone, Effect.void); + return result; + }, + }); + return Effect.gen(function* () { + const fiber = yield* dbStart(DEFAULT_FLAGS).pipe( + Effect.provide(s.layer), + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.raceFirst(Deferred.await(settleStarted), Fiber.await(fiber)); + // Small steps: the settle's own 15s cap must stay far away however many scheduler turns + // each poll needs before it registers its next sleep. + while (fiber.pollUnsafe() === undefined && !(yield* Deferred.isDone(settleDone))) { + yield* TestClock.adjust("100 millis"); + } + const exit = yield* Fiber.await(fiber); + + expect(Exit.isSuccess(exit)).toBe(true); + expect(inspectsAfterConnect).toBe(3); + }); + }); + it.live("a health-check timeout without --from-backup fails the command and rolls back", () => { // `db.health_timeout` (unlike the generic 30s `serviceTimeout` every other service waits on) // is a real config.toml-configurable seam — this keeps the scenario fast instead of waiting // out the real 2m default. const { layer, child } = setup({ configContents: 'project_id = "test"\n[db]\nhealth_timeout = "1s"\n', - route: freshVolumeRoute(defaultRoute({ neverHealthy: true })), + route: freshVolumeRoute(defaultRoute()), + connectFailures: Number.POSITIVE_INFINITY, }); return Effect.gen(function* () { const exit = yield* dbStart(DEFAULT_FLAGS).pipe(Effect.provide(layer), Effect.exit); @@ -737,7 +813,8 @@ describe("db start", () => { // it first. const { layer, child } = setup({ configContents: 'project_id = "test"\n[db]\nhealth_timeout = "1s"\n', - route: freshVolumeRoute(defaultRoute({ neverHealthy: true })), + route: freshVolumeRoute(defaultRoute()), + connectFailures: Number.POSITIVE_INFINITY, projectEnvContents: "SUPABASE_DEBUG=true\n", }); // This log write goes straight to the real process stderr, never the mocked Output @@ -769,7 +846,8 @@ describe("db start", () => { () => { const { layer, child } = setup({ configContents: 'project_id = "test"\n[db]\nhealth_timeout = "1s"\n', - route: freshVolumeRoute(defaultRoute({ neverHealthy: true })), + route: freshVolumeRoute(defaultRoute()), + connectFailures: Number.POSITIVE_INFINITY, }); return Effect.gen(function* () { // The stderr log dump on timeout is covered by the shared health-check.ts suite; this diff --git a/apps/cli/src/commands/migration/squash/SIDE_EFFECTS.md b/apps/cli/src/commands/migration/squash/SIDE_EFFECTS.md index f5ac95e80b..fb311377e8 100644 --- a/apps/cli/src/commands/migration/squash/SIDE_EFFECTS.md +++ b/apps/cli/src/commands/migration/squash/SIDE_EFFECTS.md @@ -57,7 +57,7 @@ live shadow available. - Network ensure (`ensureNetwork`, same as `db diff`/`db pull`). - Shadow Postgres container: no `--name`, no network alias, `--publish :5432`, `-c max_worker_processes=0`, `--rm`, PG≤14 tmpfs on `/docker-entrypoint-initdb.d` — created, - started, health-polled (`container inspect`), then removed (`rm -f -v`) once squash finishes, + started, readiness-polled (`container inspect` plus a host Postgres connect probe), then removed (`rm -f -v`) once squash finishes, success or failure. - PG15+ one-shot realtime/storage/auth migrate jobs (`initSchema15`), dialed at the shadow container's own 12-char short id as `DB_HOST` (no name/alias needed — see diff --git a/apps/cli/src/commands/migration/squash/squash.handler.ts b/apps/cli/src/commands/migration/squash/squash.handler.ts index 4d5d804e1c..a169f06050 100644 --- a/apps/cli/src/commands/migration/squash/squash.handler.ts +++ b/apps/cli/src/commands/migration/squash/squash.handler.ts @@ -23,7 +23,7 @@ import { resolveDbSetupPrelude, setupDatabase, } from "../../../command-internal/db-bootstrap/db-setup.ts"; -import { waitForHealthyServices } from "../../../command-internal/db-bootstrap/health-check.ts"; +import { waitForPostgresReady } from "../../../command-internal/db-bootstrap/health-check.ts"; import { buildShadowSetupDatabaseInput, connectShadowDatabase, @@ -209,7 +209,7 @@ const squashMigrations = Effect.fn("MigrationSquash.squashMigrations")(function* (handle) => Effect.scoped( Effect.gen(function* () { - yield* waitForHealthyServices(spawner, [handle.containerId], { + yield* waitForPostgresReady(spawner, handle.containerId, connConfig, { timeoutSeconds: shadowInput.healthTimeoutSeconds, }); const session = yield* connectShadowDatabase(connConfig); diff --git a/apps/cli/src/commands/migration/squash/squash.integration.test.ts b/apps/cli/src/commands/migration/squash/squash.integration.test.ts index 60745fec4f..d297c1f879 100644 --- a/apps/cli/src/commands/migration/squash/squash.integration.test.ts +++ b/apps/cli/src/commands/migration/squash/squash.integration.test.ts @@ -63,7 +63,7 @@ import { INTERNAL_SCHEMAS } from "../../../command-internal/pg-dump.env.ts"; import { dumpSchemaScript } from "../../../command-internal/pg-dump.scripts.ts"; import { DbConfigResolver } from "../../../command-internal/db-config.service.ts"; import type { DbConfigFlags, ResolvedDbConfig } from "../../../command-internal/db-config.types.ts"; -import { DbExecError } from "../../../command-internal/db-connection.errors.ts"; +import { DbConnectError, DbExecError } from "../../../command-internal/db-connection.errors.ts"; import { DbConnection, type DbSession, @@ -245,7 +245,9 @@ interface SetupOpts { readonly failResolve?: boolean; readonly failSql?: string; readonly networkId?: string; - readonly neverHealthyShadow?: boolean; + readonly neverConnectableShadow?: boolean; + /** Docker reports every container's health check as unable to exec, as on a nested or sandboxed host. */ + readonly execFailedHealth?: boolean; readonly failCreateShadow?: boolean; readonly failRemoveShadow?: boolean; readonly failSetupJob?: boolean; @@ -262,7 +264,7 @@ function setup(workdir: string, opts: SetupOpts = {}) { const cache = mockLinkedProjectCacheTracked(); const spawner = mockShadowContainerCliSpawner({ - neverHealthy: opts.neverHealthyShadow ?? false, + execFailedHealth: opts.execFailedHealth ?? false, failCreate: opts.failCreateShadow ?? false, failRemove: opts.failRemoveShadow ?? false, }); @@ -283,8 +285,11 @@ function setup(workdir: string, opts: SetupOpts = {}) { const connectedDatabases: Array = []; const connection = Layer.succeed(DbConnection, { connect: (cfg: PgConnInput) => - Effect.sync(() => { + Effect.gen(function* () { connectedDatabases.push(cfg.database); + if (opts.neverConnectableShadow === true) { + return yield* new DbConnectError({ message: "connection refused" }); + } const session: DbSession = { exec: (sql: string) => Effect.suspend(() => { @@ -731,6 +736,21 @@ describe("migration squash", () => { }, ); + it.effect( + "squashes when Docker cannot exec the shadow's health check but the shadow accepts connections", + () => { + const s = setupHappyPath({ execFailedHealth: true }); + return Effect.gen(function* () { + yield* seedHappyPathMigrations(tmp.current); + yield* migrationSquash(flags()); + + expect(yield* migrationExists(tmp.current, "0_init.sql")).toBe(false); + expect(yield* migrationExists(tmp.current, "1_target.sql")).toBe(true); + expect(s.shadowSpawned.filter((c) => c.args[0] === "rm")).toHaveLength(1); + }).pipe(Effect.provide(s.layer)); + }, + ); + it.effect( "runs the before/after dumps scoped to auth|storage and the full dump excluding the internal schemas", () => { @@ -912,11 +932,11 @@ describe("migration squash", () => { }); it.effect( - "fails with a health-check timeout when the shadow never becomes healthy, and removes it", + "fails with a health-check timeout when the shadow never becomes connectable, and removes it", () => { // A zero-second health timeout means zero retries after the first failed // probe — an immediate, deterministic timeout with no real/virtual delay. - const s = setup(tmp.current, { neverHealthyShadow: true }); + const s = setup(tmp.current, { neverConnectableShadow: true }); return Effect.gen(function* () { yield* seedMigration(tmp.current, "0_init.sql"); yield* seedMigration(tmp.current, "1_target.sql"); diff --git a/apps/cli/src/commands/start/SIDE_EFFECTS.md b/apps/cli/src/commands/start/SIDE_EFFECTS.md index 643804de2b..2d32734be0 100644 --- a/apps/cli/src/commands/start/SIDE_EFFECTS.md +++ b/apps/cli/src/commands/start/SIDE_EFFECTS.md @@ -73,6 +73,71 @@ tar archive) → `docker start` sequence is assembled by that shared core, not b health-checked via an HTTP probe through Kong (`/functions/v1/_internal/health`), not a Docker healthcheck — mirroring PostgREST's own probe shape. +### Readiness gating + +Postgres's own wait does not read Docker's health status: Docker runs every `HEALTHCHECK` with +`docker exec`, which some hosts cannot do (nested or sandboxed Docker), and +the status lags connectability by up to one 10s health interval. The wait polls every 500ms +within `db.health_timeout` (`SUPABASE_DB_HEALTH_TIMEOUT`): `docker container inspect` (a +container that is not running fails the wait at once), then a short-lived host connect to the +published Postgres address (2s dial cap). The first successful connect ends the wait. A timeout +reports ` container is not ready: `, after the container's logs. `db +start` runs the same wait, including with `--from-backup`. + +Every other health-checked container is gated on Docker's health status (`healthy`), polled once +per second within the 30s service timeout. A container with no Docker healthcheck passes once +it is running. PostgREST and Edge Runtime keep their HTTP HEAD probes through Kong. The wait also +stops after `(30 + 1) * (1 + 10)` seconds of wall-clock time, so a gateway that accepts +connections and never answers cannot outlast the retry budget; it then fails like an exhausted +budget, with the last round's reasons (`container is not ready: readiness probe hung after s` +when no round completed). + +After that wait, including when `--ignore-health-check` downgrades its failure and when no +health-checked service was started, `start` waits up to 15s for Docker's first health verdict on +the Postgres container (polling `docker container inspect` every 1s until the status leaves +`starting`, the container stops running, or Docker cannot launch its health check), so a +following `supabase status` or `supabase start` does not see `starting`. It never fails the run. + +When a container is running but Docker could not launch its health check, it is judged from the +host instead of failing. This applies only when the container's last recorded probe has exit +code `-1` with an `OCI runtime exec failed ... unable to start container process` output, whatever +else the runtime reports (a cgroup or `setns` failure, for example); a probe timeout, a failing +probe command, a restarting container, and an image fault in the healthcheck command +(`exec: "": executable file not found in $PATH`, `exec: "": stat : no such file +or directory`, `exec : no such file or directory`, `exec : exec format error`, or +`permission denied` in either form) keep failing: + +| Container | Judged by | +| --------------------------------------------------- | --------------------------------------------------------------- | +| kong | `GET /`; any HTTP response counts as up | +| gotrue | `GET /auth/v1/health` through Kong, expecting 200 | +| storage | `GET /storage/v1/status` through Kong, expecting 200 | +| pg-meta | `GET /pg/health` through Kong, expecting 200 | +| logflare | `GET /analytics/v1/health` through Kong, expecting 200 | +| every other container, and all of them without Kong | accepted as soon as it is running; readiness is not verified | + +The gateway requests carry the same `apikey`/`Authorization` headers as the bucket-seeding +requests. Kong answers `404` on `/` because no route matches, which proves its proxy is up; +only a failed connection or the 10s request timeout (covering the response body too) counts as +not ready. If a gateway request keeps failing, the container reports `container is not ready: : ` (Kong: +`container is not ready: `) and the wait times out as usual. + +When at least one container needed this fallback, `start` prints one `WARNING:` line to stderr, +in every output format, after the health wait and before the success summary: +`Docker cannot run health checks inside containers on this host (OCI runtime exec failed).` +followed by `Readiness of was not verified.` (the containers accepted on `running` +alone) or `Readiness was checked from the host instead.` when every fallback was a gateway +request. `cli_stack_started` still fires on such a success. + +A not-ready reason names the last health-check probe Docker recorded: +` container is not ready: (last health check exit code : )`, with +the output's whitespace collapsed and capped at 300 characters, and the `: ` part +omitted when the output is empty. No probe on record leaves the reason as +`container is not ready: `. When a timed-out container's health check could not be +launched, the error's `suggestion` names those containers, says Docker could not run the check +(typically nested or sandboxed Docker), and gives `docker exec true` to confirm; it +is joined after the `exec format error` advice when both apply. + ### Storage bucket seeding (`seedBucketsRun`) Runs only when `isFreshVolume && Storage started`, after the bulk @@ -218,7 +283,7 @@ code is surfaced on failure. | Code | Condition | | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `0` | success — every started container passed its health check | +| `0` | success — every started container passed its health check, or was accepted through the exec-failure fallback with a stderr `WARNING:` (see "Readiness gating") | | `0` | the stack was already running — shows status instead of restarting | | `0` | `--ignore-health-check` set and one or more containers timed out — the failure is printed and swallowed, no rollback | | `1` | `--ignore-health-check` set, the fresh-volume/Storage-healthy recheck-and-seed path ran (see "Storage bucket seeding"), and that seed itself failed — rolls back despite the flag | @@ -230,8 +295,8 @@ code is surfaced on failure. | `1` | image pull exhausted across every registry candidate, or the Docker daemon becomes unreachable during the pre-pull — even with `--ignore-health-check` (intentional divergence from the old Go CLI's exit-0 swallow quirk; see the CLI-1987 note under "Notes") | | `1` | Studio is enabled and `/supabase/snippets/` cannot be created (a file is in the way, or the workdir is not writable) — fails before any network or container is created | | `1` | network, volume, container create, or container start failure (including a port conflict) — rolls back everything created so far | -| `1` | health check timeout **without** `--ignore-health-check` — rolls back | -| `1` | Postgres itself fails to start or its own health wait times out, **without** `--ignore-health-check` — rolls back | +| `1` | health check timeout **without** `--ignore-health-check` (including a container whose exec-failure fallback request keeps failing) — rolls back | +| `1` | Postgres itself fails to start or its own readiness wait (inspect + host connect) times out, **without** `--ignore-health-check` — rolls back | | `0` | `--ignore-health-check` set and Postgres's own health wait times out — the failure is printed and swallowed, no rollback; no OTHER service is ever created (Postgres's failure is returned before any other bring-up step runs), but the command still prints "Started..." + the (config-derived) status table | | `1` | fresh-volume DB setup failure (schema SQL / one-shot migrate job / vault upsert / roles seed / migration-apply) — rolls back | | `1` | fresh-volume bucket-seeding failure — rolls back | @@ -277,7 +342,7 @@ output modes. invalid values and listing the 13 valid ones — the command still proceeds. - stderr: already-running banner (`supabase start` in aqua) **or** the bring-up sequence: `Starting database...` (fresh volume) / `Starting database from backup...` (existing - volume) → Postgres create+start+health-wait → `Starting containers...` → (image + volume) → Postgres create+start+readiness wait → `Starting containers...` → (image pre-pull) → per-container create+start → `Waiting for health checks...` → `Started supabase local development setup.` - stderr (conditional, fresh-volume bucket seeding): `Creating bucket: ` per @@ -286,6 +351,8 @@ supabase local development setup.` buckets to prune.` for a bucket left in place. These seeding lines use the raw writer, so they appear in every output mode, not only text. No confirmation question is printed and no stdin line is read. +- stderr (conditional, Docker cannot run health checks on this host): one `WARNING:` line; see + "Readiness gating". Written to stderr in the json and stream-json formats too. - stderr (conditional, health-check timeout): per unhealthy container, a ` container logs:` header and that container's `docker logs` output, then one `: ` line each. Containers are named `supabase__` @@ -310,7 +377,8 @@ buckets to prune.` for a bucket left in place. These seeding lines use the raw w A single JSON object (or a `result` NDJSON event) carrying the same value shape `supabase status --output json` produces. All the progress/warning/banner/security-notice -text above is suppressed in these modes — stdout stays payload-only. On a health-check +text above is suppressed in these modes — stdout stays payload-only — except the exec-failure +`WARNING:` (see "Readiness gating"), which stays on stderr. On a health-check timeout the error payload carries the advice above as a discrete `error.suggestion` string alongside `error.message`, so a caller can surface it without re-parsing the message. It is prose, not structured data. @@ -365,8 +433,11 @@ prose, not structured data. "unhealthy service", but a user reading only `--help` may still expect exit 0 here. - `--preview` is a hidden, parsed-but-inert flag, inherited from the old Go CLI (never read by its own `start.Run`). -- The already-running check uses `docker container inspect` on the Postgres container, - not a health check. For a verified +- The already-running check uses `docker container inspect` on the Postgres container and, + unless `--ignore-health-check` is set, requires its Docker health to be `healthy` or absent; + otherwise it fails with ` container is not ready: ...` (reason format in "Readiness + gating"). When Docker could not launch the health check, it accepts the container and prints + the same `WARNING:` naming `supabase_db_` as unverified. For a verified stopped container outside Bitbucket Pipelines, `start` removes all current-project containers — including running siblings — and unused networks, preserves named volumes, and continues normal startup. After container removal succeeds, it deletes diff --git a/apps/cli/src/commands/start/start.handler.ts b/apps/cli/src/commands/start/start.handler.ts index cf6764dd03..8a8ef7727d 100644 --- a/apps/cli/src/commands/start/start.handler.ts +++ b/apps/cli/src/commands/start/start.handler.ts @@ -62,6 +62,8 @@ import { import { resolveDockerNetworkMode } from "../../shared/functions/functions-docker.ts"; import { viperEnvStringWithProjectFallback } from "../../command-internal/viper-env.ts"; import { + formatNotReadyReason, + healthCheckCannotExec, inspectContainerState, listContainersByLabel, type ContainerIdName, @@ -150,7 +152,10 @@ import { } from "../../command-internal/db-bootstrap/container-lifecycle.ts"; import { ensureImagesCached } from "../../command-internal/db-bootstrap/image-prepull.ts"; import { + awaitDockerHealthSettled, + healthCheckExecUnavailableWarning, waitForHealthyServices, + type ExecFallbackProbe, type HealthCheckPostgrestGateway, type HealthCheckTimeoutError, } from "../../command-internal/db-bootstrap/health-check.ts"; @@ -675,9 +680,13 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { }); } if (state.health !== undefined && state.health !== "healthy") { - return yield* new StatusDbNotReadyError({ - message: `${dbContainerId} container is not ready: ${state.health}`, - }); + if (!healthCheckCannotExec(state)) { + return yield* new StatusDbNotReadyError({ + message: `${dbContainerId} ${formatNotReadyReason(state)}`, + }); + } + yield* Effect.annotateCurrentSpan("db.health_exec_unavailable", true); + yield* output.raw(healthCheckExecUnavailableWarning([dbContainerId]), "stderr"); } } @@ -1561,6 +1570,7 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { // `docker create` returns) so an unhealthy container reports as `supabase_auth_demo` // rather than 64 hex characters, and the watch list stays in sync with its images. const started = new Map(); + const execFallbacks = new Map(); let postgrestGateway: HealthCheckPostgrestGateway | undefined; let edgeRuntimeGateway: HealthCheckPostgrestGateway | undefined; let storageContainerId: string | undefined; @@ -1676,6 +1686,16 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { yield* createContainer(spawner, spec, startOpts); if (excludeFromHealthWatch !== true) { started.set(spec.containerName, spec.image); + // Routed services fall back to `running` when Kong is excluded. + const gateway = { apiExternalUrl: values.apiUrl, secretKey: values.secretKey }; + execFallbacks.set( + spec.containerName, + entry.gatewayReachable === true + ? { kind: "gateway-reachable", gateway } + : entry.gatewayReadyPath !== undefined && gates.kong + ? { kind: "gateway", gateway, path: entry.gatewayReadyPath } + : { kind: "running" }, + ); } if (entry.service === "postgrest") { postgrestGateway = { @@ -1695,6 +1715,7 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { postgrestGateway, edgeRuntimeGateway, storageContainerId, + execFallbacks, }; }).pipe( // The rollback's `NoBackupVolume` value is `true` only when this run's Postgres volume was @@ -1750,7 +1771,8 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { // Only reached when Postgres itself became healthy — the `postgresUnhealthyIgnored` // short-circuit above skips this entire block and falls through to the tail below instead. if (bringUpResult.kind === "started") { - const { started, postgrestGateway, edgeRuntimeGateway, storageContainerId } = bringUpResult; + const { started, postgrestGateway, edgeRuntimeGateway, storageContainerId, execFallbacks } = + bringUpResult; // Wraps steps 9-11 below in the same `Effect.onError` rollback `bringUp`'s own pipe uses // above, so a SIGINT/SIGTERM landing anywhere in this tail also rolls back. Per-step manual @@ -1817,6 +1839,7 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { postgrest: postgrestGateway, edgeRuntime: edgeRuntimeGateway, images: started, + execFallbacks, }), ).pipe(Effect.result); if (Result.isFailure(healthResult)) { @@ -1834,6 +1857,7 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { const storageHealthResult = yield* withLocalKongCa( waitForHealthyServices(spawner, [storageContainerId], { images: started, + execFallbacks, }), ).pipe(Effect.result); if (Result.isSuccess(storageHealthResult)) { @@ -1864,6 +1888,15 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { } } + if (Result.isSuccess(healthResult) && healthResult.success.execUnavailable.length > 0) { + yield* output.raw( + healthCheckExecUnavailableWarning(healthResult.success.readinessAssumed), + "stderr", + ); + } + + yield* awaitDockerHealthSettled(spawner, dbContainerId); + // 10. Storage-bucket seeding, gated on a freshly created volume and Storage having // started. Reached only on a genuine health-check success — mutually exclusive with the // narrower storage-only recheck-and-seed path above, which only runs when this guard is diff --git a/apps/cli/src/commands/start/start.integration.test.ts b/apps/cli/src/commands/start/start.integration.test.ts index c862f8e064..48a6992f73 100644 --- a/apps/cli/src/commands/start/start.integration.test.ts +++ b/apps/cli/src/commands/start/start.integration.test.ts @@ -4,6 +4,7 @@ import { BunServices } from "@effect/platform-bun"; import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest"; import { Cause, + Clock, Deferred, Effect, Exit, @@ -21,6 +22,7 @@ import { import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as TestClock from "effect/testing/TestClock"; import { assert, vi } from "vitest"; import { @@ -41,6 +43,11 @@ import { withEmptyConfigEnv, withEnvVar, } from "../../../tests/helpers/command-mocks.ts"; +import { + EXEC_FAILED_STATE, + PROBE_TIMEOUT_OUTPUT, + inspectedState, +} from "../../../tests/helpers/docker-health.ts"; import { assertPermissionDrift } from "../../../tests/helpers/permission-drift.ts"; import { unusedStackServices } from "../../../tests/helpers/unused-stack.ts"; import { CliArgs } from "../../shared/cli/cli-args.service.ts"; @@ -55,6 +62,7 @@ import { CommandPlatformApiFactory } from "../../auth/command-platform-api-facto import { serviceContainerIds, serviceContainerName } from "../../command-internal/docker-ids.ts"; import { bindMountSpecSource } from "../../command-internal/docker-bind-classify.ts"; import { HealthCheckTimeoutSeconds } from "../../command-internal/db-bootstrap/health-check.ts"; +import { DbConnectError } from "../../command-internal/db-connection.errors.ts"; import { DbConnection, type DbSession } from "../../command-internal/db-connection.service.ts"; import { dockerRunLayer } from "../../command-internal/docker-run.layer.ts"; import { START_EXCLUDABLE_KEYS } from "./start.exclude.ts"; @@ -290,6 +298,75 @@ function defaultRoute(opts: { readonly neverHealthy?: ReadonlySet } = {} }; } +const refusedDbConnect = () => + Effect.fail(new DbConnectError({ message: "failed to connect: connection refused" })); + +/** Docker cannot launch any HEALTHCHECK on this host, Kong's included. */ +function execBrokenHostRoute(base: (args: ReadonlyArray) => RouteResult = defaultRoute()) { + return (args: ReadonlyArray): RouteResult => { + const result = base(args); + if (args[0] === "container" && args[1] === "inspect" && result.stdout?.[0] === HEALTHY_STATE) { + return { stdout: [EXEC_FAILED_STATE] }; + } + return result; + }; +} + +/** + * A db whose Docker health reads `starting` until `healthyAtSeconds` of test-clock time. + * `settleStarted` fires on the first db inspect after the host connect probe succeeded; + * `settled` fires when Docker first reports healthy. + */ +function dbHealthVerdictAt(healthyAtSeconds: number) { + const base = defaultRoute(); + const settleStarted = Deferred.makeUnsafe(); + const settled = Deferred.makeUnsafe(); + let connected = false; + const dbConnect = () => { + connected = true; + return Effect.succeed(fakeDbSession().session); + }; + const route = (args: ReadonlyArray): RouteResult | Effect.Effect => { + const result = base(args); + const isDbInspect = + args[0] === "container" && + args[1] === "inspect" && + (args[2] ?? "").includes("_db_") && + result.stdout?.[0] === HEALTHY_STATE; + if (!isDbInspect) return result; + if (connected) Deferred.doneUnsafe(settleStarted, Effect.void); + return Effect.map(Clock.currentTimeMillis, (now) => { + if (now < healthyAtSeconds * 1000) return { stdout: [STARTING_STATE] }; + Deferred.doneUnsafe(settled, Effect.void); + return result; + }); + }; + return { route, dbConnect, settleStarted, settled }; +} + +/** Answers every Kong-gateway request with the status scripted for its path (200 otherwise), recording each. */ +function mockGatewayHttpClient(statusByPath: Readonly> = {}) { + const requests: Array<{ + readonly method: string; + readonly path: string; + readonly headers: Readonly>; + }> = []; + const layer = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + const { pathname } = new URL(request.url); + requests.push({ method: request.method, path: pathname, headers: { ...request.headers } }); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response("{}", { status: statusByPath[pathname] ?? 200 }), + ), + ); + }), + ); + return { layer, requests }; +} + /** A `HttpClient` that always answers 200 — the default config's PostgREST/Kong readiness probe. */ const alwaysReadyHttpClientLayer = Layer.succeed( HttpClient.HttpClient, @@ -493,6 +570,8 @@ interface SetupOpts { readonly networkId?: Option.Option; /** `--experimental`/`SUPABASE_EXPERIMENTAL`. Defaults to `false`. */ readonly experimental?: boolean; + /** Replaces the `DbConnection.connect` behind the Postgres readiness probe. Defaults to succeeding. */ + readonly dbConnect?: (typeof DbConnection)["Service"]["connect"]; } const setup = Effect.fnUntraced(function* (opts: SetupOpts = {}) { @@ -521,10 +600,11 @@ const setup = Effect.fnUntraced(function* (opts: SetupOpts = {}) { analytics.layer, child.layer, opts.httpClientLayer ?? alwaysReadyHttpClientLayer, - // Only exercised by a fresh-volume scenario; every other scenario's default route never - // reaches `startSetupLocalDatabase`/`seedBucketsRun`, but both are part of `start`'s - // aggregate Effect type, so every scenario still needs this satisfied. - Layer.succeed(DbConnection, { connect: () => Effect.succeed(dbSession.session) }), + // Backs the Postgres readiness probe on every scenario, and `startSetupLocalDatabase`/ + // `seedBucketsRun` on fresh-volume ones. + Layer.succeed(DbConnection, { + connect: opts.dbConnect ?? (() => Effect.succeed(dbSession.session)), + }), // `Layer.mergeAll` never cross-wires sibling requirements, so `dockerRunLayer` needs // `ChildProcessSpawner`/`ProcessControl` provided to it explicitly, not just present // elsewhere in this merge. @@ -3137,22 +3217,19 @@ content_path = "./supabase/templates/custom_notice.html" // rollback being wired via `Effect.onError` (not `Effect.tapError`, which never sees a // pure interrupt's `Cause`). // - // Marking `db` never-healthy keeps `bringUp`'s Postgres health-check wait suspended in - // its retry loop, rather than the whole synchronous mock bring-up completing before - // this test's probe wait is even scheduled — which would make `Fiber.interrupt` a - // no-op on an already-succeeded fiber. - const neverHealthy = new Set(); - const route = defaultRoute({ neverHealthy }); + // A refused Postgres connect keeps `bringUp`'s readiness wait suspended in its retry + // loop, rather than the whole synchronous mock bring-up completing before this test's + // probe wait is even scheduled — which would make `Fiber.interrupt` a no-op on an + // already-succeeded fiber. + const route = defaultRoute(); let dbContainerId: string | undefined; const dbProbed = yield* Deferred.make(); const { layer, child } = yield* setup({ + dbConnect: refusedDbConnect, route: (args) => { if (args[0] === "create") { const name = containerNameFromCreateArgs(args); - if (name.includes("_db_")) { - neverHealthy.add(name); - dbContainerId = name; - } + if (name.includes("_db_")) dbContainerId = name; } if ( dbContainerId !== undefined && @@ -3169,8 +3246,8 @@ content_path = "./supabase/templates/custom_notice.html" Effect.provide(layer), Effect.forkChild({ startImmediately: true }), ); - // Wait until the health check has actually probed the never-healthy `db` container, - // proving the fiber is suspended inside the retry loop, not merely past `create`. + // Wait until the readiness wait has actually inspected the `db` container, proving the + // fiber is suspended inside the retry loop, not merely past `create`. yield* Deferred.await(dbProbed); // `Fiber.interrupt` only resolves once the target fiber (and its finalizers, // including the `Effect.onError` rollback) has fully completed. @@ -3389,18 +3466,9 @@ content_path = "./supabase/templates/custom_notice.html" () => Effect.gen(function* () { // A zero `db.health_timeout` limits Postgres's wait to a single probe. - const neverHealthy = new Set(); - const base = defaultRoute({ neverHealthy }); - const route = (args: ReadonlyArray): RouteResult => { - if (args[0] === "create") { - const name = containerNameFromCreateArgs(args); - if (name.includes("_db_")) neverHealthy.add(name); - } - return base(args); - }; const { layer, child } = yield* setup({ configContents: 'project_id = "demo"\n[db]\nhealth_timeout = "0s"\n', - route, + dbConnect: refusedDbConnect, }); const exit = yield* Effect.exit(start(flags()).pipe(Effect.provide(layer))); @@ -3422,13 +3490,8 @@ content_path = "./supabase/templates/custom_notice.html" // `ignoreHealthCheck && isUnhealthyStartError(err)` downgrades uniformly to whatever the // run returns, including Postgres's own health-wait failure, which propagates before // any other service is even created. - const neverHealthy = new Set(); - const base = defaultRoute({ neverHealthy }); + const base = defaultRoute(); const route = (args: ReadonlyArray): RouteResult => { - if (args[0] === "create") { - const name = containerNameFromCreateArgs(args); - if (name.includes("_db_")) neverHealthy.add(name); - } // Postgres's own health wait builds its `images` map separately from the bulk one, // so this scripts the marker here too. if (args[0] === "logs" && (args[1] ?? "").includes("_db_")) { @@ -3438,6 +3501,7 @@ content_path = "./supabase/templates/custom_notice.html" }; const { layer, out, child, analytics } = yield* setup({ configContents: 'project_id = "demo"\n[db]\nhealth_timeout = "0s"\n', + dbConnect: refusedDbConnect, route, }); @@ -3736,6 +3800,260 @@ content_path = "./supabase/templates/custom_notice.html" ); }); + describe("Docker's first health verdict on the database", () => { + const runWithClock = ( + effect: Effect.Effect, + db: ReturnType, + ) => + Effect.gen(function* () { + const fiber = yield* effect.pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.raceFirst(Deferred.await(db.settleStarted), Fiber.await(fiber)); + // Small steps: each settle poll needs a few scheduler turns before it registers its next sleep. + for (let step = 0; step < 160 && fiber.pollUnsafe() === undefined; step++) { + if (yield* Deferred.isDone(db.settled)) break; + yield* TestClock.adjust("100 millis"); + } + return yield* Fiber.await(fiber); + }); + + it.effect( + "start waits for it, so a start right afterwards finds the database ready instead of starting", + () => + Effect.gen(function* () { + const db = dbHealthVerdictAt(5); + const { layer, out } = yield* setup({ route: db.route, dbConnect: db.dbConnect }); + + const first = yield* runWithClock(start(flags()).pipe(Effect.provide(layer)), db); + yield* start(flags()).pipe(Effect.provide(layer)); + + expect(Exit.isSuccess(first)).toBe(true); + expect(out.stderrText).toContain("local development setup is running."); + }).pipe(Effect.provide(BunServices.layer)), + ); + + it.effect("start still completes without rolling back when Docker never settles", () => + Effect.gen(function* () { + const db = dbHealthVerdictAt(Number.POSITIVE_INFINITY); + const { layer, child } = yield* setup({ route: db.route, dbConnect: db.dbConnect }); + + const exit = yield* runWithClock(start(flags()).pipe(Effect.provide(layer)), db); + + expect(Exit.isSuccess(exit)).toBe(true); + expect(rollbackWasAttempted(child.spawned)).toBe(false); + }).pipe(Effect.provide(BunServices.layer)), + ); + }); + + describe("a host where Docker cannot exec health checks", () => { + const projectId = "demo"; + const kongRouted = ["auth", "storage", "pg_meta", "analytics"]; + const gatewayVerified = ["kong", ...kongRouted]; + const readinessAssumed = ["realtime", "studio", "inbucket", "vector"]; + + for (const format of ["text", "json"] as const) { + it.effect( + `starts with one stderr warning naming only unverified services in ${format} mode`, + () => + Effect.gen(function* () { + const { layer, out, analytics } = yield* setup({ + format, + route: execBrokenHostRoute(), + httpClientLayer: mockGatewayHttpClient().layer, + }); + + yield* start(flags()).pipe(Effect.provide(layer)); + + const warnings = out.stderrText + .split("\n") + .filter((line) => line.includes("Docker cannot run health checks")); + expect(warnings).toHaveLength(1); + for (const service of readinessAssumed) { + expect(warnings[0]).toContain(serviceContainerName(service, projectId)); + } + for (const service of gatewayVerified) { + expect(warnings[0]).not.toContain(serviceContainerName(service, projectId)); + } + expect(out.stdoutText).not.toContain("Docker cannot run health checks"); + expect(analytics.captured).toContainEqual( + expect.objectContaining({ event: "cli_stack_started" }), + ); + if (format === "json") { + expect(out.messages.find((m) => m.type === "success")?.data).toMatchObject({ + DB_URL: expect.any(String), + }); + } + }).pipe(Effect.provide(BunServices.layer)), + ); + } + + it.effect( + "verifies Kong and gateway-routed services with an authenticated GET, accepting any status from Kong", + () => + Effect.gen(function* () { + const gateway = mockGatewayHttpClient({ "/": 404 }); + const { layer } = yield* setup({ + route: execBrokenHostRoute(), + httpClientLayer: gateway.layer, + }); + + yield* start(flags()).pipe(Effect.provide(layer)); + + const gets = gateway.requests.filter((request) => request.method === "GET"); + expect(gets.map((request) => request.path).toSorted()).toEqual([ + "/", + "/analytics/v1/health", + "/auth/v1/health", + "/pg/health", + "/storage/v1/status", + ]); + for (const request of gets) { + expect(request.headers["apikey"]).toEqual(expect.any(String)); + } + }).pipe(Effect.provide(BunServices.layer)), + ); + + it.effect( + "with Kong excluded, accepts Kong-routed services as running and lists them as unverified", + () => + Effect.gen(function* () { + const unroutable = { + "/auth/v1/health": 503, + "/storage/v1/status": 503, + "/pg/health": 503, + "/analytics/v1/health": 503, + }; + const { layer, out } = yield* setup({ + route: execBrokenHostRoute(), + httpClientLayer: mockGatewayHttpClient(unroutable).layer, + }); + + yield* start(flags({ exclude: ["kong"] })).pipe(Effect.provide(layer)); + + const warnings = out.stderrText + .split("\n") + .filter((line) => line.includes("Docker cannot run health checks")); + expect(warnings).toHaveLength(1); + for (const service of [...kongRouted, ...readinessAssumed]) { + expect(warnings[0]).toContain(serviceContainerName(service, projectId)); + } + expect(warnings[0]).not.toContain(serviceContainerName("kong", projectId)); + }).pipe(Effect.provide(BunServices.layer)), + ); + + it.live( + "fails with the gateway status, the exec suggestion and a rollback when Storage is not routable", + () => + Effect.gen(function* () { + const { layer, out, child } = yield* setup({ + route: execBrokenHostRoute(), + httpClientLayer: mockGatewayHttpClient({ "/storage/v1/status": 503 }).layer, + }); + + const error = yield* start(flags()).pipe(Effect.provide(layer), Effect.flip); + + const storage = serviceContainerName("storage", projectId); + expect(error).toMatchObject({ + _tag: "HealthCheckTimeoutError", + message: `${storage} container is not ready: /storage/v1/status: unexpected status 503`, + suggestion: expect.stringContaining(`Check with: docker exec ${storage} true`), + }); + expect(out.stderrText).not.toContain("Docker cannot run health checks"); + expect(out.stderrText).not.toContain("Started"); + expect(rollbackWasAttempted(child.spawned)).toBe(true); + }).pipe( + Effect.provideService(HealthCheckTimeoutSeconds, 0), + Effect.provide(BunServices.layer), + ), + 10_000, + ); + + it.live( + "does not accept a Docker probe timeout as an exec failure", + () => + Effect.gen(function* () { + const timedOut = inspectedState({ + health: "unhealthy", + probes: [{ exitCode: -1, output: PROBE_TIMEOUT_OUTPUT }], + }); + const base = defaultRoute(); + const { layer } = yield* setup({ + route: (args) => { + const result = base(args); + return args[0] === "container" && + args[1] === "inspect" && + (args[2] ?? "").includes("_studio_") && + result.stdout?.[0] === HEALTHY_STATE + ? { stdout: [timedOut] } + : result; + }, + }); + + const error = yield* start(flags()).pipe(Effect.provide(layer), Effect.flip); + + expect(error).toMatchObject({ + _tag: "HealthCheckTimeoutError", + message: `${serviceContainerName("studio", projectId)} container is not ready: unhealthy (last health check exit code -1: Health check exceeded timeout (2s))`, + }); + expect(error).not.toHaveProperty("suggestion"); + }).pipe( + Effect.provideService(HealthCheckTimeoutSeconds, 0), + Effect.provide(BunServices.layer), + ), + 10_000, + ); + + it.effect( + "already running: accepts a db whose health check cannot exec, with a stderr warning", + () => + Effect.gen(function* () { + const { layer, out, child } = yield* setup({ + route: (args) => { + if (args[0] === "container" && args[1] === "inspect") { + return { stdout: [EXEC_FAILED_STATE] }; + } + if (args[0] === "ps") return { stdout: [] }; + return { exitCode: 0 }; + }, + }); + + yield* start(flags()).pipe(Effect.provide(layer)); + + expect(out.stderrText).toContain("WARNING:"); + expect(out.stderrText).toContain("Readiness of supabase_db_demo was not verified."); + expect(child.spawned.some((s) => s.args[0] === "create")).toBe(false); + }).pipe(Effect.provide(BunServices.layer)), + ); + + it.effect("already running: still rejects a db whose health check ran and failed", () => + Effect.gen(function* () { + const { layer, out } = yield* setup({ + route: (args) => { + if (args[0] === "container" && args[1] === "inspect") { + return { + stdout: [ + inspectedState({ + health: "unhealthy", + probes: [{ exitCode: 1, output: "pg_isready: no response" }], + }), + ], + }; + } + return { exitCode: 0 }; + }, + }); + + const error = yield* start(flags()).pipe(Effect.provide(layer), Effect.flip); + + expect(error).toMatchObject({ + _tag: "StatusDbNotReadyError", + message: + "supabase_db_demo container is not ready: unhealthy (last health check exit code 1: pg_isready: no response)", + }); + expect(out.stderrText).not.toContain("Docker cannot run health checks"); + }).pipe(Effect.provide(BunServices.layer)), + ); + }); + describe("--network-id", () => { it.effect("overrides the generated network name and every container's --network flag", () => Effect.gen(function* () { @@ -5133,16 +5451,7 @@ content_path = "./supabase/templates/custom_notice.html" "SUPABASE_DB_HEALTH_TIMEOUT", "0s", Effect.gen(function* () { - const neverHealthy = new Set(); - const base = defaultRoute({ neverHealthy }); - const route = (args: ReadonlyArray): RouteResult => { - if (args[0] === "create") { - const name = containerNameFromCreateArgs(args); - if (name.includes("_db_")) neverHealthy.add(name); - } - return base(args); - }; - const { layer, child } = yield* setup({ route }); + const { layer, child } = yield* setup({ dbConnect: refusedDbConnect }); const exit = yield* Effect.exit(start(flags()).pipe(Effect.provide(layer))); expect(Exit.isFailure(exit)).toBe(true); diff --git a/apps/cli/src/commands/start/start.services.ts b/apps/cli/src/commands/start/start.services.ts index cf27000ec0..6f117303e4 100644 --- a/apps/cli/src/commands/start/start.services.ts +++ b/apps/cli/src/commands/start/start.services.ts @@ -22,6 +22,10 @@ export interface StartServiceMeta { * Logflare; Studio waits on pg-meta). Not a full dependency graph, just a sequencing hint. */ readonly dependsOn?: ReadonlyArray; + /** The Kong route used to verify readiness when Docker cannot exec the health check. */ + readonly gatewayReadyPath?: string; + /** The service is the gateway itself: any HTTP response from it proves it is up. */ + readonly gatewayReachable?: true; } export interface StartServiceEntry extends ServiceCatalogEntry, StartServiceMeta {} @@ -32,7 +36,14 @@ export interface StartServiceEntry extends ServiceCatalogEntry, StartServiceMeta */ const START_SERVICE_META_BY_SERVICE: ReadonlyMap = new Map([ ["postgres", { imageConfigField: "db.image", enabledGate: "always" }], - ["logflare", { imageConfigField: "analytics.image", enabledGate: "analytics.enabled" }], + [ + "logflare", + { + imageConfigField: "analytics.image", + enabledGate: "analytics.enabled", + gatewayReadyPath: "/analytics/v1/health", + }, + ], [ "vector", { @@ -41,12 +52,26 @@ const START_SERVICE_META_BY_SERVICE: ReadonlyMap = new dependsOn: ["logflare"], }, ], - ["kong", { imageConfigField: "api.kong_image", enabledGate: "none" }], - ["gotrue", { imageConfigField: "auth.image", enabledGate: "auth.enabled" }], + ["kong", { imageConfigField: "api.kong_image", enabledGate: "none", gatewayReachable: true }], + [ + "gotrue", + { + imageConfigField: "auth.image", + enabledGate: "auth.enabled", + gatewayReadyPath: "/auth/v1/health", + }, + ], ["mailpit", { imageConfigField: "local_smtp.image", enabledGate: "local_smtp.enabled" }], ["realtime", { imageConfigField: "realtime.image", enabledGate: "realtime.enabled" }], ["postgrest", { imageConfigField: "api.image", enabledGate: "api.enabled" }], - ["storage", { imageConfigField: "storage.image", enabledGate: "storage.enabled" }], + [ + "storage", + { + imageConfigField: "storage.image", + enabledGate: "storage.enabled", + gatewayReadyPath: "/storage/v1/status", + }, + ], [ "imgproxy", { @@ -56,7 +81,14 @@ const START_SERVICE_META_BY_SERVICE: ReadonlyMap = new }, ], ["edgeRuntime", { imageConfigField: "edge_runtime.image", enabledGate: "edge_runtime.enabled" }], - ["pgMeta", { imageConfigField: "studio.pgmeta_image", enabledGate: "studio.enabled" }], + [ + "pgMeta", + { + imageConfigField: "studio.pgmeta_image", + enabledGate: "studio.enabled", + gatewayReadyPath: "/pg/health", + }, + ], [ "studio", { @@ -84,5 +116,7 @@ export const START_SERVICES: ReadonlyArray = SERVICE_CATALOG. imageConfigField: meta?.imageConfigField ?? "", enabledGate: meta?.enabledGate ?? "", dependsOn: meta?.dependsOn, + gatewayReadyPath: meta?.gatewayReadyPath, + gatewayReachable: meta?.gatewayReachable, }; }); diff --git a/apps/cli/src/commands/start/start.services.unit.test.ts b/apps/cli/src/commands/start/start.services.unit.test.ts index f49310fa17..88b716e244 100644 --- a/apps/cli/src/commands/start/start.services.unit.test.ts +++ b/apps/cli/src/commands/start/start.services.unit.test.ts @@ -110,6 +110,7 @@ describe("startServiceMeta", () => { imageConfigField: entry?.imageConfigField, enabledGate: entry?.enabledGate, dependsOn: entry?.dependsOn, + gatewayReadyPath: entry?.gatewayReadyPath, }); }); diff --git a/apps/cli/src/commands/status/SIDE_EFFECTS.md b/apps/cli/src/commands/status/SIDE_EFFECTS.md index f6267ac51e..c72746faae 100644 --- a/apps/cli/src/commands/status/SIDE_EFFECTS.md +++ b/apps/cli/src/commands/status/SIDE_EFFECTS.md @@ -90,7 +90,8 @@ convention used elsewhere in config loading, and take precedence over the corres | `1` | listing running containers failed (Docker daemon unreachable, etc.) | | `1` | the db container inspect call failed (including "not found") — health assertion, skipped by `--ignore-health-check` above | | `1` | the db container is present but not in the `running` state — health assertion, skipped by `--ignore-health-check` above | -| `1` | the db container is running but its Docker health check isn't `healthy` — health assertion, skipped by `--ignore-health-check` above | +| `1` | the db container is running but its Docker health check isn't `healthy` — health assertion, skipped by `--ignore-health-check` above; the message ends with the last recorded probe, `(last health check exit code : )`, when Docker has one | +| `0` | the db container is running but Docker could not launch its health check (last probe exit code `-1`, `OCI runtime exec failed`, as on nested or sandboxed Docker) — status renders, with a stderr `WARNING:` | | `1` | `auth.jwt_secret` is configured but shorter than 16 characters (rejected at config-load time) | | `1` | `auth.signing_keys_path` is configured but the file is missing/malformed, or its first key's algorithm is not `RS256`/`ES256` | | `1` | `api.enabled` and `api.tls.enabled` are true and only one of `api.tls.cert_path`/`key_path` is set (rejected at config-load time) | @@ -213,6 +214,10 @@ headers); colors are stripped on non-TTY/piped output. bracketed list, e.g. `[supabase_storage_test supabase_studio_test]`) whenever one of the 13 expected service containers isn't in the running set. +When Docker could not launch the db container's health check, stderr gets `WARNING: Docker cannot +run health checks inside containers on this host (OCI runtime exec failed). Readiness of + was not verified.` in every output format, and the status still renders on stdout. + Whenever a machine format (`-o env|json|toml|yaml`, or `--output-format json|stream-json`) emits the deprecated `INBUCKET_URL` field, stderr gets `WARN: INBUCKET_URL is deprecated and will be removed in v3, use MAILPIT_URL instead.` (both diff --git a/apps/cli/src/commands/status/status.handler.ts b/apps/cli/src/commands/status/status.handler.ts index 57d79c79f9..33e56abbf3 100644 --- a/apps/cli/src/commands/status/status.handler.ts +++ b/apps/cli/src/commands/status/status.handler.ts @@ -12,7 +12,10 @@ import { serviceContainerIds, localDbContainerId, } from "../../command-internal/docker-ids.ts"; +import { healthCheckExecUnavailableWarning } from "../../command-internal/db-bootstrap/health-check.ts"; import { + formatNotReadyReason, + healthCheckCannotExec, inspectContainerState, listContainersByLabel, } from "../../command-internal/docker-lifecycle.ts"; @@ -183,9 +186,13 @@ export const status = Effect.fn("status")(function* (flags: StatusFlags) { }); } if (state.health !== undefined && state.health !== "healthy") { - return yield* new StatusDbNotReadyError({ - message: `${dbContainerId} container is not ready: ${state.health}`, - }); + if (!healthCheckCannotExec(state)) { + return yield* new StatusDbNotReadyError({ + message: `${dbContainerId} ${formatNotReadyReason(state)}`, + }); + } + yield* Effect.annotateCurrentSpan("db.health_exec_unavailable", true); + yield* output.raw(healthCheckExecUnavailableWarning([dbContainerId]), "stderr"); } } diff --git a/apps/cli/src/commands/status/status.integration.test.ts b/apps/cli/src/commands/status/status.integration.test.ts index c84f8b79e7..7f657b3a3f 100644 --- a/apps/cli/src/commands/status/status.integration.test.ts +++ b/apps/cli/src/commands/status/status.integration.test.ts @@ -39,6 +39,11 @@ import { useTempWorkdir, withEnvVar, } from "../../../tests/helpers/command-mocks.ts"; +import { + EXEC_FAILED_STATE, + PROBE_TIMEOUT_OUTPUT, + inspectedState, +} from "../../../tests/helpers/docker-health.ts"; import { assertPermissionDrift } from "../../../tests/helpers/permission-drift.ts"; import type { CommandPlatformApiFactoryError } from "../../auth/command-platform-api-factory.service.ts"; import { CommandPlatformApiFactory } from "../../auth/command-platform-api-factory.service.ts"; @@ -1031,6 +1036,39 @@ content_path = "./supabase/templates/password_changed_notification.html" }).pipe(Effect.provide(layer)); }); + it.effect("reports a db whose health check cannot exec as running, with a stderr warning", () => { + const { layer, out } = setup({ route: defaultRoute({ dbInspectStdout: EXEC_FAILED_STATE }) }); + return Effect.gen(function* () { + yield* writeConfig(); + yield* status(flags()); + expect(out.stderrText).toContain("WARNING:"); + expect(out.stderrText).toContain("Readiness of supabase_db_demo was not verified."); + expect(out.stdoutText).toContain("⛁ Database"); + expect(out.stdoutText).not.toContain("WARNING"); + }).pipe(Effect.provide(layer)); + }); + + it.effect("still fails a db whose last health probe timed out, naming the probe", () => { + const { layer, out } = setup({ + route: defaultRoute({ + dbInspectStdout: inspectedState({ + health: "unhealthy", + probes: [{ exitCode: -1, output: PROBE_TIMEOUT_OUTPUT }], + }), + }), + }); + return Effect.gen(function* () { + yield* writeConfig(); + const error = yield* status(flags()).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "StatusDbNotReadyError", + message: + "supabase_db_demo container is not ready: unhealthy (last health check exit code -1: Health check exceeded timeout (2s))", + }); + expect(out.stderrText).not.toContain("Docker cannot run health checks"); + }).pipe(Effect.provide(layer)); + }); + it.effect("fails when db inspect errors for a reason other than not-found", () => { const { layer } = setup({ route: defaultRoute({ dbInspectExitCode: 1, dbInspectStderr: ["permission denied"] }), diff --git a/apps/cli/tests/helpers/command-mocks.ts b/apps/cli/tests/helpers/command-mocks.ts index def4013944..4181c6f7c6 100644 --- a/apps/cli/tests/helpers/command-mocks.ts +++ b/apps/cli/tests/helpers/command-mocks.ts @@ -80,6 +80,7 @@ import { mockTty, processEnvLayer, } from "./mocks.ts"; +import { EXEC_FAILED_STATE } from "./docker-health.ts"; const hostPath = Effect.runSync(Path.Path.pipe(Effect.provide(BunPath.layer))); @@ -931,27 +932,15 @@ export const FAKE_SHADOW_CONTAINER_ID = "abc123456789shadow0".padEnd(64, "0").sl /** Inspect JSON for a healthy container. */ const SHADOW_HEALTHY_STATE = '{"Running":true,"Status":"running","Health":{"Status":"healthy"}}'; -/** - * A real (Docker-valid) "still starting" state, not `Effect.never`, so - * {@link waitForHealthyServices}'s retry loop genuinely retries on its real 1-second - * `Schedule.spaced` backoff instead of hanging on a single probe forever — a fiber interrupted - * mid-retry must be observed actually suspended inside the retry loop, not merely past the - * initial `create` call. - */ -const SHADOW_STARTING_STATE = '{"Running":true,"Status":"running","Health":{"Status":"starting"}}'; - /** * Fakes every `docker`/`podman` subprocess call the native shadow-provisioning path issues: * `buildLocalDbContainerInputs`'s image-cache check, `createShadowDatabase`'s network-create + - * container create/start, `waitForHealthyServices`'s container inspect, and + * container create/start, `waitForPostgresReady`'s container inspect, and * `removeShadowDatabase`'s cleanup. Both callers only ever create one (shadow) container, never * named. * - * `neverHealthy` (default `false`) makes every `container inspect` report `"starting"` instead of - * `"healthy"`, for interrupt-during-health-wait coverage: with the default healthy-immediately - * response, a forked fiber can run the entire shadow-provisioning sequence to completion - * synchronously before a test's own polling loop is even scheduled, making `Fiber.interrupt` a - * no-op on an already-finished fiber. + * `execFailedHealth` (default `false`) makes every `container inspect` report the health state of a + * host where Docker cannot `docker exec` a HEALTHCHECK (`EXEC_FAILED_STATE`) instead of `"healthy"`. * * `failCreate`/`failRemove` (both default `false`) make `docker create`/`docker rm` exit * non-zero instead. @@ -960,7 +949,7 @@ const SHADOW_STARTING_STATE = '{"Running":true,"Status":"running","Health":{"Sta * supabase_db_` probe `isLocalDbRunning` issues before `--use-pgadmin` provisions * anything — distinguished from the shadow's own `container inspect <64-hex-id>` health probe by * the target id's `supabase_db_` prefix, so both options leave the shadow's own health check on - * its normal (healthy/never-healthy) path. `dbNotRunning` reports Docker's "container doesn't + * its normal path. `dbNotRunning` reports Docker's "container doesn't * exist" shape (`isContainerNotFoundMessage`); mutually exclusive with `dbInspectFailsWith`, * which instead reports a daemon-unreachable failure (`isDockerDaemonUnreachable`) with the given * stderr text — enforced below (a test that sets both throws immediately, rather than one option @@ -972,7 +961,7 @@ const SHADOW_STARTING_STATE = '{"Running":true,"Status":"running","Health":{"Sta */ export function mockShadowContainerCliSpawner( opts: { - readonly neverHealthy?: boolean; + readonly execFailedHealth?: boolean; readonly failCreate?: boolean; readonly failRemove?: boolean; readonly dbNotRunning?: boolean; @@ -988,7 +977,7 @@ export function mockShadowContainerCliSpawner( "mockShadowContainerCliSpawner: dbNotRunning and dbInspectFailsWith are mutually exclusive", ); } - const neverHealthy = opts.neverHealthy ?? false; + const execFailedHealth = opts.execFailedHealth ?? false; const failCreate = opts.failCreate ?? false; const failRemove = opts.failRemove ?? false; const spawned: Array<{ readonly args: ReadonlyArray }> = []; @@ -1061,7 +1050,7 @@ export function mockShadowContainerCliSpawner( stdoutLines = [FAKE_SHADOW_CONTAINER_ID]; } } else if (args[0] === "container" && args[1] === "inspect") { - stdoutLines = [neverHealthy ? SHADOW_STARTING_STATE : SHADOW_HEALTHY_STATE]; + stdoutLines = [execFailedHealth ? EXEC_FAILED_STATE : SHADOW_HEALTHY_STATE]; } else if (args[0] === "rm") { if (failRemove) { exitCode = 1; diff --git a/apps/cli/tests/helpers/docker-health.ts b/apps/cli/tests/helpers/docker-health.ts new file mode 100644 index 0000000000..41f97abbd0 --- /dev/null +++ b/apps/cli/tests/helpers/docker-health.ts @@ -0,0 +1,48 @@ +/** What Docker records for a HEALTHCHECK probe it could not start on a host where `docker exec` fails. */ +export const EXEC_FAILURE_OUTPUT = + "OCI runtime exec failed: exec failed: unable to start container process: error executing setns process: exit status 1: unknown"; + +/** Moby records a probe that outlived its timeout with the same exit code as an exec-start failure. */ +export const PROBE_TIMEOUT_OUTPUT = "Health check exceeded timeout (2s)"; + +export interface RecordedProbe { + readonly exitCode: number; + readonly output: string; +} + +/** The `docker container inspect --format '{{json .State}}'` shape, including `Health.Log`. */ +export function inspectedState( + opts: { + readonly health?: string; + readonly probes?: ReadonlyArray; + readonly status?: string; + readonly running?: boolean; + } = {}, +): string { + return JSON.stringify({ + Status: opts.status ?? "running", + Running: opts.running ?? true, + ExitCode: 0, + OOMKilled: false, + ...(opts.health === undefined + ? {} + : { + Health: { + Status: opts.health, + FailingStreak: opts.health === "healthy" ? 0 : (opts.probes?.length ?? 0), + Log: (opts.probes ?? []).map((probe) => ({ + Start: "2026-10-27T10:00:00.000000000Z", + End: "2026-10-27T10:00:00.100000000Z", + ExitCode: probe.exitCode, + Output: probe.output, + })), + }, + }), + }); +} + +/** A running container whose HEALTHCHECK has never been able to start. */ +export const EXEC_FAILED_STATE = inspectedState({ + health: "unhealthy", + probes: [{ exitCode: -1, output: EXEC_FAILURE_OUTPUT }], +}); From 63716d1038b1edb2c3346e275538b0b40c9a413e Mon Sep 17 00:00:00 2001 From: Colum Ferry Date: Wed, 28 Oct 2026 10:00:26 +0000 Subject: [PATCH 2/2] fix(cli): catch legacy runc image faults and keep the unverified warning under --ignore-health-check - Treat pre-1.1 runc "exec user process caused: ..." exec format, missing-interpreter and permission errors as image faults, not as a host that cannot exec. - Carry the containers accepted on `running` alone on HealthCheckTimeoutError and print the unverified-readiness warning when --ignore-health-check downgrades a failure. --- .../db-bootstrap/health-check.ts | 3 ++ .../src/command-internal/docker-lifecycle.ts | 4 ++- .../docker-lifecycle.unit.test.ts | 18 +++++++++++ apps/cli/src/commands/start/start.handler.ts | 6 ++++ .../commands/start/start.integration.test.ts | 31 +++++++++++++++++++ 5 files changed, 61 insertions(+), 1 deletion(-) diff --git a/apps/cli/src/command-internal/db-bootstrap/health-check.ts b/apps/cli/src/command-internal/db-bootstrap/health-check.ts index f03b365d5d..0e095f34ab 100644 --- a/apps/cli/src/command-internal/db-bootstrap/health-check.ts +++ b/apps/cli/src/command-internal/db-bootstrap/health-check.ts @@ -77,6 +77,8 @@ export class HealthCheckTimeoutError extends Data.TaggedError("HealthCheckTimeou * logger is a non-sequitur. */ readonly suggestion?: string; + /** Containers accepted as ready on `running` alone because Docker could not exec their health check. */ + readonly readinessAssumed?: ReadonlyArray; }> { get [ErrorActionabilityId](): CliErrorActionabilityDeclaration { return actionability.startStack; @@ -466,6 +468,7 @@ export function waitForHealthyServices( .join("\n"), unhealthy: probeError.failures, ...(hints.length === 0 ? {} : { suggestion: hints.join("\n\n") }), + ...(seen.assumed.size === 0 ? {} : { readinessAssumed: [...seen.assumed] }), }); }), ), diff --git a/apps/cli/src/command-internal/docker-lifecycle.ts b/apps/cli/src/command-internal/docker-lifecycle.ts index 621c77e78a..aa5bc5c7c2 100644 --- a/apps/cli/src/command-internal/docker-lifecycle.ts +++ b/apps/cli/src/command-internal/docker-lifecycle.ts @@ -264,10 +264,12 @@ function parseLastHealthProbe(health: unknown): ContainerHealthProbe | undefined return { exitCode, output: output.replace(/\s+/gu, " ").trim() }; } -// runc reports a bad healthcheck command as a Go `exec.Error` or as an `os.PathError`. +// runc reports a bad healthcheck command as a Go `exec.Error`, an `os.PathError`, or (before +// runc 1.1) wrapped in "exec user process caused". const EXEC_IMAGE_FAULT_PATTERNS: ReadonlyArray = [ /exec: \\?"[^"]*": (?:executable file not found in \$PATH|stat \S+: no such file or directory|permission denied)/u, /(?:^|: )exec [^\s:]+: (?:no such file or directory|exec format error|permission denied)/u, + /exec user process caused:? \\?"?(?:no such file or directory|exec format error|permission denied)/u, ]; /** diff --git a/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts b/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts index 136bac59fc..8c4b435d57 100644 --- a/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts +++ b/apps/cli/src/command-internal/docker-lifecycle.unit.test.ts @@ -603,6 +603,24 @@ describe("healthCheckCannotExec", () => { ), ), ], + [ + "an older runc reporting a healthcheck binary built for another architecture", + state( + probe( + -1, + "OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec user process caused: exec format error: unknown", + ), + ), + ], + [ + "an older runc reporting a missing shebang interpreter", + state( + probe( + -1, + 'OCI runtime exec failed: exec failed: container_linux.go:349: starting container process caused "exec user process caused \\"no such file or directory\\"": unknown', + ), + ), + ], [ "an image fault that only appears after the first 300 characters", state(probe(-1, imageFaultPastTheDisplayedReason)), diff --git a/apps/cli/src/commands/start/start.handler.ts b/apps/cli/src/commands/start/start.handler.ts index 8a8ef7727d..eb7e120996 100644 --- a/apps/cli/src/commands/start/start.handler.ts +++ b/apps/cli/src/commands/start/start.handler.ts @@ -1881,6 +1881,12 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) { } // Downgrade to a warning and fall through to the success path, no rollback. yield* output.raw(`${healthWarningText(error)}\n`, "stderr"); + if (error.readinessAssumed !== undefined) { + yield* output.raw( + healthCheckExecUnavailableWarning(error.readinessAssumed), + "stderr", + ); + } } else { // No manual `rollbackStart` here — the outer `Effect.onError` // below rolls back on this failure too. diff --git a/apps/cli/src/commands/start/start.integration.test.ts b/apps/cli/src/commands/start/start.integration.test.ts index 48a6992f73..12e48c4bb7 100644 --- a/apps/cli/src/commands/start/start.integration.test.ts +++ b/apps/cli/src/commands/start/start.integration.test.ts @@ -3967,6 +3967,37 @@ content_path = "./supabase/templates/custom_notice.html" 10_000, ); + it.live( + "--ignore-health-check still names the services accepted as running when it downgrades a failure", + () => + Effect.gen(function* () { + const { layer, out, child } = yield* setup({ + route: execBrokenHostRoute(), + httpClientLayer: mockGatewayHttpClient({ "/storage/v1/status": 503 }).layer, + }); + + yield* start(flags({ ignoreHealthCheck: true })).pipe(Effect.provide(layer)); + + const storage = serviceContainerName("storage", projectId); + expect(out.stderrText).toContain( + `${storage} container is not ready: /storage/v1/status: unexpected status 503`, + ); + const warnings = out.stderrText + .split("\n") + .filter((line) => line.includes("Docker cannot run health checks")); + expect(warnings).toHaveLength(1); + for (const service of readinessAssumed) { + expect(warnings[0]).toContain(serviceContainerName(service, projectId)); + } + expect(warnings[0]).not.toContain(storage); + expect(rollbackWasAttempted(child.spawned)).toBe(false); + }).pipe( + Effect.provideService(HealthCheckTimeoutSeconds, 0), + Effect.provide(BunServices.layer), + ), + 10_000, + ); + it.live( "does not accept a Docker probe timeout as an exec failure", () =>