mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process prepares native runs, renews every controller lease on timers, and serves every request > - On a run path, the server hashed the 31 MB runner binary with `readFileSync` (more than once per run), hashed provider packs and harness backups synchronously, and ran `tar` with `execFileSync` (timeouts up to 60 s, one with no timeout) > - On a slow disk, each of these calls freezes the whole process. A 103 s stall on a hosted instance lapsed every lease. The last event before that stall was immediately before a synchronous read and hash of the runner binary (see #20694 and #20709) > - This pull request moves those reads, hashes and archive commands off the event loop. It computes the runner binary digest once per boot > - The benefit is that a slow disk delays only the run that waits for it. Turns also start faster, because the runner binary is no longer re-read for every run ## Linked Issues or Issue Description Refs #20694, #20709 **What happened?** On a hosted instance, the server process stopped for 103 s without a restart. Every controller lease lapsed, and two tasks needed a manual Retry. The last run event before the gap was immediately before `matchesControllerRunnerArtifact`, which does `createHash("sha256").update(readFileSync(controllerRunnerBinary))`. Four workspace restores were running at the same time, and file I/O was very slow (a 43 s archive hash, 20 s snapshot decrypts). The trigger is not proven. But each synchronous call below blocks the event loop for as long as the disk is slow. **Expected behavior** File hashing and archive commands on a run path must not block the event loop. A slow disk must delay only the run that waits for it. **Steps to reproduce** 1. Make a remote runner binary slow to read (the test uses a FIFO whose writer waits), or make `tar` slow (the test puts a `tar` wrapper that sleeps first on `PATH`). 2. Call `resolveRemotePaperclipRunnerBinary`, `stageRemoteRunnerDirectory`, or `syncRemoteRunnerDirectoryOut` while a 10 ms timer runs. 3. Before this change, the timer stops for the whole slow step (814 ms, 1,764 ms and 3,379 ms). After this change, it keeps firing. ## What Changed - `server/src/services/native-runtime/off-loop-file-work.ts` (new): - `sha256FileStreamed` - `cachedFileSha256`: a streamed digest, reused while the file's device, inode, size, mtime and ctime do not change - `binaryTargetFromHeader`: reads 64 KiB; reads the rest of the file only when the header cannot answer, so the result equals `runnerBinaryTarget(readFileSync(path))` - `sha256DirectoryTreeStreamed` - `execFileBuffered`: `execFile` with stdin input, `maxBuffer`, `timeout` and `env`. It rejects on a non-zero exit, a timeout or a `maxBuffer` overflow, like `execFileSync`. - `native-session-executor.ts`: - `matchesControllerRunnerArtifact` uses `cachedFileSha256`. Each boot reads the binary once, not once or twice for every run. - The remote Claude daemon target is read from the binary header. - The bundled remote runner binary is checked by `verifiedBundledRemoteRunnerBinary`: the same checks and errors, with a cached digest. - Provider-pack upload verification uses the new `verifyRemoteProviderPackManifest`. It runs the same checks, in the same order, with the same errors. One generator drives both the sync and the streamed readers. - Harness backup build and verify on run paths use streamed digests (`buildNativeHarnessBackupManifestStreamed`, `verifyNativeHarnessBackupStreamed`). The digest format does not change. - `stageRemoteRunnerDirectory` (3 calls), `assertSafeRemoteCheckpointArchive` (3 calls) and the checkpoint extract use `execFileBuffered`, with the same arguments, timeouts and buffer limits. `stageRemoteRunnerFile` uses `readFile`. - `packages/paperclip-runner/src/live/runner-binary.ts`: the default daemon lookup (`resolvePackagedRunnerBinary`, used by the local and remote resolvers) classifies the daemon with `runnerBinaryFileTarget`. It reads the 64 KiB header, not the whole file. - `packages/paperclip-runner/src/live/bundled-remote-provider-pack.ts`: the release-manifest checks now live in one helper, `bundledRemoteRunnerRelease`. The sync `bundledRemoteRunnerBinary` and the server's streamed check both use it. - `native-codex-runner.ts`: - `resolveRemotePaperclipRunnerBinary` reads only the header. - The local `runnerDigest` uses `cachedFileSha256`. - New `verifiedBundledRemoteRunnerBinary`. **Ordering and atomicity.** I checked each converted call for code that relied on the sync call being atomic with respect to other runs: - **Checkpoint copy-back.** It extracts into a private `mkdtemp` directory. The replace sequence (`existsSync`, `rename`, `rename`, `rm`) stays synchronous, so no other run can see a half-installed checkpoint. This function already awaited a remote command before the extract, so this change adds no new interleaving with the target. - **Harness backup verify then restore.** The verify was sync, but the restore after it was already async. The window between them existed before. One owner serializes the turns of a session, so no other turn publishes a backup for that session while a turn verifies it. - **Staging and provider-pack hashing.** These read build-owned, immutable trees, or the private staging copies of a run. ## Verification - Red/green: `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/off-loop-file-work.test.ts` - With `native-session-executor.ts` and `native-codex-runner.ts` from `origin/master`: 3 failed. The longest timer gaps were 814 ms (runner binary target read), 1,764 ms (directory staging tar) and 3,379 ms (checkpoint list, size check and extract). - With this change: 6 passed. The gaps stay under 400 ms. The same file also checks the digest cache, the header fallback, and the `execFileSync`-like errors (exit code, timeout kill, `ERR_CHILD_PROCESS_STDIO_MAXBUFFER`). - `native-session-executor.test.ts`: - The streamed provider-pack verifier returns the same manifest as the sync reader, and rejects a changed asset tree with the same error. - The streamed harness backup manifest equals the sync one. - The streamed verify agrees with the sync verify, for a valid backup and for a corrupt one. - Run together: `native-session-executor`, `off-loop-file-work`, `native-codex-runner`, `setup-readiness`, `antigravity-connection-probe` (1,653 passed). `run-completion.test.ts` passed all 153 tests. Its `afterAll` embedded-Postgres cleanup timed out locally, which is not related to this change; CI runs it. - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. ## Risks - **Turn start.** This change adds no wait before `turn.start`; it removes work. The first run of a boot streams the runner binary once. Later runs reuse the digest after one `stat`. - **Cache staleness.** The cache keys on device, inode, size, mtime and ctime. An in-place rewrite changes mtime and ctime, and a replaced file changes its inode, so a changed binary is hashed again. - **stderr.** `execFileSync` wrote a child's stderr to the server's stderr. `execFileBuffered` captures it. Tar warnings no longer appear in server logs; errors and exit codes are unchanged. - **Persisted state.** No persisted shape changes. Old saved state and new code (and the reverse) read the same manifests and digests. - **Not converted in this PR:** small metadata syscalls (`existsSync`, `lstatSync`, `readdirSync`, small JSON reads and writes, renames) in the native state machines. Some of these rely on running synchronously. Also not converted: the sync harness backup verify inside the sync restart-authority checks, and the sync stamp verify in `native-harness-backup-storage.ts`. Both are listed for a follow-up. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use, shell, and code execution. ## 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 (code comments carry the contract) - [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 <noreply@anthropic.com>
142 lines
9.5 KiB
TypeScript
142 lines
9.5 KiB
TypeScript
import { access, mkdir, rm, stat } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { AdapterEnvironmentTestContext } from "@paperclipai/adapter-utils";
|
|
|
|
const mocks = vi.hoisted(() => ({ probe: vi.fn(), admission: vi.fn(), credentials: vi.fn(), copyBack: vi.fn(), remove: vi.fn(), turn: vi.fn(), warn: vi.fn() }));
|
|
vi.mock("../middleware/logger.js", () => ({ logger: { warn: mocks.warn } }));
|
|
vi.mock("../vendor/paperclip-runner/index.js", async original => ({
|
|
...await original<object>(), probeNativeRunnerEnvironment: mocks.probe,
|
|
}));
|
|
vi.mock("../services/native-runtime/acpx-qualification.js", () => ({ resolveAntigravityCandidateAdmission: mocks.admission }));
|
|
vi.mock("../services/native-runtime/antigravity-runner-credentials.js", () => ({
|
|
prepareAntigravityRunnerCredentials: mocks.credentials, antigravityCredentialTurn: mocks.turn,
|
|
}));
|
|
vi.mock("../services/native-runtime/native-codex-runner.js", () => ({
|
|
resolvePaperclipRunnerBinary: () => "/owned/runnerd",
|
|
resolvePaperclipRunnerBinaryAsync: async () => "/owned/runnerd",
|
|
}));
|
|
import { antigravityConnectionProbeFailure, testAntigravityConnection } from "../services/antigravity-connection-probe.js";
|
|
import { NativeEnvironmentProbeCleanupError, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js";
|
|
|
|
const model = "exact-google-model";
|
|
const admission = { agent: "antigravity", model, companyId: "company-1" };
|
|
const roots: string[] = [];
|
|
const context: AdapterEnvironmentTestContext = { companyId: "company-1", adapterType: "paperclip_runner",
|
|
config: { provider: "acpx", acpxAgent: "antigravity", model, env: { GEMINI_HOME: "/selected/provider", PATH: "/selected/bin" } },
|
|
managedAiCredentialHome: "/selected/provider", executionTarget: null,
|
|
};
|
|
const receipt = { provider: "acpx", providerDriver: "acpx_runtime", effectiveModel: model,
|
|
sessionAdmissionPassed: true, admissionOnly: true, helloProbePassed: false };
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.admission.mockReturnValue(admission);
|
|
mocks.credentials.mockImplementation(async input => ({ environment: { ...input.environment, PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "fixture-managed-credential" }, home: "/selected/provider", credential: "fixture-managed-credential" }));
|
|
mocks.turn.mockImplementation(() => ({ copyBack: mocks.copyBack, remove: mocks.remove }));
|
|
mocks.probe.mockImplementation(async options => {
|
|
roots.push(options.runtimeDirectory);
|
|
await options.onCleanupConfirmed();
|
|
return receipt;
|
|
});
|
|
});
|
|
afterEach(async () => {
|
|
vi.unstubAllEnvs();
|
|
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
describe("Google Antigravity setup admission", () => {
|
|
it("reports the observed installation failure with a repair action and only closed server diagnostics", () => {
|
|
const privateValue = "fixture-private-token /private/selected-google-home";
|
|
const error = new Error(privateValue);
|
|
Object.defineProperty(error, "runnerCommandResult", { value: { commandType: "session.open", status: "failed", request: privateValue,
|
|
result: { code: "command_execution_failed", message: "failed to start ACPX provider: ACPX sidecar command session.open was rejected (retryable=false, classification=admission_installation)" } } });
|
|
const result = antigravityConnectionProbeFailure("company-1", error);
|
|
expect(result).toMatchObject({ status: "fail", checks: [{ code: "antigravity_installation_check_failed",
|
|
message: "Paperclip could not complete the local Google Antigravity installation check.", hint: expect.stringContaining("instance operator") }] });
|
|
expect(mocks.warn).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", code: "antigravity_installation_check_failed",
|
|
errorClass: "Error", commandCode: "command_execution_failed", classification: "admission_installation", retryable: false },
|
|
"Antigravity installation check failed before account verification");
|
|
expect(JSON.stringify([result, mocks.warn.mock.calls])).not.toMatch(/fixture-private-token|\/private\/selected-google-home/);
|
|
expect(JSON.stringify(result)).not.toMatch(/reconnect|sign in/i);
|
|
});
|
|
|
|
it("does not parse outer serialized errors or copy unknown codes, classes or native output", () => {
|
|
const privateValue = "fixture-private-token /private/selected-google-home";
|
|
for (const native of [{ code: privateValue, message: privateValue }, { code: "command_execution_failed",
|
|
message: "failed to start ACPX provider: ACPX sidecar command session.open was rejected (retryable=false, classification=admission_installation)" + privateValue }]) {
|
|
const nativeMessage = native.message;
|
|
const error = new Error(`PRP command session.open failed: ${nativeMessage}`);
|
|
error.name = privateValue;
|
|
Object.defineProperty(error, "runnerCommandResult", { value: { commandType: "session.open", status: "failed",
|
|
result: native } });
|
|
const result = antigravityConnectionProbeFailure("company-1", error);
|
|
expect(result.checks[0].code).toBe("antigravity_admission_failed");
|
|
expect(JSON.stringify([result, mocks.warn.mock.calls])).not.toMatch(/fixture-private-token|\/private\/selected-google-home/);
|
|
}
|
|
const rawOnly = new Error('PRP command session.open failed: {"code":"command_execution_failed","classification":"admission_installation"}');
|
|
expect(antigravityConnectionProbeFailure("company-1", rawOnly).checks[0].code).toBe("antigravity_admission_failed");
|
|
});
|
|
|
|
it("preserves physical cleanup ownership instead of converting its typed error into a connection result", () => {
|
|
const retired = Promise.resolve();
|
|
const error = new NativeEnvironmentProbeCleanupError(retired, new Error("fixture-private-token"), [new Error("fixture private path")]);
|
|
expect(() => antigravityConnectionProbeFailure("company-1", error)).toThrow(error);
|
|
expect(mocks.warn).not.toHaveBeenCalled();
|
|
expect(error.retired).toBe(retired);
|
|
});
|
|
|
|
it("uses the selected managed account, exact candidate and a private runtime without a model turn", async () => {
|
|
vi.stubEnv("GEMINI_API_KEY", "ambient-key-must-not-enter");
|
|
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", "/ambient-google-credential");
|
|
const order: string[] = [];
|
|
mocks.copyBack.mockImplementation(async () => { order.push("copy-back"); });
|
|
mocks.remove.mockImplementation(async () => { order.push("scrub"); });
|
|
let root = "";
|
|
mocks.probe.mockImplementation(async options => {
|
|
root = options.runtimeDirectory; roots.push(root);
|
|
expect((await stat(root)).mode & 0o777).toBe(0o700);
|
|
expect((await stat(options.transportOptions.acpxRuntimeDirectory)).mode & 0o777).toBe(0o700);
|
|
expect(options).toMatchObject({ provider: "acpx", model, admissionOnly: true,
|
|
environment: { PATH: "/selected/bin", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "fixture-managed-credential" },
|
|
transportOptions: { runnerBinary: "/owned/runnerd", acpxAgent: "antigravity", acpxCandidateAdmission: admission,
|
|
acpxPermissionMode: "approve-reads", acpxPermissionModePinned: true } });
|
|
expect(options.environment.GEMINI_API_KEY).toBeUndefined();
|
|
expect(options.environment.GOOGLE_APPLICATION_CREDENTIALS).toBeUndefined();
|
|
const identity = options.transportOptions.prpIdentity;
|
|
const nativeHome = join(await resolveAcpxRuntimeRoot(options.transportOptions.acpxRuntimeDirectory, identity.normalizedSessionId), "antigravity-home");
|
|
expect(mocks.turn).toHaveBeenCalledWith({ managedHome: "/selected/provider", runtimeHome: nativeHome, credential: "fixture-managed-credential" });
|
|
await mkdir(nativeHome, { recursive: true });
|
|
order.push("retired");
|
|
await options.onCleanupConfirmed();
|
|
await expect(access(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
return receipt;
|
|
});
|
|
const result = await testAntigravityConnection(context, model);
|
|
expect(result.status).toBe("pass");
|
|
expect(result.checks).toContainEqual(expect.objectContaining({ code: "antigravity_metadata_verified" }));
|
|
expect(mocks.admission).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", model });
|
|
expect(mocks.credentials).toHaveBeenCalledWith(expect.objectContaining({ managedHome: "/selected/provider", remote: false, lifecycleMode: "per_turn" }));
|
|
expect(order).toEqual(["retired", "copy-back", "scrub"]);
|
|
});
|
|
|
|
it.each(["effectiveModel", "providerDriver", "sessionAdmissionPassed", "admissionOnly", "helloProbePassed"] as const)("rejects a mismatched %s receipt after cleanup", async field => {
|
|
mocks.probe.mockImplementation(async options => {
|
|
roots.push(options.runtimeDirectory);
|
|
await options.onCleanupConfirmed();
|
|
return { ...receipt, [field]: typeof receipt[field] === "string" ? "different" : !receipt[field] };
|
|
});
|
|
await expect(testAntigravityConnection(context, model)).rejects.toThrow("no matching account and model admission receipt");
|
|
expect(mocks.copyBack).toHaveBeenCalledOnce();
|
|
expect(mocks.remove).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("rejects an unavailable company or remote target before reading credentials or launching native code", async () => {
|
|
mocks.admission.mockReturnValue(undefined);
|
|
await expect(testAntigravityConnection(context, model)).rejects.toThrow("not available for this company");
|
|
await expect(testAntigravityConnection({ ...context, executionTarget: { kind: "remote" } as AdapterEnvironmentTestContext["executionTarget"] }, model))
|
|
.rejects.toThrow("requires the Paperclip host");
|
|
expect(mocks.credentials).not.toHaveBeenCalled();
|
|
expect(mocks.probe).not.toHaveBeenCalled();
|
|
});
|
|
});
|