Files
PaperClipAI/server/src/shutdown.ts
T
f91e05406d fix(server): bound the shutdown steps after the run drain (#23491)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server runs an ordered shutdown when it gets SIGTERM. It drains
runs, stops workers, tears down the app services, closes the database
and exits.
> - The steps before the run drain have a shared deadline. Most steps
after the run drain have no deadline.
> - When one of those late steps stalls, a server that has finished its
work does not exit. It stays alive until the platform sends SIGKILL. On
Railway that is the full 90 s drain window.
> - A hosted Cloud idle stop waits for the deployment to stop. It has a
fixed stop budget, so a 90 s wait makes it fail with a production error.
> - This pull request puts the late steps under one shared post-drain
deadline and logs each step by name.
> - The benefit is that a stalled step cannot hold the exit, and the log
names the step that stalled.

## Linked Issues or Issue Description

**What happened?**
A hosted Cloud idle stop failed with "Automatic provider stop exhausted
its end-to-end budget" (Sentry PAPERCLIP-CLOUD-BACKEND-8Y, 2026-12-02).
The stop was in its Railway confirmation step, 95 s into a 120 s budget.

**Steps to reproduce**
1. Start a server. Make one step after the run drain stall, for example
a worker `stop()` or the app service teardown that never settles.
2. Send SIGTERM.
3. The server logs its ordered shutdown up to "plugin job coordinator
stopped", and then nothing more. The process does not exit until
SIGKILL.

**Expected behavior**
The server exits within a bounded time after the run drain, also when
one late step stalls. The log names the step that stalled.

**Evidence**
The stack's deployment logs show SIGTERM at 11:00:31.25. The ordered
shutdown logged its last line ("plugin job coordinator stopped") at
11:00:31.53. After that line the server logged nothing. The deployment
was still stopping 89.8 s after SIGTERM, when the Cloud stop budget ran
out at 11:02:01.03. Railway's 90 s drain window ends at about
11:02:01.25. The current code has no log lines after that point, so the
logs cannot show which step stalled. This change adds those log lines.

## What Changed

- `server/src/shutdown.ts`: add `POST_DRAIN_SHUTDOWN_BUDGET_MS` (20 s)
and `createPostDrainShutdownBudget`. It uses the same shared-deadline
step runner as the existing pre-drain budget.
- `finalizeServerShutdown` runs the app service teardown inside the
caller's post-drain budget (`app_services_shutdown`). It bounds the
run-failure report drain (`run_failure_report_drain`) and the span flush
(`instrumentation_shutdown`) to 5 s each, like the database close and
the Sentry close. The embedded PostgreSQL stop has no bound, as before.
- `server/src/index.ts`: the cancellation, runtime response, deployment
hint, delivery work and managed environment recovery stops, and the
run-log mirror flush, now run as named steps in the shared post-drain
budget. The same budget then goes to `finalizeServerShutdown`.
- Failures and timeouts use the existing "shutdown step failed" /
"shutdown step timed out" log lines with the step name.

## Verification

- Red before the change: the new test "bounds the run-failure report
drain and the span flush" failed by a 30 s test timeout, because the old
code waited forever. The budget tests failed because the post-drain
budget did not exist.
- Green after the change: `cd server && npx vitest run
src/shutdown.test.ts` gives 32 passed.
- New tests: a teardown that never settles still reaches the database
close, the provider stop, the Sentry flush and the exit continuation. A
stalled report drain and a stalled span flush time out by name. Steps
after the run drain share one deadline.
- Typecheck: the server's lower layer (with `shutdown.ts`) passed
locally. The `index.ts` layer was killed by this machine's memory limit,
so required CI covers it.

## Risks

- Low risk. Behavior changes only when a late shutdown step takes longer
than its bound. Then the shutdown continues without it, as the pre-drain
steps already do.
- A timed-out setup-token lease release stays a durable record for the
startup reaper, as the existing code comments describe.
- The run-log mirror flush now gets what is left of the 20 s budget. A
very large tail upload on a busy restart can time out. Before this
change, the platform SIGKILL stopped it at the end of the drain window.
- The new per-step log lines add about nine info lines to each shutdown.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), run through Claude Code
with tool use (shell, file edits, Sentry and Railway read tools).
Reasoning mode: standard.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:11:05 -08:00

415 lines
15 KiB
TypeScript

type HotRestartShutdownPreparation = {
skipDrain: boolean;
};
type ShutdownLogger = {
info(obj: object, msg: string): void;
error(obj: object, msg: string): void;
};
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<T> =
| { outcome: "completed"; value: T; durationMs: number }
| { outcome: "timed_out"; durationMs: number }
| { outcome: "failed"; error: unknown; durationMs: number };
export async function afterStalledShutdownStep<T>(result: ShutdownStepResult<T>, onStalled: () => Promise<void>) {
if (result.outcome !== "completed") await onStalled();
return result;
}
export async function runBoundedShutdownStep<T>(input: {
step: string;
signal: "SIGINT" | "SIGTERM";
timeoutMs: number;
run: (abort: AbortSignal) => Promise<T>;
log: ShutdownLogger;
now?: () => number;
}): Promise<ShutdownStepResult<T>> {
const now = input.now ?? Date.now;
const startedAt = now();
const timeoutMs = Math.max(0, input.timeoutMs);
const abort = new AbortController();
let timer: NodeJS.Timeout | null = null;
try {
const result = await Promise.race([
Promise.resolve()
.then(() => input.run(abort.signal))
.then(
(value) => ({ outcome: "completed" as const, value }),
(error: unknown) => ({ outcome: "failed" as const, error }),
),
new Promise<{ outcome: "timed_out" }>((resolve) => {
timer = setTimeout(() => resolve({ outcome: "timed_out" }), timeoutMs);
timer.unref?.();
}),
]);
const durationMs = now() - startedAt;
const fields = { signal: input.signal, step: input.step, durationMs, timeoutMs };
if (result.outcome === "completed") {
input.log.info(fields, "shutdown step completed");
return { outcome: "completed", value: result.value, durationMs };
}
if (result.outcome === "failed") {
input.log.error({ ...fields, err: result.error }, "shutdown step failed; continuing shutdown");
return { outcome: "failed", error: result.error, durationMs };
}
abort.abort(new Error(`shutdown step ${input.step} timed out`));
input.log.info(fields, "shutdown step timed out; continuing shutdown without it");
return { outcome: "timed_out", durationMs };
} finally {
if (timer) clearTimeout(timer);
}
}
export type ShutdownStepBudget = ReturnType<typeof createShutdownStepBudget>;
function createShutdownStepBudget(input: {
signal: "SIGINT" | "SIGTERM";
budgetMs: number;
log: ShutdownLogger;
now?: () => number;
}) {
const now = input.now ?? Date.now;
const deadline = now() + input.budgetMs;
return {
run<T>(step: string, run: (abort: AbortSignal) => Promise<T>) {
return runBoundedShutdownStep({
step,
signal: input.signal,
timeoutMs: deadline - now(),
run,
log: input.log,
now,
});
},
};
}
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<void>) | null;
timeoutMs?: number;
log: ShutdownLogger;
}): Promise<"drained" | "timed_out" | "unavailable"> {
if (!input.drain) return "unavailable";
const timeoutMs = input.timeoutMs ?? 5_000;
let timer: NodeJS.Timeout | null = null;
try {
const result = await Promise.race([
input.drain().then(() => "drained" as const),
new Promise<"timed_out">((resolve) => {
timer = setTimeout(() => resolve("timed_out"), timeoutMs);
timer.unref?.();
}),
]);
if (result === "timed_out") {
input.log.info(
{ signal: input.signal, timeoutMs },
"bounded heartbeat execution finalizer drain timed out",
);
}
return result;
} finally {
if (timer) clearTimeout(timer);
}
}
type ShutdownHttpListener = {
listening: boolean;
close(callback?: (err?: Error) => void): unknown;
closeIdleConnections?: () => void;
closeAllConnections?: () => void;
};
/**
* Stops the HTTP listener from accepting new requests and waits, for at most
* `timeoutMs`, for the open connections to finish. Idle keep-alive sockets
* close at once; whatever is still open when the grace period ends is closed
* forcibly, so the teardown never hangs on a long-lived client. Call this
* before the database pool ends, so no request can reach a route after
* `sql.end()` and fail with a connection-ended error.
*/
export async function closeHttpListenerForShutdown(input: {
server: ShutdownHttpListener;
signal: "SIGINT" | "SIGTERM";
timeoutMs?: number;
drainRequests?: (signal: AbortSignal) => Promise<void>;
closeRunAdmission?: () => void;
log: ShutdownLogger;
}): Promise<"closed" | "timed_out" | "not_listening"> {
input.closeRunAdmission?.();
if (!input.server.listening) return "not_listening";
const timeoutMs = input.timeoutMs ?? 5_000;
let timer: NodeJS.Timeout | null = null;
const controller = new AbortController();
try {
const closed = new Promise<"closed">((resolve) => {
input.server.close((err) => {
if (err && (err as NodeJS.ErrnoException).code !== "ERR_SERVER_NOT_RUNNING") {
input.log.error({ err, signal: input.signal }, "HTTP listener close failed");
}
resolve("closed");
});
input.server.closeIdleConnections?.();
});
return await Promise.race([
input.drainRequests ? input.drainRequests(controller.signal).then(() => {
input.server.closeIdleConnections?.();
return "closed" as const;
}) : closed,
new Promise<"timed_out">((resolve) => {
timer = setTimeout(() => {
input.log.info(
{ signal: input.signal, timeoutMs },
"HTTP listener drain timed out; closing the remaining connections",
);
input.server.closeAllConnections?.();
resolve("timed_out");
}, timeoutMs);
timer.unref?.();
}),
]);
} finally {
if (timer) clearTimeout(timer);
controller.abort();
}
}
/**
* Runs the final, ordered teardown of the server. It awaits the application
* service cleanup first, so a live setup-token login session stops and releases
* its sandbox lease before the database and the provider stop. The caller runs
* `process.exit(0)` only after this helper resolves, so an orderly shutdown
* never leaves a sandbox lease or confidential login state alive past the
* process exit.
*
* A step that rejects does not stop the teardown. The helper logs the error and
* continues to the next step. A failed setup-token lease release stays a
* durable record for the startup reaper; the helper surfaces it in the log
* instead of blocking the exit path.
*/
export async function finalizeServerShutdown(input: {
signal: "SIGINT" | "SIGTERM";
shutdownAppServices: (() => Promise<void>) | undefined;
/**
* Stops the HTTP listener and drains its connections (see
* `closeHttpListenerForShutdown`). Runs first, while every application
* service is still available to the requests being drained, so no request
* runs against a half-dismantled service or an ended pool.
*/
closeHttpListener?: (() => Promise<unknown>) | null;
/**
* Waits for every run-failure Sentry report still in flight. Runs after the
* application services and before the database pool ends, so a report that
* started just before shutdown still gets its database read and reaches
* Sentry before `shutdownSentry` flushes and closes the client.
*/
drainPendingRunFailureReports?: (() => Promise<void>) | null;
/**
* Ends the server's PostgreSQL client pools. Runs after the application
* services (which still need the database) and before the embedded
* provider stops, so the backends close in order and none outlive the
* process.
*/
closeDatabase?: (() => Promise<void>) | null;
stopEmbeddedPostgres: (() => Promise<void>) | null;
shutdownInstrumentation: () => Promise<void>;
shutdownSentry: () => Promise<void>;
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<void> {
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.
if (input.closeHttpListener) {
try {
await input.closeHttpListener();
} catch (err) {
input.log.error({ err, signal }, "HTTP listener shutdown failed");
}
}
// 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 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.
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
// process exit leaves the pooled backends to PostgreSQL's own TCP keepalive
// reaping, and a restart loop can pile up enough of them to hit
// `max_connections` before the next boot gets a connection.
if (input.closeDatabase) {
try {
await input.closeDatabase();
} catch (err) {
input.log.error({ err, signal }, "Database client shutdown failed");
}
}
if (input.stopEmbeddedPostgres) {
input.log.info({ signal }, "Stopping embedded PostgreSQL");
try {
await input.stopEmbeddedPostgres();
} catch (err) {
input.log.error({ err }, "Failed to stop embedded PostgreSQL cleanly");
}
}
// Flush buffered OTel spans before the process goes away; without this await
// 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.
await input.shutdownSentry();
}
const COORDINATED_SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"] as const;
type ShutdownSignalTarget = {
rawListeners(eventName: string): Function[];
removeListener(eventName: string, listener: (...args: any[]) => void): unknown;
};
/**
* Some dependencies eagerly install process signal handlers as an import side
* effect. Paperclip must remain the sole owner of SIGINT/SIGTERM ordering: its
* handler first snapshots live heartbeat runs and only then stops embedded
* infrastructure. Remove only listeners added by the supplied import, while
* preserving every listener that was already registered.
*/
export async function loadWithoutCoordinatedShutdownSignalHooks<T>(
load: () => Promise<T>,
signalTarget: ShutdownSignalTarget = process,
) {
const listenersBeforeLoad = new Map(
COORDINATED_SHUTDOWN_SIGNALS.map((signal) => [
signal,
signalTarget.rawListeners(signal),
]),
);
let loaded: T;
try {
loaded = await load();
} finally {
for (const signal of COORDINATED_SHUTDOWN_SIGNALS) {
const remainingBeforeLoad = [...(listenersBeforeLoad.get(signal) ?? [])];
for (const listener of signalTarget.rawListeners(signal)) {
const existingIndex = remainingBeforeLoad.indexOf(listener);
if (existingIndex >= 0) {
remainingBeforeLoad.splice(existingIndex, 1);
continue;
}
signalTarget.removeListener(signal, listener as (...args: any[]) => void);
}
}
}
return loaded;
}
export async function coordinateHeartbeatSchedulerShutdown<
TPreparation extends HotRestartShutdownPreparation,
>(input: {
signal: "SIGINT" | "SIGTERM";
prepareHotRestartShutdown: ((signal: "SIGINT" | "SIGTERM") => Promise<TPreparation>) | null;
waitForHeartbeatSchedulerIdle: () => Promise<void>;
}): Promise<{
hotRestart: TPreparation | null;
preparationError: unknown;
waitedForSchedulerIdle: boolean;
}> {
let hotRestart: TPreparation | null = null;
let preparationError: unknown = null;
// The signal handler stops the scheduler before entering this coordinator.
// Quiesce any callback that was already in flight before querying running
// rows for the shutdown snapshot, otherwise a late queue claim can create a
// run that is absent from both the snapshot and the selective drain set.
await input.waitForHeartbeatSchedulerIdle();
if (input.prepareHotRestartShutdown) {
try {
hotRestart = await input.prepareHotRestartShutdown(input.signal);
} catch (err) {
preparationError = err;
}
}
return {
hotRestart,
preparationError,
waitedForSchedulerIdle: true,
};
}
export async function finishServiceShutdown(
stop: () => Promise<void>,
cleanup: () => Promise<void>,
): Promise<void> {
const failures: unknown[] = [];
let retryStop = false;
try { await stop(); } catch { retryStop = true; }
try { await cleanup(); } catch (error) { failures.push(error); }
if (retryStop) {
try { await stop(); } catch (error) { failures.unshift(error); }
}
if (failures.length === 1) throw failures[0];
if (failures.length > 1) throw new AggregateError(failures, "Service shutdown failed");
}