mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
test: fix CLI bind races and SSH fixture input (#23830)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - CI runs fixtures for real CLI servers and SSH commands. > - The CLI fixture can lose its fallback port before the server binds it. > - The SSH login-profile fixture must supply the command payload on stdin. > - These fixture failures stop CI before it can verify the application behavior. > - This pull request adds bounded CLI bind retries and supplies the SSH stdin payload. > - The fixtures retain their startup deadlines, child identity checks, and behavior assertions. ## Linked Issues or Issue Description **What happened?** [Source verification 47462717613, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/47462717613/job/145492578739) failed in `cli/src/__tests__/company-import-export-e2e.test.ts`. The fixture occupied port 41511. The server selected 41512, then exited with `listen EADDRINUSE: address already in use 127.0.0.1:41512`. The suite failed before health readiness. The other 354 files passed, with 3,971 tests passed and one skipped. This cancelled [image run 47462717565](https://github.com/paperclipai/paperclip/actions/runs/47462717565). The SSH login-profile fixture also ran the command bootstrap without its stdin payload. It exited with code 125 before it could check profile behavior. [CI run 47464397195 on `ef3250d`](https://github.com/paperclipai/paperclip/actions/runs/47464397195/job/145497678930) failed on that test. The CLI shard passed in the same run. **Expected behavior** A fixture can start a fresh attempt after it loses a listener bind race to another local process. A configuration error, signal exit, health timeout, or test assertion must still fail. Runtime discovery must use the child PID and actual fallback port. The SSH fixture must supply `stdinPrefix` to execute the generated remote command. **Steps to reproduce** The failed source was master `dfe392dada69838da3d7c33a0ef00d7e4cfc60f3`, in local trusted mode. Reserve a loopback port, then make a child process bind that port. The new socket regression test does this without timing assumptions. Without the retry policy, the first collision aborts startup. For the SSH failure, run `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run packages/adapter-utils/src/ssh-fixture.test.ts -t 'survives a bash-only login profile' --maxWorkers=1` on a host with `dash`. Before the stdin fix, it exits 125 with empty output. Refs #23813: that separate database teardown fix is already in this master revision. This failure is a listener bind collision. ## What Changed - Retry only a child exit with code 1 and the listener `EADDRINUSE` diagnostic on stderr. Limit startup to three attempts. - Release the old port reservation and start a fresh child with a fresh requested-port reservation on each attempt. - Share the original 90-second startup deadline across attempts. Keep the PID-matched runtime health check and the assertion that the server used a fallback port. - Recognize a child that has already exited by signal, so cleanup does not wait for a past exit event. - Add real-socket regression tests for recovery, failure limits, and other startup errors. - Pass `target.stdinPrefix` to the SSH login-profile fixture process, as required by the existing transport contract. ## Verification - CLI red: with the policy set to one attempt, the socket recovery test failed with the same `EADDRINUSE` diagnostic as CI. The bounded-attempt test also failed. - CLI green: `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run cli/src/__tests__/server-startup.test.ts cli/src/__tests__/company-import-export-e2e.test.ts --maxWorkers=1` passed both suites and all five tests after rebase. CLI typecheck passed. These files have not changed since that verification. - SSH red: the targeted login-profile test failed locally with exit 125 and retries disabled, matching the CI failure on `ef3250d`. - SSH green: `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run packages/adapter-utils/src/ssh-fixture.test.ts --maxWorkers=1` passed 26 tests, with two skipped. `pnpm exec tsc --noEmit -p packages/adapter-utils/tsconfig.json` passed. - The test budget check passed for all three changed test files. `git diff --check` passed. Final head: `4b0a5e4b96702829454b101b57be313b8908a63e`. - The CLI dependency-selection plan retained 2,347 of 3,084 test files on the previous head. Required CI will verify the final head with the SSH correction. No full local suite was run. - [Greptile rated final head `4b0a5e4b96702829454b101b57be313b8908a63e` 5/5](https://github.com/paperclipai/paperclip/pull/23830#issuecomment-7429780977), with no actionable findings or review threads. Final check results: 76 passed, six skipped, none pending or failed. The [final CI workflow](https://github.com/paperclipai/paperclip/actions/runs/47465088910) passed, and GitHub reports no merge conflicts. - Operational recovery: [image run 47463279495](https://github.com/paperclipai/paperclip/actions/runs/47463279495/job/145501215693) passed exact-source verification and published the AMD64/ARM64 manifest for master `6a5dfc028831831756bea006df4e399e31cdf281`. Tag: `ghcr.io/paperclipai/paperclip:sha-6a5dfc0`. Digest: `sha256:44576ab5bc386903dd592ed1f3e7277f60e0cd6c696590996d02330be2fbdbff`. All publication gates remained in place. This establishes publication recovery; these fixture changes address recurrence and still need to merge. ## Risks - Low risk. This changes test fixture startup only. - A persistent collision still fails after three attempts. Other failures retain their diagnostics and do not retry. Each recovered collision emits a warning in the test log. - Production listener selection is unchanged. This PR does not add a production server restart policy. - No documentation change is needed because the application contract does not change. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning effort and shell tools. The context window size is not exposed. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
65f429305e
commit
bc548a736a
4 files changed
+168
-41
No files matched your search
@@ -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<string, s
|
||||
}
|
||||
|
||||
async function stopServerProcess(child: ServerProcess | null) {
|
||||
if (!child || child.exitCode !== null) return;
|
||||
if (!child || child.exitCode !== null || child.signalCode !== null) return;
|
||||
child.kill("SIGTERM");
|
||||
await new Promise<void>((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);
|
||||
|
||||
|
||||
@@ -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<T>(startAttempt: () => Promise<T>): Promise<T> {
|
||||
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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> {
|
||||
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<void>((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<void>((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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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` },
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user