diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 3da0d854021..d0816940929 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -1239,11 +1239,13 @@ describe("startServer feedback export wiring", () => { await markIdleBackupWakeRequired(directory); starting = startServer(); await vi.waitFor(() => expect(runDatabaseBackup).toHaveBeenCalledOnce()); + // The dump grows with the database: it holds idle eligibility, not readiness. + await starting; + expect(getStartupRecoveryState().phase).toBe("ready"); expect(eligible).not.toHaveBeenCalled(); expect(idleWorkSnapshot().active).toBeGreaterThan(0); finish(); - await starting; - expect(eligible).toHaveBeenCalledWith({ scheduledBackups: true }); + await vi.waitFor(() => expect(eligible).toHaveBeenCalledWith({ scheduledBackups: true })); const options = createAppMock.mock.calls[0]?.[1] as unknown as { prepareIdleDatabaseBackup?: unknown }; expect(Boolean(options.prepareIdleDatabaseBackup)).toBe(checkpointMode); expect(existsSync(idleBackupWakeMarker(directory))).toBe(fails); @@ -1668,6 +1670,51 @@ describe("startServer feedback export wiring", () => { expect(externalObjectsServiceMock.registerRefreshWork).toHaveBeenCalledOnce(); }); + // paperclip.staging, 2026-11-13: under a large backlog these first passes ran + // past the deploy health-check window, so two replacement servers in a row + // never reported ready and were killed. + it.each([true, false])("reports ready while backlog queues' first passes never finish (scheduler=%s)", async enabled => { + loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: enabled })); + const held = new Set([ + DELIVERY_QUEUES.toolReviewExpiry, DELIVERY_QUEUES.toolReviewRecovery, DELIVERY_QUEUES.toolReviewInterruption, + DELIVERY_QUEUES.toolReviewProjection, DELIVERY_QUEUES.gatewayCredentialExpiry, + DELIVERY_QUEUES.budgetEnforcement, DELIVERY_QUEUES.accounting, DELIVERY_QUEUES.fastResponse, + DELIVERY_QUEUES.chatCompletion, DELIVERY_QUEUES.connection, DELIVERY_QUEUES.toolAction, DELIVERY_QUEUES.question, + DELIVERY_QUEUES.connectionEvents, DELIVERY_QUEUES.connectionContinuity, DELIVERY_QUEUES.terminalWorkspaces, + DELIVERY_QUEUES.environmentCleanup, DELIVERY_QUEUES.databaseBackups, + ]); + const original = deliveryWorkRegisterMock.getMockImplementation()!; + const releases: Array<() => void> = []; + deliveryWorkRegisterMock.mockImplementation((queue, task) => { + if (!held.has(queue)) return original(queue, task); + const pass = Promise.withResolvers(); + releases.push(pass.resolve); + return { ready: pass.promise, wake: vi.fn(), stop: vi.fn(async () => {}), + reconciliationSnapshot: () => ({ revision: `held-${queue}:1`, reconciled: false }) }; + }); + try { + const outcome = await Promise.race([ + startServer().then(() => "ready"), + new Promise(resolve => setTimeout(() => resolve("still starting"), 2_000)), + ]); + expect(outcome).toBe("ready"); + expect(getStartupRecoveryState().phase).toBe("ready"); + const readiness = vi.mocked(logger.info).mock.calls.find(([, message]) => message === "startup timeline at readiness"); + const fields = readiness![0] as unknown as { readinessStepsMs: Record; backgroundStepsOutstanding: string[] }; + expect(fields.backgroundStepsOutstanding).toEqual(expect.arrayContaining(enabled + ? ["tool_reviews", "gateway_sessions", "delivery_workers", "github_connections", "terminal_workspaces"] + // Without the scheduler, tool reviews and gateway sessions sweep once + // directly instead of registering a queue. + : ["delivery_workers", "github_connections", "environment_lease_cleanup"])); + expect(Object.keys(fields.readinessStepsMs)).toEqual(expect.arrayContaining(["listen", "external_adapters"])); + } finally { + deliveryWorkRegisterMock.mockImplementation(original); + // Held passes are tracked idle work; finish them so later tests start idle. + for (const release of releases) release(); + await settleStartupHousekeeping(); + } + }); + it("keeps external object refresh active when heartbeat scheduling is disabled", async () => { loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: false, diff --git a/server/src/__tests__/startup-readiness-boundary.test.ts b/server/src/__tests__/startup-readiness-boundary.test.ts new file mode 100644 index 00000000000..4c14e72a404 --- /dev/null +++ b/server/src/__tests__/startup-readiness-boundary.test.ts @@ -0,0 +1,75 @@ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { parseAst } from "vite"; +import { expect, it } from "vitest"; + +// /api/ready means "this server can serve requests and take over". Each step +// that holds it must be named, bounded by this boot, and listed here with why +// it must finish first. Work that grows with saved backlog (a queue's first +// pass, a sweep, a dump) or waits on an outside service runs through +// startupTimeline.background instead. On 2026-11-13, backlog first passes +// awaited here kept two replacement servers on paperclip.staging from ever +// reporting ready. +const READINESS_PRECONDITIONS: Record = { + listen: "the HTTP/PRP listener must be bound before anything can be served", + runtime_control_operations: "releases control operations the previous process left running, bounded by its in-flight work", + execution_policy: "a bad forced execution policy must fail startup, before any run starts", + managed_environments: "declared environments must exist before queued runs resume (fails closed)", + worktree_run_execution: "one settings read that decides whether run execution is armed", + scheduling_suppression: "one read that decides whether this runtime schedules heartbeats at all", + native_recovery: "adoption of old runs and the gates that can refuse a start finish before taking over", + external_adapters: "adapter type validation rejects valid external adapters until they are loaded", + cloud_configuration: "an image whose saved configuration is not eligible must not take over", +}; + +type Node = { type: string; start: number; end: number; [key: string]: unknown }; + +function children(node: Node): Node[] { + return Object.values(node).flatMap(value => Array.isArray(value) ? value : [value]) + .filter((value): value is Node => Boolean(value) && typeof (value as Node).type === "string"); +} + +function walk(node: Node, functions: Node[], visit: (node: Node, owner: Node | undefined) => void) { + const scope = /Function|ArrowFunctionExpression/.test(node.type) ? [...functions, node] : functions; + visit(node, scope.at(-1)); + for (const child of children(node)) walk(child, scope, visit); +} + +it("holds readiness only on named, listed preconditions", () => { + const file = fileURLToPath(new URL("../index.ts", import.meta.url)); + const source = readFileSync(file, "utf8"); + // Vite's parser (already a server dependency) reads TypeScript as ESTree. + const program = parseAst(source, { lang: "ts" }); + + // The boot path is the function that moves the phase from "recovering" to + // "ready". Awaits inside nested closures run in the background. + let boot: Node | undefined; + let from = -1; + let to = -1; + walk(program as unknown as Node, [], (node, owner) => { + if (node.type !== "CallExpression") return; + const callee = node.callee as Node & { name?: string }; + const phase = ((node.arguments as Node[])[0] as Node & { value?: unknown } | undefined)?.value; + if (callee.name !== "setStartupRecoveryPhase") return; + if (phase === "recovering") { boot = owner; from = node.start; } + if (phase === "ready" && owner === boot) to = node.start; + }); + expect(boot).toBeDefined(); + expect(to).toBeGreaterThan(from); + + const unnamed: string[] = []; + const named: string[] = []; + walk(program as unknown as Node, [], (node, owner) => { + if (node.type !== "AwaitExpression" || owner !== boot || node.start < from || node.start > to) return; + const argument = node.argument as Node; + const callee = argument.type === "CallExpression" ? argument.callee as Node : undefined; + const isPrecondition = callee?.type === "MemberExpression" + && source.slice(callee.start, callee.end) === "startupTimeline.precondition"; + const step = isPrecondition ? ((argument.arguments as Node[])[0] as Node & { value?: unknown }).value : undefined; + if (typeof step === "string") named.push(step); + else unnamed.push(`line ${source.slice(0, node.start).split("\n").length}: ${source.slice(node.start, node.start + 80)}`); + }); + + expect(unnamed, "await on the boot path outside startupTimeline.precondition").toEqual([]); + expect([...new Set(named)].sort()).toEqual(Object.keys(READINESS_PRECONDITIONS).sort()); +}); diff --git a/server/src/index.ts b/server/src/index.ts index 28d568c59b7..76dbbbb71ca 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1099,7 +1099,7 @@ async function startServerWithDatabaseTeardown( // to this address; delaying listen until after orphan reconciliation makes // authenticated adoption impossible and turns a healthy process into a // duplicate-provider risk. - await new Promise((resolveListen, rejectListen) => { + await startupTimeline.precondition("listen", () => new Promise((resolveListen, rejectListen) => { const onError = (err: Error) => { server.off("error", onError); rejectListen(err); @@ -1112,7 +1112,7 @@ async function startServerWithDatabaseTeardown( ); resolveListen(); }); - }); + })); startupListenerBound = true; startupTimeline.mark("listening"); // A blocked event loop lapses every controller lease and freezes every @@ -1127,8 +1127,8 @@ async function startServerWithDatabaseTeardown( resolveLocalRuntimeApiUrl(); try { - const result = await workspaceOperationService(db as any) - .reconcileStaleRuntimeControlOperations(); + const result = await startupTimeline.precondition("runtime_control_operations", () => workspaceOperationService(db as any) + .reconcileStaleRuntimeControlOperations()); if (result.reconciled > 0) { logger.warn( { reconciled: result.reconciled, operationIds: result.operationIds }, @@ -1234,7 +1234,7 @@ async function startServerWithDatabaseTeardown( // PAPERCLIP_EXECUTION_MODE / PAPERCLIP_K8S_* value throws and fails startup // (fail-loud) rather than silently allowing local execution. try { - const policyResult = await bootstrapExecutionPolicyFromEnv(db as any); + const policyResult = await startupTimeline.precondition("execution_policy", () => bootstrapExecutionPolicyFromEnv(db as any)); if (policyResult) { logger.warn( { @@ -1274,12 +1274,12 @@ async function startServerWithDatabaseTeardown( const appLocals = (app as { locals?: { bundledPluginsStartup?: Promise; managedBundledPluginKeys?: readonly string[] }; }).locals; - const managedEnvironmentsResult = await applyManagedEnvironments(db as any, managedConfig, { + const managedEnvironmentsResult = await startupTimeline.precondition("managed_environments", () => applyManagedEnvironments(db as any, managedConfig, { recovery: managedEnvironmentRecovery, pluginsReady: appLocals?.bundledPluginsStartup, autoInstalledPluginKeys: appLocals?.managedBundledPluginKeys, workerManager: pluginWorkerManager, - }); + })); if (managedEnvironmentsResult) { logger.warn(managedEnvironmentsResult, "managed environments ensured from managed config"); } @@ -1561,7 +1561,14 @@ async function startServerWithDatabaseTeardown( if (githubCanRun()) await githubConnectionEvents.pollOnce({ forSetup: true }); })); - await timeStartupRecovery("tool_reviews", async () => { + // A queue's first pass scales with saved backlog and can wait on outside + // services, so none of them holds readiness: on a busy instance these passes + // took longer than a deploy's whole health-check window and the replacement + // server was killed before it reported ready. Each queue owns its work, is + // woken by commits and retries on its own schedule; a first pass that ends + // after ready is the same as any later pass. Requests are already served + // while they run, and shutdown and idle sleep wait for them as tracked work. + trackHeartbeatSchedulerWork(startupTimeline.background("tool_reviews", () => timeStartupRecovery("tool_reviews", async () => { if (config.heartbeatSchedulerEnabled) { await registerToolReviewExpiryWork(deliveryWork, app.locals.toolGateway, () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready; @@ -1584,14 +1591,15 @@ async function startServerWithDatabaseTeardown( ? registerToolReviewProjectionWork(deliveryWork, { sweep: app.locals.toolGateway.repairActionReviewProjections, companies: app.locals.toolGateway.actionReviewProjectionCompanies }, () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready : app.locals.toolGateway.repairActionReviewProjections(); - }).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed")); - await timeStartupRecovery("gateway_sessions", () => config.heartbeatSchedulerEnabled + }).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed")))); + trackHeartbeatSchedulerWork(startupTimeline.background("gateway_sessions", () => timeStartupRecovery("gateway_sessions", () => config.heartbeatSchedulerEnabled ? registerGatewayCredentialExpiryWork(deliveryWork, app.locals.toolGateway, () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready - : app.locals.toolGateway.cleanupExpiredSessions()).catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed")); - await timeStartupRecovery("delivery_workers", () => Promise.all([budgetEnforcementWorker, accountingWorker, fastResponseWorker, ...deliveryWorkers].map(worker => worker.ready))); - await Promise.all([githubEventWorker.ready, githubContinuityWorker.ready]); - startupTimeline.mark("delivery_first_passes"); + : app.locals.toolGateway.cleanupExpiredSessions()).catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed")))); + trackHeartbeatSchedulerWork(startupTimeline.background("delivery_workers", () => timeStartupRecovery("delivery_workers", + () => Promise.all([budgetEnforcementWorker, accountingWorker, fastResponseWorker, ...deliveryWorkers].map(worker => worker.ready))))); + trackHeartbeatSchedulerWork(startupTimeline.background("github_connections", + () => Promise.all([githubEventWorker.ready, githubContinuityWorker.ready]))); if (heartbeat) { const secretProposals = createSecretProposalsService(db as any); @@ -1685,7 +1693,7 @@ async function startServerWithDatabaseTeardown( }, }, () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped); unregisterTerminalWorkspaceProbe = registerIdleLocalWorkProbe(() => terminalWorkspaceWorker.hasUnrecoveredWork() ? "present" : "none"); - await terminalWorkspaceWorker.ready; + trackHeartbeatSchedulerWork(startupTimeline.background("terminal_workspaces", () => terminalWorkspaceWorker.ready)); const adapterLoginReaper = createDeviceLoginReaper({ store: createDbAdapterAuthSessionStore(db as any), @@ -1720,9 +1728,9 @@ async function startServerWithDatabaseTeardown( } }; - const worktreeRunExecutionActivation = await resolveWorktreeRunExecutionActivationState({ + const worktreeRunExecutionActivation = await startupTimeline.precondition("worktree_run_execution", () => resolveWorktreeRunExecutionActivationState({ getExperimental: () => instanceSettingsService(db).getExperimental(), - }); + })); logger.info( { state: worktreeRunExecutionActivation.armed ? "armed" : "disarmed", @@ -1730,7 +1738,7 @@ async function startServerWithDatabaseTeardown( }, "worktree run-execution cutoff state", ); - const heartbeatSchedulingSuppression = await heartbeat.resolveSchedulingSuppression(); + const heartbeatSchedulingSuppression = await startupTimeline.precondition("scheduling_suppression", () => heartbeat.resolveSchedulingSuppression()); // Reap orphaned runs before timer ticks start so wakeups cannot coalesce // into a dead "running" row during startup recovery. @@ -1812,7 +1820,9 @@ async function startServerWithDatabaseTeardown( throw err; }); trackHeartbeatSchedulerWork(startupHeartbeatRecovery); - await startupHeartbeatRecovery; + // Adoption of old runs and the gates that can refuse a start finish + // before this server takes over (see the comment below). + await startupTimeline.precondition("native_recovery", () => startupHeartbeatRecovery); } startupTimeline.mark("native_recovery"); @@ -2051,9 +2061,10 @@ async function startServerWithDatabaseTeardown( // is still required. A failed acquire can leak a paid provider sandbox, so // this path registers the same startup recovery and pending-work deadlines // as the enabled path. - await startEnvironmentCleanup(); + trackHeartbeatSchedulerWork(startupTimeline.background("environment_lease_cleanup", startEnvironmentCleanup)); } + let idleWakeBackup: Promise | null = null; if (config.databaseBackupEnabled) { const backupIntervalMs = config.databaseBackupIntervalMinutes * 60 * 1000; @@ -2068,20 +2079,25 @@ async function startServerWithDatabaseTeardown( // The final pre-sleep dump remains on the volume throughout sleep. Take // a fresh backup on restart before idle eligibility is enabled, including // after rollback of the opt-in flag. Failure retains the marker for retry. + // A dump grows with the database, so it holds idle eligibility, not + // readiness. if (!isWarmStandby() && existsSync(idleBackupWakeMarker(config.databaseBackupDir))) { - await runServerDatabaseBackup("scheduled").catch(() => {}); + idleWakeBackup = startupTimeline.background("idle_wake_backup", () => runServerDatabaseBackup("scheduled").catch(() => {})); + trackHeartbeatSchedulerWork(idleWakeBackup); } - await registerDatabaseBackupWork(deliveryWork, { + trackHeartbeatSchedulerWork(startupTimeline.background("database_backups", () => registerDatabaseBackupWork(deliveryWork, { intervalMs: backupIntervalMs, run: () => runServerDatabaseBackup("scheduled"), - }).ready; + }).ready)); } // Wait for external adapters to finish loading before accepting requests. // Without this, adapter type validation (assertKnownAdapterType) would // reject valid external adapter types during the startup loading window. - const { waitForExternalAdapters } = await import("./adapters/registry.js"); - await waitForExternalAdapters(); + await startupTimeline.precondition("external_adapters", async () => { + const { waitForExternalAdapters } = await import("./adapters/registry.js"); + await waitForExternalAdapters(); + }); // Reconcile the agent-creation picker to the declaratively-configured adapter // set (PAPERCLIP_ADAPTERS). Must run after external adapters are loaded so the @@ -2096,12 +2112,14 @@ async function startServerWithDatabaseTeardown( } if (deploymentListenUrl !== null) { - const qualification = await qualifyCloudConfigurationForCurrentImage(db as any); + const qualification = await startupTimeline.precondition("cloud_configuration", () => qualifyCloudConfigurationForCurrentImage(db as any)); if (qualification && !qualification.configurationPackagesEligible) { throw new Error(`Volume-free server packages are not eligible: ${qualification.blockers.map(blocker => blocker.code).join(", ")}`); } } - markIdleStartupComplete({ scheduledBackups: config.databaseBackupEnabled }); + const markIdleStartup = () => markIdleStartupComplete({ scheduledBackups: config.databaseBackupEnabled }); + if (idleWakeBackup) void idleWakeBackup.then(markIdleStartup); + else markIdleStartup(); setStartupRecoveryPhase("ready"); startupTimeline.mark("ready"); startupTimeline.log("startup timeline at readiness"); diff --git a/server/src/services/terminal-workspace-work.ts b/server/src/services/terminal-workspace-work.ts index 6c86d1ac907..0a479d459f5 100644 --- a/server/src/services/terminal-workspace-work.ts +++ b/server/src/services/terminal-workspace-work.ts @@ -23,9 +23,10 @@ export function registerTerminalWorkspaceWork( ) { let next: number | null = Date.now(); let recovered = false; - // Server readiness waits for the first sweep. Compaction walks worktrees and - // deletes dependency trees, which can take seconds per workspace and is never - // needed to serve requests, so the first sweep skips it and later sweeps do it. + // The first sweep runs while the server finishes starting (it does not hold + // readiness). Compaction walks worktrees and deletes dependency trees, which + // can take seconds per workspace, so the first sweep skips it and later + // sweeps do it. let startupSweepStarted = false; const worker = coordinator.register(DELIVERY_QUEUES.terminalWorkspaces, { retryMs: TERMINAL_WORKSPACE_RETRY_MS, diff --git a/server/src/startup-timeline.test.ts b/server/src/startup-timeline.test.ts new file mode 100644 index 00000000000..037cc8b3d41 --- /dev/null +++ b/server/src/startup-timeline.test.ts @@ -0,0 +1,81 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { createStartupTimeline } from "./startup-timeline.js"; + +let uptime = 0; +const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} +const timeline = () => createStartupTimeline({ uptimeMs: () => uptime, log: log as never, warnAfterMs: 30_000 }); + +beforeEach(() => { + uptime = 0; + vi.clearAllMocks(); + vi.useFakeTimers(); +}); +afterEach(() => vi.useRealTimers()); + +it("never waits for a background step and reports it outstanding at readiness", async () => { + const startup = timeline(); + const finished = vi.fn(); + void startup.background("delivery_workers", () => new Promise(() => {})).then(finished); + await startup.precondition("listen", async () => { uptime = 40; }); + uptime = 100; + startup.mark("ready"); + startup.log("startup timeline at readiness"); + expect(finished).not.toHaveBeenCalled(); + expect(log.info).toHaveBeenCalledExactlyOnceWith({ + processUptimeMs: 100, + startupSteps: { ready: 100 }, + readinessStepsMs: { listen: 40 }, + backgroundStepsMs: {}, + backgroundStepsOutstanding: ["delivery_workers"], + }, "startup timeline at readiness"); +}); + +it("names a precondition still holding readiness every interval until it ends", async () => { + const startup = timeline(); + const gate = deferred(); + const result = startup.precondition("native_recovery", () => gate.promise); + uptime = 30_000; + await vi.advanceTimersByTimeAsync(30_000); + uptime = 60_000; + await vi.advanceTimersByTimeAsync(30_000); + expect(log.warn.mock.calls).toEqual([ + [{ startupStep: "native_recovery", waitingMs: 30_000, holdsReadiness: true }, "startup step is still holding readiness"], + [{ startupStep: "native_recovery", waitingMs: 60_000, holdsReadiness: true }, "startup step is still holding readiness"], + ]); + gate.resolve("adopted"); + await expect(result).resolves.toBe("adopted"); + await vi.advanceTimersByTimeAsync(90_000); + expect(log.warn).toHaveBeenCalledTimes(2); +}); + +it("propagates a precondition failure and records its duration", async () => { + const startup = timeline(); + const error = new Error("ineligible"); + await expect(startup.precondition("cloud_configuration", async () => { uptime = 5; throw error; })).rejects.toBe(error); + startup.log("ready"); + expect(log.info.mock.calls[0]![0]).toMatchObject({ readinessStepsMs: { cloud_configuration: 5 } }); +}); + +it("logs a slow or failed background step by name and never rejects", async () => { + const startup = timeline(); + const slow = deferred(); + const slowStep = startup.background("terminal_workspaces", () => slow.promise); + const failed = startup.background("github_connections", async () => { throw new Error("GitHub unavailable"); }); + await expect(failed).resolves.toBeUndefined(); + expect(log.error).toHaveBeenCalledExactlyOnceWith( + { err: expect.any(Error), startupStep: "github_connections" }, "startup background step failed"); + uptime = 30_000; + await vi.advanceTimersByTimeAsync(30_000); + await vi.advanceTimersByTimeAsync(60_000); + expect(log.warn.mock.calls).toEqual([[{ startupStep: "terminal_workspaces", waitingMs: 30_000, holdsReadiness: false }, + "startup step is still running in the background"]]); + uptime = 95_000; + slow.resolve(undefined); + await slowStep; + expect(log.info).toHaveBeenCalledWith({ startupStep: "terminal_workspaces", durationMs: 95_000 }, "startup background step finished"); +}); diff --git a/server/src/startup-timeline.ts b/server/src/startup-timeline.ts index 777d8f67335..df4a8c3f2f6 100644 --- a/server/src/startup-timeline.ts +++ b/server/src/startup-timeline.ts @@ -2,22 +2,95 @@ import { logger } from "./middleware/logger.js"; export type StartupTimelineMark = { step: string; atMs: number; durationMs: number }; +/** A startup step still running after this long is named in a warning, so a + * slow start says which step holds it in one grep ("startup step"). */ +export const STARTUP_STEP_WARN_AFTER_MS = 30_000; + +type StartupTimelineLogger = Pick; + /** Boot-to-ready milestones, measured from process start. One log line at * readiness (and one when the background recovery passes finish) names the - * step that took the time, without an OpenTelemetry collector. */ -export function createStartupTimeline(uptimeMs: () => number = () => process.uptime() * 1000) { + * step that took the time, without an OpenTelemetry collector. + * + * Readiness means "this server can serve requests and take over". Only + * `precondition` steps hold it, and each one must be bounded by this boot, not + * by saved backlog or an outside service. Work that grows with backlog (a + * queue's first pass) goes through `background`: it starts at once, never + * holds readiness, and is reported at readiness as still outstanding. */ +export function createStartupTimeline(options: { + uptimeMs?: () => number; + log?: StartupTimelineLogger; + warnAfterMs?: number; +} = {}) { + const uptimeMs = options.uptimeMs ?? (() => process.uptime() * 1000); + const log = options.log ?? logger; + const warnAfterMs = options.warnAfterMs ?? STARTUP_STEP_WARN_AFTER_MS; const marks: StartupTimelineMark[] = []; + const preconditions = new Map(); + const background = new Map(); + const outstanding = new Map(); + const now = () => Math.round(uptimeMs()); + + function watch(step: string, holdsReadiness: boolean) { + const startedAt = now(); + outstanding.set(step, { startedAt, holdsReadiness }); + // A step that holds readiness is named every period until it ends; a + // background step is named once, since it does not delay anything. One + // unref'd timeout at a time: no interval outlives the step. + let timer: ReturnType | undefined; + const arm = () => { + timer = setTimeout(() => { + if (!outstanding.has(step)) return; + log.warn({ startupStep: step, waitingMs: now() - startedAt, holdsReadiness }, + holdsReadiness ? "startup step is still holding readiness" : "startup step is still running in the background"); + if (holdsReadiness) arm(); + }, warnAfterMs); + timer.unref?.(); + }; + arm(); + return () => { + clearTimeout(timer); + outstanding.delete(step); + return now() - startedAt; + }; + } + return { mark(step: string) { - const atMs = Math.round(uptimeMs()); + const atMs = now(); const previous = marks.at(-1)?.atMs ?? 0; marks.push({ step, atMs, durationMs: atMs - previous }); }, marks: () => marks.map(mark => ({ ...mark })), + /** A step readiness must wait for. Keep it bounded by this boot. */ + async precondition(step: string, work: () => Promise): Promise { + const finish = watch(step, true); + try { + return await work(); + } finally { + preconditions.set(step, finish()); + } + }, + /** Starts work that must not hold readiness. The returned promise never + * rejects (a failure is logged with the step's name), so callers can track + * it as scheduler work. */ + background(step: string, work: () => Promise): Promise { + const finish = watch(step, false); + return Promise.resolve().then(work).then(() => undefined, (err: unknown) => { + log.error({ err, startupStep: step }, "startup background step failed"); + }).finally(() => { + const durationMs = finish(); + background.set(step, durationMs); + if (durationMs >= warnAfterMs) log.info({ startupStep: step, durationMs }, "startup background step finished"); + }); + }, log(message: string) { - logger.info({ - processUptimeMs: Math.round(uptimeMs()), + log.info({ + processUptimeMs: now(), startupSteps: Object.fromEntries(marks.map(mark => [mark.step, mark.durationMs])), + readinessStepsMs: Object.fromEntries(preconditions), + backgroundStepsMs: Object.fromEntries(background), + backgroundStepsOutstanding: [...outstanding].filter(([, entry]) => !entry.holdsReadiness).map(([step]) => step), }, message); }, };