diff --git a/server/src/index.ts b/server/src/index.ts index 961e28c01ee..eed4c10ea47 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -224,6 +224,7 @@ import { afterStalledShutdownStep, closeHttpListenerForShutdown, coordinateHeartbeatSchedulerShutdown, + createPostDrainShutdownBudget, createPreDrainShutdownBudget, drainRunExecutionFinalizersForShutdown, finalizeServerShutdown, @@ -2396,21 +2397,21 @@ async function startServerWithDatabaseTeardown( }); } - await cancellationDelivery?.stop(); - await runtimeResponseDelivery?.stop(); - await deploymentHints?.stop(); - await deliveryWork.stop(); - await managedEnvironmentRecovery.stop(); + // One deadline covers every stop from here through the application + // teardown, and each step is logged by name. A stalled stop must not keep + // a finished server alive until the platform's SIGKILL. + const postDrain = createPostDrainShutdownBudget({ signal, log: logger }); + await postDrain.run("cancellation_delivery_stop", async () => { await cancellationDelivery?.stop(); }); + await postDrain.run("runtime_response_delivery_stop", async () => { await runtimeResponseDelivery?.stop(); }); + await postDrain.run("deployment_hints_stop", async () => { await deploymentHints?.stop(); }); + await postDrain.run("delivery_work_final_stop", () => deliveryWork.stop()); + await postDrain.run("managed_environment_recovery_stop", () => managedEnvironmentRecovery.stop()); // Whatever the drain did not finalize (timed-out runs, the hot-restart // skip path) still has a local-only tail when the in-flight run-log // mirror is enabled; upload those tails now so an orderly restart // never loses run output. No-op when the mirror is off. - try { - await flushInFlightRunLogMirrors(); - } catch (err) { - logger.error({ err, signal }, "run-log in-flight mirror flush failed"); - } + await postDrain.run("run_log_mirror_flush", () => flushInFlightRunLogMirrors()); const appShutdown = (app as { locals?: { paperclipShutdown?: () => Promise } }).locals ?.paperclipShutdown; @@ -2446,6 +2447,7 @@ async function startServerWithDatabaseTeardown( shutdownInstrumentation, shutdownSentry, log: logger, + postDrain, }); if (!exitProcess && server.listening) { diff --git a/server/src/shutdown.test.ts b/server/src/shutdown.test.ts index 43e2147c77a..bc35bdac81e 100644 --- a/server/src/shutdown.test.ts +++ b/server/src/shutdown.test.ts @@ -3,11 +3,13 @@ import { describe, expect, it, vi } from "vitest"; import { closeHttpListenerForShutdown, coordinateHeartbeatSchedulerShutdown, + createPostDrainShutdownBudget, createPreDrainShutdownBudget, drainRunExecutionFinalizersForShutdown, finalizeServerShutdown, finishServiceShutdown, loadWithoutCoordinatedShutdownSignalHooks, + POST_DRAIN_SHUTDOWN_BUDGET_MS, runBoundedShutdownStep, } from "./shutdown.js"; @@ -234,8 +236,8 @@ describe("finalizeServerShutdown", () => { expect(closeDatabase).toHaveBeenCalledOnce(); expect(log.error).toHaveBeenCalledWith( - expect.objectContaining({ err: drainError, signal: "SIGTERM" }), - "run-failure report drain failed", + expect.objectContaining({ err: drainError, signal: "SIGTERM", step: "run_failure_report_drain" }), + "shutdown step failed; continuing shutdown", ); }); @@ -256,7 +258,73 @@ describe("finalizeServerShutdown", () => { expect(shutdownAppServices).toHaveBeenCalledOnce(); expect(shutdownInstrumentation).toHaveBeenCalledOnce(); - expect(log.info).not.toHaveBeenCalled(); + expect(log.info).not.toHaveBeenCalledWith(expect.anything(), "Stopping embedded PostgreSQL"); + }); + + // PAPERCLIP-CLOUD-BACKEND-8Y: an idle stack's teardown went silent after + // the run drain and held its deployment until the platform's SIGKILL, so + // the Cloud's bounded automatic stop ran out of time waiting for it. + it("exits within the post-drain budget when the app service teardown never settles", async () => { + vi.useFakeTimers(); + try { + const log = stubLogger(); + const order: string[] = []; + const finalize = finalizeServerShutdown({ + signal: "SIGTERM", + postDrain: createPostDrainShutdownBudget({ signal: "SIGTERM", budgetMs: 1_000, log }), + shutdownAppServices: () => new Promise(() => undefined), + drainPendingRunFailureReports: async () => { order.push("reports:drain"); }, + closeDatabase: async () => { order.push("database:close"); }, + stopEmbeddedPostgres: async () => { order.push("postgres:stop"); }, + shutdownInstrumentation: async () => { order.push("instrumentation:flush"); }, + shutdownSentry: async () => { order.push("sentry:flush"); }, + log, + }).then(() => { order.push("exit"); }); + + await vi.advanceTimersByTimeAsync(1_000); + await finalize; + + expect(order).toEqual(["reports:drain", "database:close", "postgres:stop", "instrumentation:flush", "sentry:flush", "exit"]); + expect(log.info).toHaveBeenCalledWith( + expect.objectContaining({ step: "app_services_shutdown", timeoutMs: 1_000 }), + expect.stringContaining("timed out"), + ); + } finally { + vi.useRealTimers(); + } + }); + + it("bounds the run-failure report drain and the span flush, so neither can hold the exit", async () => { + vi.useFakeTimers(); + try { + const log = stubLogger(); + const order: string[] = []; + const hang = () => new Promise(() => undefined); + const finalize = finalizeServerShutdown({ + signal: "SIGTERM", + boundedStepTimeoutMs: 100, + shutdownAppServices: async () => { order.push("appServices"); }, + drainPendingRunFailureReports: hang, + closeDatabase: async () => { order.push("database:close"); }, + stopEmbeddedPostgres: null, + shutdownInstrumentation: hang, + shutdownSentry: async () => { order.push("sentry:flush"); }, + log, + }).then(() => { order.push("exit"); }); + + await vi.advanceTimersByTimeAsync(200); + await finalize; + + expect(order).toEqual(["appServices", "database:close", "sentry:flush", "exit"]); + for (const step of ["run_failure_report_drain", "instrumentation_shutdown"]) { + expect(log.info).toHaveBeenCalledWith( + expect.objectContaining({ step, timeoutMs: 100 }), + expect.stringContaining("timed out"), + ); + } + } finally { + vi.useRealTimers(); + } }); }); @@ -512,6 +580,30 @@ describe("createPreDrainShutdownBudget", () => { }); }); +describe("createPostDrainShutdownBudget", () => { + it("shares one deadline across the teardown steps that follow the run drain", async () => { + vi.useFakeTimers(); + try { + const log = stubLogger(); + const budget = createPostDrainShutdownBudget({ signal: "SIGTERM", log }); + const first = budget.run("delivery_work_final_stop", () => + new Promise((resolve) => setTimeout(resolve, POST_DRAIN_SHUTDOWN_BUDGET_MS - 1_000))); + await vi.advanceTimersByTimeAsync(POST_DRAIN_SHUTDOWN_BUDGET_MS - 1_000); + await expect(first).resolves.toMatchObject({ outcome: "completed" }); + + const second = budget.run("app_services_shutdown", () => new Promise(() => undefined)); + await vi.advanceTimersByTimeAsync(1_000); + await expect(second).resolves.toMatchObject({ outcome: "timed_out" }); + expect(log.info).toHaveBeenCalledWith( + expect.objectContaining({ step: "app_services_shutdown", timeoutMs: 1_000 }), + expect.stringContaining("timed out"), + ); + } finally { + vi.useRealTimers(); + } + }); +}); + describe("loadWithoutCoordinatedShutdownSignalHooks", () => { it("removes the eager signal handlers from the real embedded-postgres import", async () => { const before = { diff --git a/server/src/shutdown.ts b/server/src/shutdown.ts index 63f7f1e2905..e78ed94c8dc 100644 --- a/server/src/shutdown.ts +++ b/server/src/shutdown.ts @@ -8,6 +8,16 @@ type ShutdownLogger = { }; export const PRE_DRAIN_SHUTDOWN_BUDGET_MS = 20_000; +/** + * Shared deadline for the worker stops and application teardown that follow + * the run drain. Each of these steps used to wait without a bound, so one + * stalled stop kept an otherwise finished process alive until the platform's + * SIGKILL (Railway's 90 s drain window) and held up whatever waited for the + * deployment to stop (PAPERCLIP-CLOUD-BACKEND-8Y). + */ +export const POST_DRAIN_SHUTDOWN_BUDGET_MS = 20_000; +/** Bound for a single late teardown step that runs outside the shared budget. */ +export const LATE_SHUTDOWN_STEP_TIMEOUT_MS = 5_000; export type ShutdownStepResult = | { outcome: "completed"; value: T; durationMs: number } @@ -63,14 +73,16 @@ export async function runBoundedShutdownStep(input: { } } -export function createPreDrainShutdownBudget(input: { +export type ShutdownStepBudget = ReturnType; + +function createShutdownStepBudget(input: { signal: "SIGINT" | "SIGTERM"; - budgetMs?: number; + budgetMs: number; log: ShutdownLogger; now?: () => number; }) { const now = input.now ?? Date.now; - const deadline = now() + (input.budgetMs ?? PRE_DRAIN_SHUTDOWN_BUDGET_MS); + const deadline = now() + input.budgetMs; return { run(step: string, run: (abort: AbortSignal) => Promise) { return runBoundedShutdownStep({ @@ -85,6 +97,25 @@ export function createPreDrainShutdownBudget(input: { }; } +export function createPreDrainShutdownBudget(input: { + signal: "SIGINT" | "SIGTERM"; + budgetMs?: number; + log: ShutdownLogger; + now?: () => number; +}) { + return createShutdownStepBudget({ ...input, budgetMs: input.budgetMs ?? PRE_DRAIN_SHUTDOWN_BUDGET_MS }); +} + +/** Each step after the run drain gets only what is left of one shared deadline. */ +export function createPostDrainShutdownBudget(input: { + signal: "SIGINT" | "SIGTERM"; + budgetMs?: number; + log: ShutdownLogger; + now?: () => number; +}) { + return createShutdownStepBudget({ ...input, budgetMs: input.budgetMs ?? POST_DRAIN_SHUTDOWN_BUDGET_MS }); +} + export async function drainRunExecutionFinalizersForShutdown(input: { signal: "SIGINT" | "SIGTERM"; drain: (() => Promise) | null; @@ -216,8 +247,17 @@ export async function finalizeServerShutdown(input: { shutdownInstrumentation: () => Promise; shutdownSentry: () => Promise; log: ShutdownLogger; + /** + * The caller's post-drain deadline, already shared with the worker stops + * before this call. The application teardown gets what is left of it. + */ + postDrain?: ShutdownStepBudget; + /** Bound for the run-failure report drain and the span flush. */ + boundedStepTimeoutMs?: number; }): Promise { const { signal } = input; + const postDrain = input.postDrain ?? createPostDrainShutdownBudget({ signal, log: input.log }); + const boundedStepTimeoutMs = input.boundedStepTimeoutMs ?? LATE_SHUTDOWN_STEP_TIMEOUT_MS; // Stop accepting requests and drain the open ones before any service goes // away, so a request that is still in flight sees a fully working server. @@ -231,23 +271,19 @@ export async function finalizeServerShutdown(input: { // Await the application service cleanup, so a live setup-token login session // releases its sandbox lease before the database and the provider stop. A - // rejected cleanup stays durable for the reaper; it does not block the exit. - try { - await input.shutdownAppServices?.(); - } catch (err) { - input.log.error({ err, signal }, "Application service shutdown failed"); - } + // rejected or stalled cleanup stays durable for the reaper; it does not + // block the exit past the post-drain deadline. + const shutdownAppServices = input.shutdownAppServices; + if (shutdownAppServices) await postDrain.run("app_services_shutdown", () => shutdownAppServices()); // Wait for every in-flight run-failure Sentry report before the database // pool ends. `reportRunFailure` is fire-and-forget: without this wait, a // report that started just before shutdown can lose its database read to // the pool end below, or lose its Sentry call to the flush further down. - if (input.drainPendingRunFailureReports) { - try { - await input.drainPendingRunFailureReports(); - } catch (err) { - input.log.error({ err, signal }, "run-failure report drain failed"); - } + const drainPendingRunFailureReports = input.drainPendingRunFailureReports; + if (drainPendingRunFailureReports) { + await runBoundedShutdownStep({ step: "run_failure_report_drain", signal, timeoutMs: boundedStepTimeoutMs, + run: () => drainPendingRunFailureReports(), log: input.log }); } // End the client pools once nothing needs them any more. Without this the @@ -272,8 +308,10 @@ export async function finalizeServerShutdown(input: { } // Flush buffered OTel spans before the process goes away; without this await - // the exporter's final batch is dropped on exit. - await input.shutdownInstrumentation(); + // the exporter's final batch is dropped on exit. An unreachable collector + // must not hold the exit, so the flush is bounded like the Sentry close. + await runBoundedShutdownStep({ step: "instrumentation_shutdown", signal, timeoutMs: boundedStepTimeoutMs, + run: () => input.shutdownInstrumentation(), log: input.log }); // Flush buffered Sentry events before the process goes away; without this // await the last events are dropped on exit.