Public: anyone can read this; the crew can change it.

An agent's second clone of a repository borrows the objects already on disk instead of fetching them all again #3707

Closed opened this
Closed without merging

scout/forge:scout/3666-an-agent-s-second-clone-of-a-repository → main 3 commits fork 9 threads · 9 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +326 −2
src/actions/accounts.ts +2
@@ -23,6 +23,7 @@ import {
2323 setSuspended,
2424 type AccountRow,
2525 } from "../core/accounts.ts";
26 import { dropMirror } from "../crew/mirror.ts";
2627 import { deleteRepo as destroyRepo, listReposOwnedBy } from "../core/repos.ts";
2728 import { listActive } from "../core/runs.ts";
2829 import { getUserByName, type User } from "../core/users.ts";
@@ -184,6 +185,7 @@ async function removeOwnedRepos(
184185 const label = `${owner.username}/${repo.name}`;
185186 const deleted = await destroyRepo(app.db, app.reposRoot, repo);
186187 if (!deleted.ok) return label;
188 dropMirror(app.config.dataDir, repo.id);
outdated

No test covers this; removing the line breaks nothing. Add a check that removing the account deletes the mirror. Also consider not awaiting it here: it waits behind a running clone of the repository for up to 5 minutes.

187189 removed.push(label);
188190 if (owner.kind === "org")
189191 app.bus.append({
src/actions/repos.ts +2
@@ -20,6 +20,7 @@ import {
2020 updateLabel as writeLabel,
2121 type Label,
2222 } from "../core/issues.ts";
23 import { dropMirror } from "../crew/mirror.ts";
2324 import { accessAllows, getOrg, orgAccess } from "../core/orgs.ts";
2425 import {
2526 createRepo as initRepo,
@@ -502,6 +503,7 @@ export async function deleteRepo(
502503 if (!admin.ok) return admin;
503504 const deleted = await destroyRepo(app.db, app.reposRoot, repo);
504505 if (!deleted.ok) return deleted;
506 dropMirror(app.config.dataDir, repo.id);
outdated

This await holds up the delete until any running clone of the repository finishes, up to 5 minutes. The repository is already gone, so start the removal without awaiting it and log a failure.

505507 storageChanged(app, repo.ownerId);
506508 // The row is gone (events cascade with it), so this event carries no repo.
507509 app.bus.append({ kind: "repo.deleted", actorId: admin.value.id });
src/crew/mirror.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * A bare mirror of each repository, so a second clone of it borrows the
3 * objects already on disk. It lives at `<data>/crew/.mirrors/<repo id>`:
4 * one per repository id, never shared, so a private repository's objects
5 * never reach another's clone. The sandbox denies it with the other agents'
6 * directories (it is an entry of `crew/` that is not the agent's own).
7 *
8 * The clone borrows with `--reference-if-able` and `--dissociate`: it copies
9 * what it borrowed and keeps no link, so a deleted mirror breaks nothing. A
10 * mirror that cannot be fetched is skipped, and the clone is a plain one.
11 */
12
13 import { existsSync, mkdirSync, rmSync } from "node:fs";
14 import { join } from "node:path";
15 import { runGit } from "../git/env.ts";
16 import { createLog } from "../kernel/log.ts";
17 import { crewRoot } from "./workdir.ts";
18
outdated

High: nothing removes this directory when the repository is deleted, so a deleted private repository's objects stay on disk and in backups. Remove it in deleteRepo, running through exclusive(repo.id, …), and add a test for it.

19 const log = createLog("mirror");
20
21 export const mirrorDir = (dataDir: string, repoId: string): string =>
22 join(crewRoot(dataDir), ".mirrors", repoId);
23
24 // One chain per repository: two fetches into one mirror never overlap.
25 const chains = new Map<string, Promise<unknown>>();
26
27 function exclusive<T>(key: string, job: () => Promise<T>): Promise<T> {
28 const run = (chains.get(key) ?? Promise.resolve()).then(job, job);
29 const tail = run.catch(() => undefined);
30 chains.set(key, tail);
31 void tail.then(() => {
32 if (chains.get(key) === tail) chains.delete(key);
33 });
34 return run;
35 }
36
37 /** Fetch into the mirror, or rebuild it; the mirror's path, or undefined. Hold the chain. */
38 async function refresh(
39 dir: string,
40 url: string,
41 opts: { env: Record<string, string>; timeoutMs: number; signal?: AbortSignal },
42 ): Promise<string | undefined> {
43 if (existsSync(join(dir, "HEAD"))) {
44 const fetched = await runGit(
45 ["fetch", "--quiet", "--prune", "--force", url, "+refs/*:refs/*"],
46 { ...opts, cwd: dir },
outdated

A cancelled run also lands here and deletes a good mirror. If opts.signal?.aborted, return undefined without the rmSync.

47 );
48 if (fetched.ok) return dir;
49 // A cancelled fetch is not a broken mirror: keep what is good.
50 if (opts.signal?.aborted) return undefined;
51 rmSync(dir, { recursive: true, force: true });
outdated

Medium: this deletes the mirror while another run's clone (line 80, which runs outside the chain) may still be borrowing from it, and that clone then fails. Keep the borrowing clone inside the chain, or rebuild the mirror at a new path and rename it into place.

52 }
53 if (opts.signal?.aborted) return undefined;
54 mkdirSync(join(dir, ".."), { recursive: true });
55 const made = await runGit(
56 ["clone", "--quiet", "--mirror", "--", url, dir],
57 opts,
58 );
59 if (made.ok) return dir;
60 rmSync(dir, { recursive: true, force: true });
61 return undefined;
62 }
63
64 const validId = (repoId: string): boolean => /^[A-Za-z0-9_-]+$/.test(repoId);
65
66 /** Bring the repository's mirror up to date; the mirror's path, or undefined. */
67 export function refreshMirror(

Low (dead code): nothing in src/ calls this; only the tests do. Delete it and set the tests up with cloneWithMirror, or wire it to a real caller.

68 dataDir: string,
69 repoId: string,
70 url: string,
outdated

Low: there is no AbortSignal here, so a cancelled run waits up to five minutes for the mirror fetch. Pass through the signal that prepareClone already has.

71 env: Record<string, string>,
72 signal?: AbortSignal,
73 ): Promise<string | undefined> {
74 if (!validId(repoId)) return Promise.resolve(undefined);
75 return exclusive(repoId, () =>
76 refresh(mirrorDir(dataDir, repoId), url, {
77 env,
78 timeoutMs: 5 * 60_000,
79 ...(signal === undefined ? {} : { signal }),
80 }),
81 );
82 }
83
84 /**
85 * Delete the repository's mirror, through the same chain as the fetches, so
86 * one already running finishes first and none can recreate it afterwards (the
87 * repository is gone, so a later fetch fails).
88 */
89 export function removeMirror(dataDir: string, repoId: string): Promise<void> {

Nit: dropMirror is the only caller, so this doesn't need to be exported.

90 if (!validId(repoId)) return Promise.resolve();
91 return exclusive(repoId, async () => {
92 rmSync(mirrorDir(dataDir, repoId), { recursive: true, force: true });
93 });
94 }
95
96 /** `removeMirror` without waiting for it: a failure is logged, never thrown. */
97 export function dropMirror(dataDir: string, repoId: string): void {
98 removeMirror(dataDir, repoId).catch((error) =>
99 log.warn("a deleted repository's mirror would not go", {
100 repo: repoId,
101 error: String(error),
102 }),
103 );
104 }
105
106 /**
107 * `git clone` of `url` into `dir`, borrowing from the repository's mirror
108 * when there is one. The clone runs inside the chain: a rebuild of the mirror
109 * cannot delete it while it is being read.
110 */
111 export async function cloneWithMirror(input: {
112 dataDir: string;
113 repoId: string;
114 url: string;
115 dir: string;
116 env: Record<string, string>;
117 timeoutMs?: number;
118 signal?: AbortSignal;
119 }): ReturnType<typeof runGit> {
120 const opts = {
121 env: input.env,
122 timeoutMs: input.timeoutMs ?? 5 * 60_000,
123 ...(input.signal === undefined ? {} : { signal: input.signal }),
124 };
125 const plain = () =>
126 runGit(["clone", "--quiet", "--", input.url, input.dir], opts);
127 if (!validId(input.repoId)) return plain();
128 return exclusive(input.repoId, async () => {
129 const mirror = await refresh(mirrorDir(input.dataDir, input.repoId), input.url, opts);
130 if (mirror === undefined) return plain();
131 return runGit(
132 ["clone", "--quiet", "--reference-if-able", mirror, "--dissociate", "--", input.url, input.dir],
133 opts,
134 );
135 });
136 }
src/crew/runner.ts +7 −2
@@ -68,6 +68,7 @@ import {
6868 } from "../core/runs.ts";
6969 import { createToken, deleteToken } from "../core/tokens.ts";
7070 import { runGit } from "../git/env.ts";
71 import { cloneWithMirror } from "./mirror.ts";
7172 import { isSafeRef } from "../git/guard.ts";
7273 import { runGitCapture } from "../git/env.ts";
7374 import { looksForEnv } from "../core/looks.ts";
@@ -1653,9 +1654,13 @@ async function prepareClone(
16531654 if (!existsSync(join(dir, ".git"))) {
16541655 mkdirSync(dir, { recursive: true });
16551656 write(`cloning ${repo.ownerName}/${repo.name}`);
1656 const cloned = await runGit(["clone", "--quiet", "--", url, dir], {
1657 const cloned = await cloneWithMirror({
1658 dataDir: app.config.dataDir,
1659 repoId: repo.id,
1660 url,
1661 dir,
16571662 env,
1658 timeoutMs: 5 * 60_000,
1663 signal,
16591664 });
16601665 if (!cloned.ok)
16611666 return {
src/crew/sandbox.ts +2
@@ -236,6 +236,8 @@ export function sandboxPolicy(input: {
236236 ...others(data, "crew"),
237237 // Every agent but this one.
238238 ...others(crew, input.agentName),
239 // The mirrors, by name: one a later run creates is not in the listing.
240 join(crew, ".mirrors"),
239241 // This agent's other runs' temp directories.
240242 ...others(join(own, ".t"), tmpDir === undefined ? "" : basename(tmpDir)),
241243 // The machine's temp directory: every other session's files, and the
src/git/env.ts +6
@@ -236,6 +236,8 @@ export interface RunOptions {
236236 stdin?: Uint8Array | string;
237237 /** Kill the process after this long. @default 30_000 */
238238 timeoutMs?: number;
239 /** Kill the process when this aborts. */
240 signal?: AbortSignal;
239241 }
240242
241243 /** Run git to completion, capturing output as bytes. Non-zero exit is an Err. */
@@ -254,6 +256,9 @@ export async function runGitRaw(
254256
255257 const timeoutMs = options.timeoutMs ?? 30_000;
256258 const timer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
259 const stop = () => proc.kill("SIGKILL");
260 if (options.signal?.aborted) stop();
261 options.signal?.addEventListener("abort", stop, { once: true });
257262 try {
258263 const [stdout, stderr, code] = await Promise.all([
259264 readAll(proc.stdout),
@@ -264,6 +269,7 @@ export async function runGitRaw(
264269 return ok(stdout);
265270 } finally {
266271 clearTimeout(timer);
272 options.signal?.removeEventListener("abort", stop);
267273 }
268274 });
269275 }
test/crew-mirror.test.ts added +171
@@ -0,0 +1,171 @@
1 /** A second clone borrows from the repository's mirror; a deleted mirror breaks nothing. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { seedAdmin } from "./helpers/admin.ts";
8 import { promote } from "./helpers/members.ts";
9 import { removeAccount } from "../src/actions/accounts.ts";
10 import { runGit } from "../src/git/env.ts";
11 import { createApp } from "../src/app.ts";
12 import { createRepo, deleteRepo } from "../src/actions/repos.ts";
13 import { signUpProven as signUp } from "./helpers/verified.ts";
14 import { cloneWithMirror, mirrorDir, refreshMirror } from "../src/crew/mirror.ts";
15 import { sandboxPolicy } from "../src/crew/sandbox.ts";
16
17 let root: string;
18 let origin: string;
19 const data = () => join(root, "data");
20 const sh = (args: string[], cwd: string, env: Record<string, string> = {}) => {
21 const p = Bun.spawnSync(["git", ...args], {
22 cwd,
23 env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", ...env },
24 });
25 if (p.exitCode !== 0) throw new Error(p.stderr.toString());
26 };
27
28 beforeAll(() => {
29 root = mkdtempSync(join(tmpdir(), "mirror-"));
30 origin = join(root, "origin");
31 mkdirSync(origin);
32 sh(["init", "-q", "-b", "main"], origin);
33 Bun.write(join(origin, "a.txt"), "hello\n");
34 sh(["add", "."], origin);
35 sh(["commit", "-qm", "one"], origin);
36 });
37 afterAll(() => rmSync(root, { recursive: true, force: true }));
38
39 const wants = (trace: string) =>
40 readFileSync(trace, "utf8").split("\n").filter((l) => /packet:\s+fetch< want |packet:\s+clone> want /.test(l) || / want [0-9a-f]{40}/.test(l));
41
42 test("the second clone fetches no object the mirror already held", async () => {
43 const url = `file://${origin}`;
44 const first = await cloneWithMirror({ dataDir: data(), repoId: "r1", url, dir: join(root, "c1"), env: {} });
45 expect(first.ok).toBe(true);
46 expect(existsSync(join(mirrorDir(data(), "r1"), "HEAD"))).toBe(true);
47
48 const trace = join(root, "trace");
49 const second = await cloneWithMirror({
50 dataDir: data(), repoId: "r1", url, dir: join(root, "c2"),
51 env: { GIT_TRACE_PACKET: trace },
52 });
53 expect(second.ok).toBe(true);
54 // the mirror refresh asked for nothing new, and the clone wanted nothing
55 expect(wants(trace)).toEqual([]);
56 expect(readFileSync(join(root, "c2", "a.txt"), "utf8")).toBe("hello\n");
57 // dissociated: no link left to the mirror
58 expect(existsSync(join(root, "c2", ".git", "objects", "info", "alternates"))).toBe(false);
59 });
60
61 test("a deleted mirror still gives a good clone", async () => {
62 const url = `file://${origin}`;
63 await refreshMirror(data(), "r2", url, {});
64 const dir = join(root, "c3");
65 const cloned = await cloneWithMirror({ dataDir: data(), repoId: "r2", url, dir, env: {} });
66 expect(cloned.ok).toBe(true);
67 rmSync(mirrorDir(data(), "r2"), { recursive: true, force: true });
68 sh(["fsck", "--full"], dir);
69 expect(readFileSync(join(dir, "a.txt"), "utf8")).toBe("hello\n");
70 });
71
72 test("concurrent refreshes of one mirror both succeed", async () => {
73 const url = `file://${origin}`;
74 const [a, b] = await Promise.all([
75 refreshMirror(data(), "r3", url, {}),
76 refreshMirror(data(), "r3", url, {}),
77 ]);
78 expect(a).toBe(mirrorDir(data(), "r3"));
79 expect(b).toBe(a);
80 });
81
82 test("an agent's sandbox denies the mirrors", () => {
83 const policy = sandboxPolicy({ dataDir: data(), agentName: "scout", urls: [] });
84 expect(policy.denyRead).toContain(join(data(), "crew", ".mirrors"));
85 });
86
87 test("deleting a repository deletes its mirror", async () => {
88 const dataDir = join(root, "forge");
89 const app = createApp({ dataDir, port: 0 });
90 try {
91 const u = await signUp(app, { username: "carol", email: "[email protected]", password: "a-long-passphrase" });
92 if (!u.ok) throw new Error("signup failed");
93 promote(app.db, u.value);
94 const made = await createRepo(app, u.value, { name: "gone" });
95 if (!made.ok) throw new Error("repo failed");
96 await refreshMirror(dataDir, made.value.id, `file://${origin}`, {});
97 expect(existsSync(mirrorDir(dataDir, made.value.id))).toBe(true);
98 expect((await deleteRepo(app, u.value, made.value)).ok).toBe(true);
99 for (let i = 0; i < 40 && existsSync(mirrorDir(dataDir, made.value.id)); i++) await Bun.sleep(50);
100 expect(existsSync(mirrorDir(dataDir, made.value.id))).toBe(false);
101 } finally {
102 app.close();
outdated

This passes with the abort handling taken out of runGitRaw: file:///nonexistent fails either way. Abort a git that is actually running (or a clone that would succeed) and check it ends early, well before the timeout.

103 }
104 });
105
106 const gone = async (pid: number) => {
107 for (let i = 0; i < 40; i++) {
108 try {
109 process.kill(pid, 0);
110 } catch {
111 return true;
112 }
113 await Bun.sleep(50);
114 }
115 return false;
116 };
117
118 test("aborting a running git ends it early and leaves no process behind", async () => {
119 const pidFile = join(root, "pid");
120 const ctl = new AbortController();
121 setTimeout(() => ctl.abort(), 300);
122 const started = Date.now();
123 const result = await runGit(
124 ["clone", "--quiet", "--upload-pack", `echo $$ > ${pidFile}; exec cat #`, `file://${origin}`, join(root, "slow")],
125 { timeoutMs: 60_000, signal: ctl.signal },
126 );
127 expect(result.ok).toBe(false);
128 expect(Date.now() - started).toBeLessThan(10_000);
129 expect(await gone(Number(readFileSync(pidFile, "utf8").trim()))).toBe(true);
130 });
131
132 test("an already aborted signal stops a clone that would succeed", async () => {
133 const ctl = new AbortController();
134 ctl.abort();
135 const dir = join(root, "aborted");
136 const cloned = await cloneWithMirror({
137 dataDir: data(), repoId: "r4", url: `file://${origin}`, dir, env: {}, signal: ctl.signal,
138 });
139 expect(cloned.ok).toBe(false);
140 expect(existsSync(join(dir, "a.txt"))).toBe(false);
141 });
142
143 test("a cancelled refresh keeps a good mirror", async () => {
144 const url = `file://${origin}`;
145 await refreshMirror(data(), "r5", url, {});
146 const ctl = new AbortController();
147 ctl.abort();
148 expect(await refreshMirror(data(), "r5", url, {}, ctl.signal)).toBeUndefined();
149 expect(existsSync(join(mirrorDir(data(), "r5"), "HEAD"))).toBe(true);
150 });
151
152 test("removing an account deletes its repositories' mirrors", async () => {
153 const dataDir = join(root, "forge2");
154 const app = createApp({ dataDir, port: 0 });
155 try {
156 const admin = await seedAdmin(app, { username: "boss", email: "[email protected]", password: "a-long-passphrase" });
157 const dave = await signUp(app, { username: "dave", email: "[email protected]", password: "a-long-passphrase" });
158 if (!admin.ok || !dave.ok) throw new Error("signup failed");
159 promote(app.db, dave.value);
160 const made = await createRepo(app, dave.value, { name: "mine" });
161 if (!made.ok) throw new Error("repo failed");
162 await refreshMirror(dataDir, made.value.id, `file://${origin}`, {});
163 expect(existsSync(mirrorDir(dataDir, made.value.id))).toBe(true);
164 const removed = await removeAccount(app, admin.value, "dave");
165 expect(removed.ok).toBe(true);
166 for (let i = 0; i < 40 && existsSync(mirrorDir(dataDir, made.value.id)); i++) await Bun.sleep(50);
167 expect(existsSync(mirrorDir(dataDir, made.value.id))).toBe(false);
168 } finally {
169 app.close();
170 }
171 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs