diff --git a/cli/src/__tests__/company-import-export-e2e.test.ts b/cli/src/__tests__/company-import-export-e2e.test.ts index 5182afd3cdc..d6cd35008aa 100644 --- a/cli/src/__tests__/company-import-export-e2e.test.ts +++ b/cli/src/__tests__/company-import-export-e2e.test.ts @@ -12,6 +12,7 @@ import { startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; import { createStoredZipArchive } from "./helpers/zip.js"; +import { CliServerStartupError, retryCliServerStartup } from "./helpers/server-startup.js"; import { removeTestHome } from "../../../tests/helpers/remove-test-home.js"; import { PAPERCLIP_RUNTIME_INFO_FILENAME, readRuntimeInfo } from "../runtime-info.js"; @@ -193,7 +194,7 @@ function collectTextFiles(root: string, current: string, files: Record((resolve) => { child.once("exit", () => resolve()); @@ -264,13 +265,11 @@ async function waitForServer( runtimeInfoPath: string, child: ServerProcess, output: { stdout: string[]; stderr: string[] }, + deadline: number, ) { - const startedAt = Date.now(); - while (Date.now() - startedAt < SERVER_STARTUP_TIMEOUT_MS) { - if (child.exitCode !== null) { - throw new Error( - `paperclipai run exited before healthcheck succeeded.\nstdout:\n${output.stdout.join("")}\nstderr:\n${output.stderr.join("")}`, - ); + while (Date.now() < deadline) { + if (child.exitCode !== null || child.signalCode !== null) { + throw new CliServerStartupError(output.stdout.join(""), output.stderr.join(""), child.exitCode); } const runtime = readRuntimeInfo(instanceId, runtimeInfoPath); @@ -315,43 +314,49 @@ describeEmbeddedPostgres("paperclipai company import/export e2e", () => { mkdirSync(cliShellHome, { recursive: true }); tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-cli-db-"); + const { connectionString } = tempDb; + const startupDeadline = Date.now() + SERVER_STARTUP_TIMEOUT_MS; + apiBase = await retryCliServerStartup(async () => { + await stopServerProcess(serverProcess); + await requestedPortReservation?.release(); + requestedPortReservation = null; + requestedPortReservation = await reserveRequestedPort(); + const { port } = requestedPortReservation; + writeTestConfig(configPath, tempRoot, port, connectionString); + const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); + const output = { stdout: [] as string[], stderr: [] as string[] }; + const child = spawn( + process.execPath, + ["--import", createRequire(import.meta.url).resolve("tsx"), path.join(repoRoot, "cli/src/index.ts"), "run", "--config", configPath], + { + cwd: repoRoot, + env: createServerEnv(configPath, port, connectionString, { + paperclipHome, + instanceId: paperclipInstanceId, + shellHome: cliShellHome, + }), + stdio: ["ignore", "pipe", "pipe"], + }, + ); + serverProcess = child; + child.stdout?.on("data", (chunk) => { + output.stdout.push(String(chunk)); + }); + child.stderr?.on("data", (chunk) => { + output.stderr.push(String(chunk)); + }); - - requestedPortReservation = await reserveRequestedPort(); - const { port } = requestedPortReservation; - writeTestConfig(configPath, tempRoot, port, tempDb.connectionString); - - const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); - const output = { stdout: [] as string[], stderr: [] as string[] }; - const child = spawn( - process.execPath, - ["--import", createRequire(import.meta.url).resolve("tsx"), path.join(repoRoot, "cli/src/index.ts"), "run", "--config", configPath], - { - cwd: repoRoot, - env: createServerEnv(configPath, port, tempDb.connectionString, { - paperclipHome, - instanceId: paperclipInstanceId, - shellHome: cliShellHome, - }), - stdio: ["ignore", "pipe", "pipe"], - }, - ); - serverProcess = child; - child.stdout?.on("data", (chunk) => { - output.stdout.push(String(chunk)); + const apiBase = await waitForServer( + paperclipInstanceId, + path.join(paperclipHome, "instances", paperclipInstanceId, PAPERCLIP_RUNTIME_INFO_FILENAME), + child, + output, + startupDeadline, + ); + expect(new URL(apiBase).port).not.toBe(String(port)); + return apiBase; }); - child.stderr?.on("data", (chunk) => { - output.stderr.push(String(chunk)); - }); - - apiBase = await waitForServer( - paperclipInstanceId, - path.join(paperclipHome, "instances", paperclipInstanceId, PAPERCLIP_RUNTIME_INFO_FILENAME), - child, - output, - ); - expect(new URL(apiBase).port).not.toBe(String(port)); // Room for the embedded database start on top of the server budget. }, SERVER_STARTUP_TIMEOUT_MS + 30_000); diff --git a/cli/src/__tests__/helpers/server-startup.ts b/cli/src/__tests__/helpers/server-startup.ts new file mode 100644 index 00000000000..449df2f0263 --- /dev/null +++ b/cli/src/__tests__/helpers/server-startup.ts @@ -0,0 +1,27 @@ +export class CliServerStartupError extends Error { + constructor( + stdout: string, + readonly stderr: string, + readonly exitCode: number | null, + ) { + super(`paperclipai run exited before healthcheck succeeded.\nstdout:\n${stdout}\nstderr:\n${stderr}`); + } +} + +export async function retryCliServerStartup(startAttempt: () => Promise): Promise { + for (let attempt = 1; ; attempt += 1) { + try { + return await startAttempt(); + } catch (error) { + if ( + attempt >= 3 || + !(error instanceof CliServerStartupError) || + error.exitCode !== 1 || + !/^(?:Error: )?listen EADDRINUSE: address already in use /m.test(error.stderr) + ) { + throw error; + } + console.warn(`CLI test server bind collision; starting attempt ${attempt + 1} of 3`); + } + } +} diff --git a/cli/src/__tests__/server-startup.test.ts b/cli/src/__tests__/server-startup.test.ts new file mode 100644 index 00000000000..ea8b4905d2b --- /dev/null +++ b/cli/src/__tests__/server-startup.test.ts @@ -0,0 +1,94 @@ +import { execFile } from "node:child_process"; +import net from "node:net"; +import { promisify } from "node:util"; +import { describe, expect, it } from "vitest"; +import { CliServerStartupError, retryCliServerStartup } from "./helpers/server-startup.js"; + +const execFileAsync = promisify(execFile); + +async function runChild(script: string): Promise { + try { + const { stdout } = await execFileAsync(process.execPath, ["-e", script]); + return stdout.trim(); + } catch (error) { + const result = error as { code: number; stdout: string; stderr: string }; + if (typeof result.code !== "number") throw error; + throw new CliServerStartupError(result.stdout, result.stderr, result.code); + } +} + +async function occupyPort() { + const server = net.createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const port = (server.address() as net.AddressInfo).port; + return { + port, + close: () => new Promise((resolve, reject) => { + server.close((error) => error ? reject(error) : resolve()); + }), + }; +} + +function listenerScript(port: number) { + return ` + const server = require('node:net').createServer(); + server.on('error', (error) => { + console.error(error.message); + process.exitCode = 1; + }); + server.listen(${port}, '127.0.0.1', () => { + console.log(server.address().port); + server.close(); + }); + `; +} + +describe("CLI test server startup", () => { + it("starts a fresh attempt after a real listener bind collision", async () => { + const occupied = await occupyPort(); + let attempts = 0; + try { + const port = await retryCliServerStartup(async () => { + attempts += 1; + return Number(await runChild(listenerScript(attempts === 1 ? occupied.port : 0))); + }); + expect(attempts).toBe(2); + expect(port).toBeGreaterThan(0); + expect(port).not.toBe(occupied.port); + } finally { + await occupied.close(); + } + }); + + it.each([ + [1, "invalid server configuration"], + [2, "listen EADDRINUSE: address already in use 127.0.0.1:3100"], + ])("preserves a non-bind startup failure (exit %s)", async (exitCode, stderr) => { + let attempts = 0; + await expect(retryCliServerStartup(async () => { + attempts += 1; + return await runChild(`console.error(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`); + })).rejects.toMatchObject({ exitCode, stderr: `${stderr}\n` }); + expect(attempts).toBe(1); + }); + + it("fails after three bind collisions and retains the final diagnostics", async () => { + const occupied = await occupyPort(); + let attempts = 0; + try { + await expect(retryCliServerStartup(async () => { + attempts += 1; + return await runChild(listenerScript(occupied.port)); + })).rejects.toMatchObject({ + exitCode: 1, + stderr: expect.stringContaining(`EADDRINUSE: address already in use 127.0.0.1:${occupied.port}`), + }); + expect(attempts).toBe(3); + } finally { + await occupied.close(); + } + }); +}); diff --git a/packages/adapter-utils/src/ssh-fixture.test.ts b/packages/adapter-utils/src/ssh-fixture.test.ts index 7a21074658b..09b7886b091 100644 --- a/packages/adapter-utils/src/ssh-fixture.test.ts +++ b/packages/adapter-utils/src/ssh-fixture.test.ts @@ -625,6 +625,7 @@ describe("ssh env-lab fixture", () => { const remoteCommandLine = String(target.args.at(-1) ?? ""); const output = execFileSync(dashPath!, ["-c", remoteCommandLine], { encoding: "utf8", + input: target.stdinPrefix, env: { HOME: homeDir, PATH: `${binDir}:/usr/bin:/bin` }, });