mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
fix(startup): report ready without waiting for backlog first passes (#21247)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - A hosted instance upgrades by starting a new server beside the old
server. The deployer sends traffic to the new server when `GET
/api/ready` returns 200.
> - `/api/ready` returns 200 only after the boot sequence in
`server/src/index.ts` sets the phase to "ready".
> - The boot sequence awaited the first pass of many delivery queues.
Each pass grows with saved backlog or waits on outside services.
> - On a busy instance, these passes took more than the deploy's
health-check window. The deployer killed two new servers in a row before
they became ready, including a rollback to an image that had started in
86 s one hour before.
> - This pull request moves those first passes off the readiness path.
Readiness now waits only on named, bounded preconditions, and each step
reports its duration.
> - The benefit: an upgrade or rollback becomes ready in boot time, not
in backlog time. A slow start also names its slow step in one log line.
## Linked Issues or Issue Description
**What happened?**
On the hosted staging instance, two replacement servers did not report
`/api/ready` and were killed after about 9 minutes. The first was a new
image and the second was a rollback to the old image. At that time the
instance had about 200 queued runs, about 80 running runs, a slow
database, and many continuation runs. The failed server logged "managed
environments ensured from managed config" (`index.ts` line 1284 on
master). It never logged "worktree run-execution cutoff state" (line
1726), which the server always logs when the heartbeat service exists.
Between those two lines, boot awaited only these steps: `tool_reviews`
(four tool-review queue first passes), `gateway_sessions`,
`delivery_workers` (budget enforcement, cost accounting, fast responses,
chat completions, connection continuations, tool action receipts and
question responses), the GitHub connection event and continuity workers,
and `terminalWorkspaceWorker.ready`. Each step is a delivery-coordinator
`register(...).ready`, and that promise resolves only after the queue's
whole first pass. No queue except `mcp-client-mirror` (also failing on
the healthy server) logged an error, so the cause was slow passes and
not failures. The log had no per-step markers, so it does not show which
of these awaits was still running at the kill.
**Expected behavior**
Readiness means "this server can serve requests and take over". It must
not wait on work that grows with backlog or that depends on an outside
service. Queues own that work and retry it on their own schedule after
readiness.
**Steps to reproduce**
1. Start the server while the first pass of any of the queues above does
not finish. The new test in `server-startup-feedback-export.test.ts`
does this for every queue.
2. On master, `startServer()` does not resolve and the phase stays
"recovering".
## What Changed
- `server/src/index.ts`: These first passes now start in the background
as tracked scheduler work and do not hold readiness: tool reviews,
gateway sessions, delivery workers, GitHub connection workers, the
terminal workspace sweep, environment lease cleanup (scheduler-disabled
path) and scheduled database backups. Shutdown and idle sleep still wait
for them through `trackHeartbeatSchedulerWork`, and each queue keeps its
retry schedule.
- `server/src/index.ts`: The restart backup after an idle wake (a
`pg_dump` whose time grows with the database) holds idle eligibility
(`markIdleStartupComplete`), as before. It no longer holds readiness.
- `server/src/index.ts`: Every remaining await on the boot path is a
named `startupTimeline.precondition(...)`: `listen`,
`runtime_control_operations`, `execution_policy`,
`managed_environments`, `worktree_run_execution`,
`scheduling_suppression`, `native_recovery`, `external_adapters` and
`cloud_configuration`. These preconditions do not change.
- `server/src/startup-timeline.ts`: Adds `precondition(step, work)` and
`background(step, work)`. A precondition that is still running after 30
s is named in the warning "startup step is still holding readiness",
which repeats every 30 s. A background step logs a warning once at 30 s
and logs its duration when it finishes late. A background step that
fails is logged with its step name. The line "startup timeline at
readiness" now includes `readinessStepsMs`, `backgroundStepsMs` and
`backgroundStepsOutstanding`. All timers are single unref'd timeouts and
the module adds no queries.
- `server/src/__tests__/startup-readiness-boundary.test.ts`: This guard
test parses `index.ts` with `parseAst` from `vite`. The server already
depends on `vite`, so this PR adds no dependency and no lockfile change.
The test fails when an await on the boot path (between the phases
"recovering" and "ready") is not a named precondition, or when the
precondition names do not match a reviewed list that gives the reason
for each name.
- `server/src/services/terminal-workspace-work.ts`: Updates a comment.
The first sweep no longer holds readiness, and it still skips
compaction.
## Verification
- Red/green regression test: `server-startup-feedback-export.test.ts`,
"reports ready while backlog queues' first passes never finish". This
test makes every first pass above never finish. With master `index.ts`
it fails with `expected 'still starting' to be 'ready'` for both
scheduler settings. With this change it passes.
- Guard test: with master `index.ts`,
`startup-readiness-boundary.test.ts` fails and lists 18 unnamed awaits,
including `timeStartupRecovery("delivery_workers")` and
`terminalWorkspaceWorker.ready`. With this change it passes.
- `cd server && npx vitest run
src/__tests__/server-startup-feedback-export.test.ts
src/startup-timeline.test.ts
src/__tests__/startup-readiness-boundary.test.ts
src/startup-recovery-timing.test.ts
src/__tests__/terminal-workspace-work.test.ts`: all tests pass.
- `cd server && pnpm typecheck`: passes.
- `pnpm verify` exited with code 2 on the first revision (a lockfile
change that this PR no longer makes). Required CI supplies the broad
coverage.
- After deploy, run `grep "startup timeline at readiness"` on a server
start. The line shows each precondition's duration and the background
passes that are still running.
## Risks
- The listed first passes now run at the same time as native run
recovery and the requests that the server serves, not before them.
Requests were already served during recovery. Commit-woken passes of the
same queues, and the fresh queued-run dispatch, already ran at the same
time as native recovery. The coordinator still serializes the passes of
each queue.
- `/api/ready` can now return 200 while a queue still has backlog. That
is the intended meaning, and it matches the queued-run and recovery
passes that already run after readiness (#21014).
- Native run recovery still holds readiness, which is correct because
adoption must happen before takeover. If that recovery is slow, the
server now logs its step name every 30 s.
- Low risk otherwise: no schema or API change.
> 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
- Claude (Anthropic) via Claude Code, model ID `claude-opus-5-5` (commit
trailer: Claude Fable 5.2). Tool use and code execution were enabled.
## 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: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
b0233b5b33
commit
2de5d97958
6 files changed
+332
-37
No files matched your search
@@ -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<string>([
|
||||
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<void>();
|
||||
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<string, number>; 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,
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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());
|
||||
});
|
||||
+45
-27
@@ -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<void>((resolveListen, rejectListen) => {
|
||||
await startupTimeline.precondition("listen", () => new Promise<void>((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<unknown>; 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<void> | 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");
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(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<string>();
|
||||
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<void>();
|
||||
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");
|
||||
});
|
||||
@@ -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<typeof logger, "info" | "warn" | "error">;
|
||||
|
||||
/** 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<string, number>();
|
||||
const background = new Map<string, number>();
|
||||
const outstanding = new Map<string, { startedAt: number; holdsReadiness: boolean }>();
|
||||
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<typeof setTimeout> | 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<T>(step: string, work: () => Promise<T>): Promise<T> {
|
||||
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<unknown>): Promise<void> {
|
||||
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);
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user