mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
fix(workspaces): clone network repositories blobless in remote sandboxes (#23347)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A Paperclip Runner task in a Cloud sandbox gets a fresh workspace: the server clones the task's repositories into the sandbox before the agent starts > - The clone is a full clone, so it downloads every historical blob. A full clone of `paperclipai/paperclip` now grows the disk by about 856 MiB > - The Cloud sandbox wraps Git in a storage guard. The guard stops one Git command when the net disk growth gets to 1 GiB, and the growth includes other writers on the same disk > - On hosted staging, the clone now stops with `stage=clone disk=full git=storage_limit exit=75`. Paperclip records `sandbox_disk_full`, the run fails during setup, and the task does not start. This happens more frequently as the repository history grows > - This pull request makes a fresh clone from a network remote blobless (`--filter=blob:none`). The clone gets all commits and trees, but only the file contents that the checkout needs > - Agent commands that the managed GitHub launcher treats as local (`git show`, `git blame`, `git log -p`, checkout) do not ask the credential broker. In a blobless clone they can need to fetch an old blob, which fails for a private repository without credentials. So the launcher now gives these commands the broker credential on demand, at most once per command > - The benefit is that the same clone grows the disk by about 409 MiB and takes less than half the time, so large repositories start again in Cloud sandboxes ## Linked Issues or Issue Description Refs #22848 (classifies the Git storage guard refusal during clone as a full sandbox disk; this PR removes the cause of that refusal for large histories) Refs #22837 (moves a restore off a full reused sandbox; the clone path in this PR is a fresh sandbox, so a new sandbox does not help) **What happened?** On hosted staging, Paperclip Runner runs fail before the agent starts. The run error is `remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=clone disk=full git=storage_limit exit=75 program=git` (and the same refusal with `operation=repository` for a secondary repository). The error code is `sandbox_disk_full`. Between 2026-11-27 and 2026-11-30 there were 20 such failures for three different agents. The tasks used fresh workspaces for `paperclipai/paperclip` with `paperclipai/paperclip-cloud` as a secondary repository. **Expected behavior** A fresh sandbox workspace for a large repository starts without hitting the sandbox Git storage budget. **Steps to reproduce** 1. Run `git clone --no-hardlinks https://github.com/paperclipai/paperclip.git` and measure the disk growth. I measured 856 MiB (39 s). 2. Compare with the Cloud sandbox Git storage guard budget: it stops one Git command at 1 GiB of net disk growth, and it counts other writers on the same disk. 3. Run the same clone with `--filter=blob:none`. I measured 409 MiB (17 s). **Paperclip version or commit** `master` at `c737187ec7`. The hosted staging failures were on releases `635ed5a364`, `c49e80da6c`, `629281b1e8`, `e55b475f30` and `bc98abda0c`. **Deployment mode** Hosted Cloud, Paperclip Runner with remote sandbox workspaces. ## What Changed - `server/src/services/remote-workspace-transport.ts`: - The primary workspace clone (`prepareRemoteWorkspaceDirectory`) and the secondary repository clone (`prepareRemoteRepository`) add `--filter=blob:none` when the repository URL is a network remote (`https`, `http`, `ssh`, `git`, or `user@host:path`). - The staged checkout steps after the clone (`checkout_branch`, `checkout_ref`) use the clone's credentials. Checkout of a revision other than the default branch can fetch missing blobs from the origin. Without credentials, that fetch fails for a private repository. The checks after publication still run without credentials. - A local path or `file://` origin stays a full clone. A saved workspace keeps only a promisor remote whose URL works on another machine, so a partial clone of a local origin cannot be saved. - A server that does not support filters ignores the filter and sends a full clone, so the old behavior stays available. - `server/src/services/remote-workspace-transport.test.ts`: a real-subprocess regression with a history-only blob and an origin that is reachable only through the clone credentials. It checks the blobless clone, the fetch of an older revision's files with credentials, the full clone of a local origin, and a save and restore of the blobless clone after the origin is removed. - `packages/adapter-utils/src/github-launcher.ts` (managed `git`/`gh` launcher): a local `git` command (one that does not ask the broker since #17886) now runs with the launcher as `GIT_ASKPASS`, when the launcher has a broker capability and is not anonymous. - Git calls askpass only after every credential helper declines, for example on a lazy fetch of a missing blob from a private repository. Askpass was not used before, so a lazy fetch failed with `could not read Username for 'https://github.com'`. - The launcher answers only prompts for `https://github.com` and `https://www.github.com`. It answers `x-access-token` for the username without the broker. For the password, it asks the broker. - The command's launcher keeps the first broker answer in memory and serves later prompts through a Unix socket in a private (`0700`) temporary directory. So one command asks the broker at most once, however many objects Git fetches. A command that fetches nothing does not ask the broker, as before. If the socket cannot be created, each prompt asks the broker itself. - The recursion guard still rejects every launcher invocation inside an operation, except an askpass prompt inside a local operation (which holds no credential). - I used askpass instead of a URL-scoped `credential.helper`, because a Git wrapper that adds its own `credential.<url>.helper` reset (as the Paperclip tools Git bundle does through `-c include.path`) is applied after the launcher's `GIT_CONFIG_*` entries and would remove the helper. `GIT_ASKPASS` takes priority over any `core.askPass` configuration. - `packages/adapter-utils/src/github-launcher.test.ts`: launcher tests with real Git. A local command runs `git credential fill` three times for a GitHub URL. The test checks that the managed token is returned with one broker request, that `git status` makes no request, that another host gets no answer and no request, and both broker modes (inherited URL and broker file). A second test checks that askpass is set only for local commands of a connected, non-anonymous launcher, and that the recursion guard still rejects other re-entries. - `doc/workspace-storage.md`: a note about the blobless clone. `doc/execution-github-identity.md`: the askpass behavior for local commands. ## Verification - Red: on the unfixed code, the new test fails because the clone downloads the history-only blob (`expected [] to include '<blob>'`). - A second red: with the filter but without credentials for the checkout steps, the test fails with `stage=checkout_ref git=network exit=128`. This proves that the test also covers the private-repository case. - Green: `pnpm --filter @paperclipai/server exec vitest run src/services/remote-workspace-transport.test.ts src/services/remote-workspace-readonly-capture-cause.test.ts src/services/remote-workspace-readonly-inventory-git-guard.test.ts src/services/remote-workspace-restore-disk-full.test.ts` passes (201 tests). - `src/services/remote-workspaces.integration.test.ts`, `remote-workspace-lifecycle.test.ts` and `remote-workspace-migration.test.ts` pass (347 passed, 16 skipped; the integration file skips locally). - `pnpm --filter @paperclipai/server typecheck` passes. - Launcher, red/green: without the launcher change, the 3 new launcher tests fail. With it, `src/github-launcher.test.ts` passes (44 tests). `github-launcher.test.ts`, `github-launcher-environment.test.ts` and `sandbox-callback-bridge.test.ts` in adapter-utils pass (175 tests). `packages/paperclip-runner` `src/drivers/acpx/github-launcher.test.ts` (3) and server `heartbeat-github-launchers.test.ts` (12) pass. `tsc --noEmit` passes in `packages/adapter-utils`. - Launcher, real private repository: I made a blobless clone of a private GitHub repository and ran the generated launcher with a local fake broker that returned a real GitHub token. With the old launcher, `git show <old commit>:README.md` failed with `could not read Username for 'https://github.com': terminal prompts disabled` / `could not fetch <blob> from promisor remote`. With the new launcher, it printed the file with 1 broker request. On a fresh blobless clone, `git log -p -40 -- README.md` (about 150 lazy fetches in the trace) made 1 broker request, and `git status` made 0. - Measurement on a Linux host: a full clone of `paperclipai/paperclip` grows the disk by 856 MiB; a blobless clone grows it by 409 MiB. - Not run: a live Cloud sandbox run. Hosted staging gets this change through the normal automatic deployment. After that deployment, the Sentry case gets a check that new fresh workspaces for this repository start without the refusal. - Local environment note: the tests rewrite the remote URL through `GIT_CONFIG_COUNT`. A Git wrapper first on `PATH` that sets its own `GIT_CONFIG_COUNT` makes the rewrite tests fail, also on `master`. I ran the tests with the system Git first on `PATH`. ## Risks - A blobless clone fetches file contents from the origin when an agent command needs old blobs (for example `git log -p`, `git blame`, or a checkout of another branch). These commands need network access and the run's Git credentials, the same as `git fetch`. The launcher now supplies the credential on demand (one broker request per command that needs it). The Cloud Git storage guard already measures these lazy downloads. - While a local `git` command runs, a process of the same user can read the password from the askpass socket. That user can already get the token with `gh auth token`, so this adds no new access. The token is not written to disk. - A saved workspace of a blobless clone keeps its promisor remote. The existing snapshot capture and restore support this. The new test proves a save and restore after the origin is removed. - Medium-low risk: the clone of a repository on a server without filter support is unchanged (Git ignores the filter). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use (shell, code execution) in Claude Code. ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
6 files changed
+293
-11
No files matched your search
@@ -2289,4 +2289,71 @@ return result};`);
|
||||
ref: "HEAD~1", pinnedCommit: receipt.pinnedCommit, resolveGitAuth: unavailableAuth })).resolves.toEqual(receipt);
|
||||
expect(unavailableAuth).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clones without history-only blobs and fetches an older revision's files with the clone credentials", async () => {
|
||||
// A full clone downloads every historical blob. In a Cloud sandbox that alone
|
||||
// can spend Git's per-command storage budget, so the clone fails with a full disk.
|
||||
const origin = await repository({ revisions: true });
|
||||
await fs.writeFile(path.join(origin, "history-only.bin"), randomBytes(64 * 1024));
|
||||
await git(origin, "add", "history-only.bin");
|
||||
await git(origin, "commit", "-m", "History-only blob");
|
||||
const historyBlob = (await git(origin, "rev-parse", "HEAD:history-only.bin")).stdout.trim();
|
||||
await git(origin, "rm", "-q", "history-only.bin");
|
||||
await git(origin, "commit", "-m", "Remove history-only blob");
|
||||
await git(origin, "config", "uploadpack.allowFilter", "true");
|
||||
// The origin is reachable only through the credential rewrite, like a private repository.
|
||||
const remoteUrl = "ssh://git@127.0.0.1:1/synthetic-partial-repository";
|
||||
const resolveGitAuth = async () => ({ configArgs: [], env: { GIT_CONFIG_COUNT: "1",
|
||||
GIT_CONFIG_KEY_0: `url.${pathToFileURL(origin).href}.insteadOf`, GIT_CONFIG_VALUE_0: remoteUrl },
|
||||
source: "company_secret" as const, secretName: "SYNTHETIC_FIXTURE" });
|
||||
const { remote } = target();
|
||||
const missingObjects = async (repo: string) => (await git(repo, "rev-list", "--objects", "--missing=print", "--all"))
|
||||
.stdout.split("\n").filter(line => line.startsWith("?")).map(line => line.slice(1));
|
||||
|
||||
const root = path.join(workspace, "partial-root");
|
||||
await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, preparationIdentity: "b".repeat(64),
|
||||
source: { kind: "git", repoUrl: remoteUrl, ref: "HEAD" }, resolveGitAuth });
|
||||
expect(await missingObjects(root)).toContain(historyBlob);
|
||||
expect((await git(root, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true");
|
||||
await expect(fs.access(path.join(root, "history-only.bin"))).rejects.toThrow();
|
||||
|
||||
// An older configured revision needs a blob the clone left on the server.
|
||||
const older = path.join(workspace, "partial-older-root");
|
||||
await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: older, preparationIdentity: "c".repeat(64),
|
||||
source: { kind: "git", repoUrl: remoteUrl, ref: "HEAD~1" }, resolveGitAuth });
|
||||
expect((await fs.readFile(path.join(older, "history-only.bin"))).length).toBe(64 * 1024);
|
||||
|
||||
const nested = path.join(workspace, "partial-repository");
|
||||
const receipt = await prepareRemoteRepository({ target: remote, remoteCwd: nested, repoUrl: remoteUrl,
|
||||
ref: "HEAD~1", resolveGitAuth });
|
||||
expect((await fs.readFile(path.join(nested, "history-only.bin"))).length).toBe(64 * 1024);
|
||||
expect((await git(nested, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true");
|
||||
expect(receipt.pinnedCommit).toMatch(/^[a-f0-9]{40}$/);
|
||||
|
||||
// A local origin stays a full clone: a saved workspace cannot keep a promisor
|
||||
// remote that only exists on this machine.
|
||||
const local = path.join(workspace, "partial-local-origin");
|
||||
await prepareRemoteRepository({ target: remote, remoteCwd: local, repoUrl: pathToFileURL(origin).href,
|
||||
ref: "HEAD", resolveGitAuth: async () => null });
|
||||
expect(await missingObjects(local)).toEqual([]);
|
||||
await expect(git(local, "config", "--get", "remote.origin.promisor")).rejects.toThrow();
|
||||
|
||||
// The blobless clone is saved and restored with its promisor remote; the
|
||||
// restore does not need the origin.
|
||||
await fs.writeFile(path.join(root, "source.txt"), "agent edit in a blobless clone\n");
|
||||
const captured = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: root, operationId: randomUUID() });
|
||||
try {
|
||||
await fs.rm(origin, { recursive: true });
|
||||
const restoredRoot = path.join(scratch, "partial-saved-root");
|
||||
const restored = await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: restoredRoot,
|
||||
archivePath: captured.archivePath, manifestDigest: captured.manifestDigest, restorationIdentity: "d".repeat(64) });
|
||||
await cleanupRemoteWorkspaceArchive({ target: remote, remoteCwd: restored.stagingRoot, operationId: restored.operationId });
|
||||
expect(await fs.readFile(path.join(restoredRoot, "source.txt"), "utf8")).toBe("agent edit in a blobless clone\n");
|
||||
expect((await git(restoredRoot, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true");
|
||||
expect((await git(restoredRoot, "config", "--get", "remote.origin.url")).stdout.trim()).toBe(remoteUrl);
|
||||
expect(await missingObjects(restoredRoot)).toContain(historyBlob);
|
||||
expect((await git(restoredRoot, "rev-parse", "HEAD")).stdout.trim())
|
||||
.toBe((await git(root, "rev-parse", "HEAD")).stdout.trim());
|
||||
} finally { await captured.cleanup(); }
|
||||
});
|
||||
});
|
||||
@@ -355,6 +355,25 @@ export async function removeRemoteRecoveryAttachment(input: {
|
||||
return output === "removed";
|
||||
}
|
||||
|
||||
// A fresh clone from a network remote is blobless (--filter=blob:none): it gets
|
||||
// every commit and tree, but only the file contents a checkout needs. A full
|
||||
// clone also downloads every historical blob, which alone can exceed a Cloud
|
||||
// sandbox's per-command Git storage budget. Checkout of another revision can
|
||||
// fetch missing blobs, so the staged checkout steps use the clone's credentials.
|
||||
// A server without filter support ignores the filter and sends a full clone.
|
||||
// A local path or file:// origin is cloned in full: a saved workspace keeps
|
||||
// only a promisor remote whose URL works on another machine.
|
||||
function bloblessCloneSource(repoUrl: string): boolean {
|
||||
if (!repoUrl || /[\u0000-\x20\u007f\\]/u.test(repoUrl)) return false;
|
||||
if (/^[a-z][a-z0-9+.-]*:\/\//iu.test(repoUrl)) {
|
||||
try {
|
||||
const url = new URL(repoUrl);
|
||||
return ["http:", "https:", "ssh:", "git:"].includes(url.protocol) && Boolean(url.hostname);
|
||||
} catch { return false; }
|
||||
}
|
||||
return !/^[a-z]:[\/\\]/iu.test(repoUrl) && /^(?:[a-z0-9._-]+@)?(?:[a-z0-9._-]+|\[[a-f0-9:]+\]):[^\s]+$/iu.test(repoUrl);
|
||||
}
|
||||
|
||||
const PREPARE = String.raw`
|
||||
const fs = require('node:fs/promises'), path = require('node:path'), cp = require('node:child_process');
|
||||
const {promisify}=require('node:util'); const exec=promisify(cp.execFile);
|
||||
@@ -365,7 +384,6 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid
|
||||
const noConfig={GIT_TERMINAL_PROMPT:'0',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_SYSTEM:'/dev/null',GIT_CONFIG_COUNT:'0',GIT_CONFIG_PARAMETERS:'',GIT_TEMPLATE_DIR:'',GIT_ASKPASS:'',SSH_ASKPASS:''};
|
||||
const isolated={...process.env,...noConfig};for(const key of Object.keys(isolated))if(/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key))delete isolated[key];
|
||||
const cloneEnv={...isolated};for(const key of input.authEnvKeys)if(/^GIT_CONFIG_(COUNT|(KEY|VALUE)_\d+)$/.test(key)&&process.env[key]!==undefined)cloneEnv[key]=process.env[key];
|
||||
const localEnv={...isolated};for(const key of input.authEnvKeys)delete localEnv[key];Object.assign(localEnv,noConfig);
|
||||
stage='create_parent';let current='/'; for(const part of path.dirname(root).split('/').filter(Boolean)) {
|
||||
current=path.join(current,part); await fs.mkdir(current,{mode:0o700}).catch(e=>{if(e.code!=='EEXIST')throw e});
|
||||
const s=await fs.lstat(current); if(!s.isDirectory()||s.isSymbolicLink())throw Error('unsafe_root');
|
||||
@@ -383,8 +401,8 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid
|
||||
stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');let published=false;
|
||||
try{
|
||||
if(input.kind==='git'){
|
||||
stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks','--',input.repoUrl,staged],{env:cloneEnv});
|
||||
const git=async args=>exec('git',['-c','core.hooksPath=/dev/null','-C',staged,...args],{env:localEnv});
|
||||
stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks',...(input.blobless?['--filter=blob:none']:[]),'--',input.repoUrl,staged],{env:cloneEnv});
|
||||
const git=async args=>exec('git',['-c','core.hooksPath=/dev/null',...input.authArgs,'-C',staged,...args],{env:cloneEnv});
|
||||
if(input.branchMode==='existing'){
|
||||
stage='checkout_branch';if(!input.branchName)throw Error('existing_branch_required');
|
||||
await git(['check-ref-format','--branch',input.branchName]);
|
||||
@@ -425,6 +443,7 @@ export async function prepareRemoteWorkspaceDirectory(input: {
|
||||
const auth = input.source.kind === "git" ? await input.resolveGitAuth(input.source.repoUrl) : null;
|
||||
const output = await command(input.target, "prepare", ["-e", PREPARE, input.remoteCwd,
|
||||
JSON.stringify({ ...input.source, preparationIdentity: input.preparationIdentity,
|
||||
blobless: input.source.kind === "git" && bloblessCloneSource(input.source.repoUrl),
|
||||
authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env);
|
||||
const result = JSON.parse(output) as { cwd: string };
|
||||
if (result.cwd !== input.remoteCwd) throw new Error("remote_workspace_root_changed");
|
||||
@@ -458,8 +477,8 @@ export async function prepareRemoteRepository(input: {
|
||||
if(existing){if(!existing.isDirectory()||existing.isSymbolicLink())throw Error('unsafe_repository')}
|
||||
else{if(input.verifyOnly||input.savedArchive)throw Error('repository_missing');if(input.probeOnly){process.stdout.write(JSON.stringify({cloneRequired:true}));return;}
|
||||
stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');try{
|
||||
stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks','--',input.repoUrl,staged],{env:cloneEnv});
|
||||
const git=async args=>exec('git',['-c','core.hooksPath=/dev/null','-C',staged,...args],opts);
|
||||
stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks',...(input.blobless?['--filter=blob:none']:[]),'--',input.repoUrl,staged],{env:cloneEnv});
|
||||
const git=async args=>exec('git',['-c','core.hooksPath=/dev/null',...input.authArgs,'-C',staged,...args],{env:cloneEnv});
|
||||
stage='checkout_ref';
|
||||
${checkoutConfiguredRefScript}
|
||||
stage='publish';await fs.rename(staged,root);
|
||||
@@ -483,7 +502,8 @@ export async function prepareRemoteRepository(input: {
|
||||
}
|
||||
const auth = await input.resolveGitAuth(input.repoUrl);
|
||||
const output = await command(input.target, "repository", ["-e", script, input.remoteCwd,
|
||||
JSON.stringify({ ...payload, authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env);
|
||||
JSON.stringify({ ...payload, blobless: bloblessCloneSource(input.repoUrl),
|
||||
authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env);
|
||||
const value = JSON.parse(output) as { cwd: string; pinnedCommit: string; branchName: string | null };
|
||||
if (value.cwd !== input.remoteCwd || !/^[a-f0-9]{40,64}$/.test(value.pinnedCommit)) throw new Error("remote_workspace_repository_receipt_invalid");
|
||||
return value;
|
||||
|
||||
Reference in new issue
Block a user