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

Runner jobs' git-upload-pack: count the work per job, then cut it so the serving thread is not held #17984

opened this

Merged 17h 14m ago, live in production

torque/forge:torque/17975-runner-jobs-git-upload-pack-count-the-wo → main 0 commits fork

  • Merged. torque/17975-runner-jobs-git-upload-pack-count-the-wo was merged into main as ee5308f.

Review

Sign in to review this change.
9 files changed +647 −16
src/git/fetch_work.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The work the forge does to serve one fetch (#17975): the git processes it spawns for it, the
3 * waits its handler makes before it can answer and the bytes it reads synchronously. A runner
4 * job's fetch is counted and the count is said in the run's log, so a stall that comes back from
5 * this door is named by its numbers.
6 *
7 * Each number is counted where the thing happens, never added by hand: a process where it is
8 * spawned (`notedProcess`), a wait where it is awaited (`waited`, at the leaf waits: a body read,
9 * a permit, a git question, a disk operation), a synchronous read where it is read
10 * (`notedSyncRead`). The work is carried by the async context into what the fetch calls, never by
11 * a module-level collection; outside a counted fetch every one of these does nothing.
12 */
13
14 import { AsyncLocalStorage } from "node:async_hooks";
15
16 export interface FetchWork {
17 /** git processes spawned to answer this fetch. */
18 processes: number;
19 /** Waits the handler made (`waited`) before its answer could start. */
20 awaits: number;
21 /** Milliseconds those waits took, end to end. */
22 waitedMs: number;
23 /** Bytes read with a synchronous call while the fetch was served: each held the thread. */
24 syncBytes: number;
25 /** Served from an answer another job's fetch built (`pack_share.ts`), nothing built for it. */
26 shared: boolean;
27 }
28
29 const counting = new AsyncLocalStorage<FetchWork>();
30
31 export function newFetchWork(): FetchWork {
32 return { processes: 0, awaits: 0, waitedMs: 0, syncBytes: 0, shared: false };
33 }
34
35 /** Run `fn` with everything it does counted into `work` (nothing when `work` is undefined). */
36 export function countingWork<T>(work: FetchWork | undefined, fn: () => Promise<T>): Promise<T> {
37 return work === undefined ? fn() : counting.run(work, fn);
38 }
39
40 /** One git process was spawned for the fetch now running, if one is being counted. */
41 export function notedProcess(): void {
42 const work = counting.getStore();
43 if (work !== undefined) work.processes++;
44 }
45
46 /** `bytes` were read synchronously for the fetch now running, if one is being counted. */
47 export function notedSyncRead(bytes: number): void {
48 const work = counting.getStore();
49 if (work !== undefined) work.syncBytes += bytes;
50 }
51
52 /** Await `pending`, counting the wait and its time into the fetch now running, if any. */
53 export async function waited<T>(pending: Promise<T>): Promise<T> {
54 const work = counting.getStore();
55 if (work === undefined) return pending;
56 const from = performance.now();
57 try {
58 return await pending;
59 } finally {
60 work.awaits++;
61 work.waitedMs += performance.now() - from;
62 }
63 }
64
65 /** The log line: `git fetch: built, 2 processes, 3 awaits (14 ms), 0 bytes read synchronously`. */
66 export function workWords(what: string, work: FetchWork): string {
67 const processes = `${work.processes} process${work.processes === 1 ? "" : "es"}`;
68 const awaits = `${work.awaits} await${work.awaits === 1 ? "" : "s"} (${Math.round(work.waitedMs)} ms)`;
69 const sync = `${work.syncBytes} byte${work.syncBytes === 1 ? "" : "s"} read synchronously`;
70 const how = work.shared ? "shared, the answer another job's fetch built" : "built";
71 return `${what}: ${how}, ${processes}, ${awaits}, ${sync}`;
72 }
src/git/own_refs.ts +6 −2
@@ -35,6 +35,7 @@ import { closeSync, openSync, readdirSync, readSync } from "node:fs";
3535 import { join } from "node:path";
3636 import { sliced } from "../kernel/breathe.ts";
3737 import { Gate, gitEnv, gitGate } from "./env.ts";
38 import { notedProcess, notedSyncRead, waited } from "./fetch_work.ts";
3839
3940 /** What a held reader is told at the git door, and what to do. */
4041 export const OWN_REFS_ONLY =
@@ -252,7 +253,9 @@ async function ask(
252253 args: readonly string[],
253254 stdin?: string,
254255 ): Promise<{ code: number; out: string }> {
255 return gitGate.run(async () => {
256 // One wait per question, the permit and git's answer together.
257 return waited(gitGate.run(async () => {
258 notedProcess();
256259 const proc = Bun.spawn(["git", ...args], {
257260 cwd: dir,
258261 env: gitEnv(),
@@ -270,7 +273,7 @@ async function ask(
270273 } finally {
271274 clearTimeout(timer);
272275 }
273 });
276 }));
274277 }
275278
276279 /** `oids` that `dir`'s store holds (its lenders' included), with each one's type. */
@@ -819,6 +822,7 @@ async function refDeltaBases(
819822 const head = new Uint8Array(16 + 32);
820823 for (const { offset, hashBytes } of entries) {
821824 const read = readSync(fd, head, 0, head.length, offset);
825 notedSyncRead(read);
822826 let at = 0;
823827 let byte = head[at++]!;
824828 const type = (byte >> 4) & 7;
src/git/pack_share.ts added +237
@@ -0,0 +1,237 @@
1 /**
2 * One answer per question for runner jobs' fetches (#17975). The jobs of one run, and the runs on
3 * one commit, fetch the same commit within a minute and send the same negotiation byte for byte;
4 * each of them used to make git count, compress and send the same pack again. Now the first
5 * one's answer is written to disk as git makes it, and every other fetch with the same key reads
6 * that file, following it while it grows: one pack built, N served, no process for the rest.
7 *
8 * The key is everything a pack depends on: the repository, the commit ids the job may want and
9 * the negotiation's own bytes. Never a ref name: a pack for an id is the same pack whatever a
10 * branch says a second later, so a moved ref cannot make a pack stale. Only packs are shared: the
11 * ref advertisement is built for each fetch (`smart-http.ts`), so a client always sees the refs
12 * as they are. A job's token is checked before anything here is asked (`http/api/runners.ts`).
13 * The runner fetches into a mirror it keeps, so its negotiation names `have`s: the key keeps them,
14 * as the pack git makes depends on them.
15 *
16 * Every read and write is `node:fs/promises`: nothing here holds the serving thread. A shared
17 * answer lives SHARE_MS after it is whole. The disk is bounded by bytes, not only by count: an
18 * answer that grows past SHARE_PACK_BYTES leaves the share (its file goes when its last reader
19 * does), a new answer is shared only while the files on disk come to less than SHARE_BYTES and
20 * fewer than SHARE_BUILDING are being built, and whole answers are dropped oldest first while
21 * the files come to more. Anything not shared is built for its fetch alone, straight from git,
22 * as before. So the directory holds less than SHARE_BYTES plus SHARE_BUILDING packs each no
23 * larger than the one git would have sent that fetch. The files are under the forge's data
24 * directory and the directory is emptied the first time a forge uses it, so a restart leaves
25 * nothing behind.
26 */
27
28 import { mkdir, open, rm, unlink, type FileHandle } from "node:fs/promises";
29 import { join } from "node:path";
30 import { background } from "../perf/jobs.ts";
31 import { waited, type FetchWork } from "./fetch_work.ts";
32
33 /** How long a whole answer is served again after it was built. */
34 export const SHARE_MS = 60_000;
35 /** How many answers are kept at once. */
36 export const SHARE_MAX = 8;
37 /** The bytes on disk past which no new answer is shared and whole ones are dropped. */
38 const SHARE_BYTES = 1024 * 1024 * 1024;
39 /** An answer larger than this leaves the share: a fetch that big is not a job's checkout. */
40 const SHARE_PACK_BYTES = 256 * 1024 * 1024;
41 /** How many answers may be being built at once for sharing. */
42 const SHARE_BUILDING = 2;
43 /** How much a follower reads from the file at a time. */
44 const CHUNK = 256 * 1024;
45
46 /** What a build gives: the bytes as git makes them, and whether git ended well. */
47 export interface Built {
48 readonly stream: ReadableStream<Uint8Array>;
49 readonly ok: Promise<boolean>;
50 }
51
52 interface Answer {
53 readonly path: string;
54 size: number;
55 state: "building" | "done" | "failed";
56 doneAt: number;
57 readers: number;
58 /** Out of the share: the file goes when its last reader does. */
59 retired: boolean;
60 /** The file is unlinked and its bytes no longer counted on disk. */
61 gone: boolean;
62 /** Followers waiting for the file to grow or end. */
63 readonly waiting: (() => void)[];
64 }
65
66 export interface PackShare {
67 /** The answer to `key`, built by `build` only when no live one exists. */
68 answer(key: string, build: () => Promise<Built>, work: FetchWork): Promise<ReadableStream<Uint8Array>>;
69 /** Answers built for sharing since this share was made. */
70 builds(): number;
71 /** Bytes of this share's files now on disk. */
72 onDisk(): number;
73 }
74
75 /** The disk a share may use: SHARE_BYTES and SHARE_PACK_BYTES unless a test says less. */
76 interface ShareBounds {
77 readonly bytes: number;
78 readonly packBytes: number;
79 }
80
81 /** A share whose files live in `dir` (emptied on first use). */
82 export function createPackShare(
83 dir: string,
84 now: () => number = Date.now,
85 bounds: ShareBounds = { bytes: SHARE_BYTES, packBytes: SHARE_PACK_BYTES },
86 ): PackShare {
87 const answers = new Map<string, Answer>();
88 let ready: Promise<unknown> | undefined;
89 let built = 0;
90 let serial = 0;
91 let onDisk = 0;
92 /** Shared builds whose git has not ended, in the share or left it for size. */
93 let building = 0;
94
95 const wake = (entry: Answer): void => {
96 for (const go of entry.waiting.splice(0)) go();
97 };
98
99 const remove = async (entry: Answer): Promise<void> => {
100 if (entry.gone) return;
101 entry.gone = true;
102 onDisk -= entry.size;
103 await unlink(entry.path).catch(() => {});
104 };
105
106 const drop = (key: string, entry: Answer): void => {
107 if (answers.get(key) === entry) answers.delete(key);
108 entry.retired = true;
109 if (entry.readers === 0) void remove(entry);
110 };
111
112 const sweep = (): void => {
113 const at = now();
114 for (const [key, entry] of answers)
115 if (entry.state === "failed" || (entry.state === "done" && at - entry.doneAt >= SHARE_MS)) drop(key, entry);
116 // Whole answers go oldest first while the files come to more than SHARE_BYTES.
117 const whole = [...answers].filter(([, entry]) => entry.state === "done").sort(([, a], [, b]) => a.doneAt - b.doneAt);
118 for (const [key, entry] of whole) {
119 if (onDisk <= bounds.bytes) break;
120 drop(key, entry);
121 }
122 };
123
124 const pump = async (entry: Answer, built: Built): Promise<void> => {
125 let handle: FileHandle | undefined;
126 try {
127 handle = await open(entry.path, "w");
128 for await (const chunk of built.stream) {
129 // Nobody left to read it and out of the share: git is stopped, nothing more is written.
130 if (entry.gone) break;
131 await handle.write(chunk);
132 if (entry.gone) break;
133 entry.size += chunk.length;
134 onDisk += chunk.length;
135 if (!entry.retired && entry.size > bounds.packBytes)
136 for (const [key, live] of answers) if (live === entry) drop(key, entry);
137 wake(entry);
138 }
139 entry.state = !entry.gone && (await built.ok) ? "done" : "failed";
140 } catch {
141 entry.state = "failed";
142 }
143 entry.doneAt = now();
144 building--;
145 await handle?.close().catch(() => {});
146 wake(entry);
147 if (entry.state === "failed") sweep();
148 // Gone a minute after, even when no fetch comes to sweep it.
149 else setTimeout(() => background("job-pack-sweep", sweep), SHARE_MS + 1_000).unref();
150 };
151
152 const follow = (entry: Answer): ReadableStream<Uint8Array> => {
153 entry.readers++;
154 let at = 0;
155 let handle: FileHandle | undefined;
156 let closed = false;
157 const finish = async (): Promise<void> => {
158 if (closed) return;
159 closed = true;
160 entry.readers--;
161 await handle?.close().catch(() => {});
162 if (entry.retired && entry.readers === 0) await remove(entry);
163 };
164 return new ReadableStream<Uint8Array>(
165 {
166 async pull(controller) {
167 for (;;) {
168 if (at < entry.size) {
169 handle ??= await open(entry.path, "r");
170 const want = Math.min(entry.size - at, CHUNK);
171 const bytes = new Uint8Array(want);
172 const { bytesRead } = await handle.read(bytes, 0, want, at);
173 if (bytesRead === 0) break;
174 at += bytesRead;
175 controller.enqueue(bytes.subarray(0, bytesRead));
176 return;
177 }
178 if (entry.state === "done") {
179 await finish();
180 controller.close();
181 return;
182 }
183 if (entry.state === "failed") break;
184 await new Promise<void>((resolve) => entry.waiting.push(resolve));
185 }
186 await finish();
187 controller.error(new Error("the shared fetch ended early"));
188 },
189 cancel: finish,
190 },
191 { highWaterMark: 0 },
192 );
193 };
194
195 return {
196 builds: () => built,
197 onDisk: () => onDisk,
198 async answer(key, build, work) {
199 sweep();
200 const live = answers.get(key);
201 if (live !== undefined) {
202 work.shared = true;
203 return follow(live);
204 }
205 if (answers.size >= SHARE_MAX || onDisk >= bounds.bytes || building >= SHARE_BUILDING)
206 return (await build()).stream;
207 // Taken before the first await: a fetch asking the same a moment later follows this one.
208 const name = `${new Bun.CryptoHasher("sha256").update(key).digest("hex").slice(0, 32)}-${++serial}`;
209 const entry: Answer = {
210 path: join(dir, name),
211 size: 0,
212 state: "building",
213 doneAt: 0,
214 readers: 0,
215 retired: false,
216 gone: false,
217 waiting: [],
218 };
219 answers.set(key, entry);
220 built++;
221 building++;
222 try {
223 ready ??= rm(dir, { recursive: true, force: true }).then(() => mkdir(dir, { recursive: true }));
224 await waited(ready);
225 const made = await build();
226 void pump(entry, made);
227 } catch (error) {
228 building--;
229 entry.state = "failed";
230 wake(entry);
231 sweep();
232 throw error;
233 }
234 return follow(entry);
235 },
236 };
237 }
src/git/pull-pipe.ts +2
@@ -19,6 +19,7 @@ import {
1919 } from "node:fs";
2020 import { tmpdir } from "node:os";
2121 import { join } from "node:path";
22 import { notedProcess } from "./fetch_work.ts";
2223
2324 export interface PullPipe {
2425 /** Hand to `Bun.spawn` as `stdout`; call `sealed()` once it has spawned. */
@@ -45,6 +46,7 @@ export async function pullPipe(
4546 onCancel: () => void = () => undefined,
4647 ): Promise<PullPipe> {
4748 const path = fifoPath();
49 notedProcess();
4850 const made = Bun.spawn(["mkfifo", "-m", "600", path], {
4951 stdin: "ignore",
5052 stdout: "ignore",
src/git/smart-http.ts +77 −7
@@ -22,6 +22,8 @@ import { transferDeadline, type Stall } from "./progress.ts";
2222 import { pacer } from "./pace.ts";
2323 import { bundleConfig } from "./bundle_uri.ts";
2424 import { OWN_REFS_ONLY, heldNegotiation, reachableFromOwnRefs, refusalLine, wantsOf } from "./own_refs.ts";
25 import { countingWork, newFetchWork, notedProcess, waited, type FetchWork } from "./fetch_work.ts";
26 import type { Built, PackShare } from "./pack_share.ts";
2527
2628 export type GitService = "git-upload-pack" | "git-receive-pack";
2729
@@ -114,6 +116,31 @@ export interface SmartHttpOptions {
114116 * a held reader's, so every want is seen before git is given it.
115117 */
116118 onlyWants?: readonly string[];
119 /**
120 * Where the pack of a fetch held to `onlyWants` is answered once for every job that asks the
121 * same (`pack_share.ts`), keyed by the repository, the ids and the negotiation's bytes. The
122 * advertisement is never shared: it lists refs, and a ref that moved is shown as it is now.
123 */
124 share?: PackShare;
125 /** What serving this fetch cost, counted as it is served (`fetch_work.ts`). */
126 work?: FetchWork;
127 }
128
129 /** The share a fetch is answered from: only a job's, held to its ids and to nothing else. */
130 function shareOf(options: SmartHttpOptions): { share: PackShare; only: readonly string[] } | undefined {
131 const { share, onlyWants: only } = options;
132 // A transfer with its own `release` is one caller's; it is never shared.
133 if (share === undefined || only === undefined || options.ownRefsOnly === true || options.release !== undefined)
134 return undefined;
135 return { share, only };
136 }
137
138 /**
139 * A request of the forge's own for a shared build: no client's hang-up stops a build other
140 * fetches follow, and it is nobody's session to close.
141 */
142 function buildRequest(): Request {
143 return new Request("http://forge.invalid/shared-fetch", { method: "POST" });
117144 }
118145
119146 /** How long a fetch's negotiation may go without a byte before it ends. */
@@ -130,9 +157,9 @@ export async function advertiseRefs(
130157 request: Request,
131158 options: SmartHttpOptions = {},
132159 ): Promise<Response> {
133 const { stdout } = await spawnService(repoDir, service, request, options, [
134 "--advertise-refs",
135 ]);
160 const { stdout } = await countingWork(options.work, () =>
161 spawnService(repoDir, service, request, options, ["--advertise-refs"]),
162 );
136163
137164 const preamble = new TextEncoder().encode(
138165 pktLine(`# service=${service}\n`) + FLUSH,
@@ -152,18 +179,28 @@ export async function advertiseRefs(
152179 * Request body streams to git's stdin (gunzipped if the client compressed
153180 * it); git's stdout streams back as the response.
154181 */
155 export async function serviceRpc(
182 export function serviceRpc(
156183 repoDir: string,
157184 service: GitService,
158185 request: Request,
159186 options: SmartHttpOptions = {},
187 ): Promise<Response> {
188 return countingWork(options.work, () => answerRpc(repoDir, service, request, options));
189 }
190
191 async function answerRpc(
192 repoDir: string,
193 service: GitService,
194 request: Request,
195 options: SmartHttpOptions,
160196 ): Promise<Response> {
161197 // A held reader's request is read whole first (it is the negotiation, a few
162198 // kilobytes): what it wants is asked of the fork's own refs, then git gets it.
163199 let read: Uint8Array | undefined;
164200 const only = options.onlyWants;
201 const work = options.work;
165202 if ((options.ownRefsOnly === true || only !== undefined) && service === "git-upload-pack") {
166 read = await negotiation(request);
203 read = await waited(negotiation(request));
167204 const asked = read === undefined ? "bad" : wantsOf(read);
168205 const beyond = asked !== "bad" && only !== undefined && asked.wants.some((want) => !only.includes(want));
169206 if (
@@ -179,6 +216,16 @@ export async function serviceRpc(
179216 },
180217 });
181218 }
219 // A job's fetch: the same negotiation for the same ids is answered once (`pack_share.ts`).
220 const shared = shareOf(options);
221 if (shared !== undefined) {
222 const key = `pack\0${repoDir}\0${shared.only.join(",")}\0${new Bun.CryptoHasher("sha256").update(read!).digest("hex")}`;
223 const negotiated = read!;
224 const stdout = await shared.share.answer(key, () => heldBuild(repoDir, negotiated, shared.only, options), work ?? newFetchWork());
225 return new Response(wasInternal(request) ? stdout : pacer.pace(stdout), {
226 headers: { "content-type": `application/x-${service}-result`, "cache-control": "no-cache" },
227 });
228 }
182229 // What git is told it has and what it is told is shallow is held too.
183230 try {
184231 read = await heldNegotiation(repoDir, only).push(read!);
@@ -211,6 +258,28 @@ export async function serviceRpc(
211258 });
212259 }
213260
261 /**
262 * The pack one job's negotiation asks for, built for every fetch that asks the same: what git is
263 * told it has is held to what the job may name (`heldNegotiation`), then upload-pack answers.
264 */
265 async function heldBuild(
266 repoDir: string,
267 read: Uint8Array,
268 only: readonly string[],
269 options: SmartHttpOptions,
270 ): Promise<Built> {
271 let held: Uint8Array;
272 try {
273 held = await heldNegotiation(repoDir, only).push(read);
274 } catch {
275 return { stream: new Response(refusalLine(OWN_REFS_ONLY)).body!, ok: Promise.resolve(true) };
276 }
277 const from = buildRequest();
278 const { proc, stdout } = await spawnService(repoDir, "git-upload-pack", from, options, []);
279 feedStdin(proc, "git-upload-pack", from, options.idleMs ?? FETCH_IDLE_MS, held).catch(() => proc.kill("SIGKILL"));
280 return { stream: stdout, ok: proc.exited.then((code) => code === 0) };
281 }
282
214283 /**
215284 * Spawn one pack service, holding a transfer permit for its whole life.
216285 *
@@ -235,7 +304,7 @@ async function spawnService(
235304 options: SmartHttpOptions,
236305 extraArgs: readonly string[],
237306 ) {
238 const permit = await transferGate.acquire();
307 const permit = await waited(transferGate.acquire());
239308 const release = (): void => {
240309 permit();
241310 options.release?.();
@@ -257,7 +326,8 @@ async function spawnService(
257326 let pipe: PullPipe | undefined;
258327 let proc: Bun.Subprocess<"pipe", number, "ignore">;
259328 try {
260 pipe = await pullPipe(() => proc.kill("SIGKILL"));
329 pipe = await waited(pullPipe(() => proc.kill("SIGKILL")));
330 notedProcess();
261331 proc = Bun.spawn(
262332 serviceCommand(
263333 service,
src/http/api/runners.ts +31 −4
@@ -43,7 +43,11 @@ import { buildOf } from "../../kernel/version.ts";
4343 import { inFlight } from "../../perf/live.ts";
4444 import { appendRunLog } from "../../runs/log.ts";
4545 import { RUNNER_VERSION_HEADER } from "../../runner/upgrade.ts";
46 import { join } from "node:path";
4647 import { advertiseRefs, serviceRpc } from "../../git/smart-http.ts";
48 import { newFetchWork, workWords } from "../../git/fetch_work.ts";
49 import { createPackShare, type PackShare } from "../../git/pack_share.ts";
50 import type { App } from "../../app.ts";
4751 import type { Ctx, Handler } from "../context.ts";
4852 import { STRANGER_MAX } from "../limits.ts";
4953 import { apiError, body, boundedBody, json, notFound, str, tryAgain, unauthorized } from "../respond.ts";
@@ -105,6 +109,18 @@ function readLend(raw: unknown): LendInput | undefined {
105109 };
106110 }
107111
112 /** One pack share per forge: its jobs' fetches of one commit are built once (#17975). */
113 const packShares = new WeakMap<App, PackShare>();
114
115 function packShareOf(app: App): PackShare {
116 let share = packShares.get(app);
117 if (share === undefined) {
118 share = createPackShare(join(app.config.dataDir, "job-packs"));
119 packShares.set(app, share);
120 }
121 return share;
122 }
123
108124 export function runnerRoutes(router: Router<Handler>): void {
109125 router.add("POST", "/api/v1/admin/runners", async (ctx) => {
110126 const denied = accountAdmin(ctx, "admin");
@@ -347,22 +363,33 @@ export function runnerRoutes(router: Router<Handler>): void {
347363 });
348364
349365 // The job's git door: a fetch of its repository, held to the commits the job names.
350 router.add("GET", "/api/v1/runner/jobs/:id/git/info/refs", (ctx) => {
366 router.add("GET", "/api/v1/runner/jobs/:id/git/info/refs", async (ctx) => {
351367 const mine = held(ctx);
352368 if (
353369 mine === undefined ||
354370 ctx.url.searchParams.get("service") !== "git-upload-pack"
355371 )
356372 return notFound();
357 return advertiseRefs(mine.job.dir, "git-upload-pack", ctx.request, {
373 // The work each side of the fetch cost is said in the run's log (#17975).
374 const work = newFetchWork();
375 const answer = await advertiseRefs(mine.job.dir, "git-upload-pack", ctx.request, {
358376 onlyWants: mine.job.wants,
377 share: packShareOf(ctx.app),
378 work,
359379 });
380 mine.ear.lines("", [workWords("git refs", work)]);
381 return answer;
360382 });
361 router.add("POST", "/api/v1/runner/jobs/:id/git/git-upload-pack", (ctx) => {
383 router.add("POST", "/api/v1/runner/jobs/:id/git/git-upload-pack", async (ctx) => {
362384 const mine = held(ctx);
363385 if (mine === undefined) return notFound();
364 return serviceRpc(mine.job.dir, "git-upload-pack", ctx.request, {
386 const work = newFetchWork();
387 const answer = await serviceRpc(mine.job.dir, "git-upload-pack", ctx.request, {
365388 onlyWants: mine.job.wants,
389 share: packShareOf(ctx.app),
390 work,
366391 });
392 mine.ear.lines("", [workWords("git fetch", work)]);
393 return answer;
367394 });
368395 }
test/job-slices.test.ts +1
@@ -300,6 +300,7 @@ function jobs(): Record<string, () => unknown> {
300300 * on.
301301 */
302302 const UNTIMED: Record<string, string> = {
303 "job-pack-sweep": "a one-shot timer a minute after a shared runner-job pack is whole (git/pack_share.ts): a walk of at most SHARE_MAX in-memory entries and an async unlink each; runner-fetch-share.test.ts drives the expiry with a clock",
303304 "push": "one event's pushes to Apple (push/watch.ts): a few indexed reads, at most one askLinesFor per person with an alert device, and network answers that are not timed here; push-apns.test.ts drives it with a recording transport",
304305 "decider-shadow": "one call to a second decider after a decision is recorded (crew/snap.ts): a few indexed reads, one insert and a network answer, at most two at once; decider-shadow.test.ts drives it with a fake",
305306 "decider-replay": "an admin's replay of at most 500 past decisions (crew/snap.ts): network answers and one insert each, two at once; decider-shadow.test.ts drives it with a fake",
test/request-path-sync.test.ts +16 −3
@@ -2,8 +2,8 @@
22 * Every synchronous file or process call on a request path is named here, with
33 * its reason (#17885). A stall comes back one cause at a time: a `readFileSync`
44 * in a handler blocks every request the process holds while the disk answers.
5 * This test reads src/http, src/web/pages and src/apps/proxy.ts for the calls
6 * in SYNC and fails on a file whose count is not exactly its row in ALLOWED:
5 * This test reads src/http, src/web/pages, src/apps/proxy.ts and a runner's fetch path for the
6 * calls in SYNC and fails on a file whose count is not exactly its row in ALLOWED:
77 * a new call fails until it is cached, sliced, moved off the thread or named
88 * with a reason; a call that went away fails until its row shrinks, so the list
99 * only shrinks. It reads the source as text and never runs it, as
@@ -14,7 +14,20 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
1414 import { join, relative } from "node:path";
1515
1616 const ROOT = join(import.meta.dir, "..");
17 const SCANNED = ["src/http", "src/web/pages", "src/apps/proxy.ts"];
17 // A runner job's fetch too (#17975): its git door, and the share its packs are answered from.
18 // Two modules the fetch calls are not scanned, on purpose, and why: own_refs.ts (its
19 // `heldNegotiation`) has a readdirSync and a readSync, both in `refDeltaBases`, which only a
20 // push's quarantine reaches; pull-pipe.ts has `pullPipeSync`, which only the SSH door calls, the
21 // HTTP fetch takes the async `pullPipe`. Each sync read in own_refs.ts is counted into a fetch's
22 // work (`notedSyncRead`), so a fetch that reached one would say so in its job's log.
23 const SCANNED = [
24 "src/http",
25 "src/web/pages",
26 "src/apps/proxy.ts",
27 "src/git/smart-http.ts",
28 "src/git/pack_share.ts",
29 "src/git/fetch_work.ts",
30 ];
1831 const SYNC = ["spawnSync", "execSync", "readFileSync", "readdirSync", "statSync", "writeFileSync", "appendFileSync"] as const;
1932 type SyncCall = (typeof SYNC)[number];
2033
test/runner-fetch-share.test.ts added +205
@@ -0,0 +1,205 @@
1 /**
2 * Runner jobs that fetch the same commit are answered from one pack (#17975): the first fetch's
3 * upload-pack output is written once and every other job with the same negotiation follows that
4 * file, no process spawned for it. Keyed by commit id, never by a ref, so a moved branch is never
5 * served a stale pack; the advertisement, which lists refs, is never shared. The share's disk is
6 * bounded by bytes, and the work each fetch cost is counted where it happens.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { runGit } from "../src/git/env.ts";
13 import { countingWork, newFetchWork, notedSyncRead, waited, workWords, type FetchWork } from "../src/git/fetch_work.ts";
14 import { createPackShare, type PackShare } from "../src/git/pack_share.ts";
15 import { initBareRepo, repoDir } from "../src/git/repos.ts";
16 import { advertiseRefs, serviceRpc } from "../src/git/smart-http.ts";
17 import { unwrap } from "../src/kernel/result.ts";
18 import { gitClientEnv } from "./helpers/git-client.ts";
19
20 let root: string;
21 let first: string;
22 let second: string;
23 const dir = () => repoDir(root, "ada", "job");
24
25 beforeAll(async () => {
26 root = await mkdtemp(join(tmpdir(), "forge-runner-share-"));
27 unwrap(await initBareRepo(dir()));
28 const seed = join(root, "seed");
29 const env = gitClientEnv();
30 const git = (args: string[]) => Bun.spawn(["git", ...args], { cwd: seed, env, stdout: "ignore", stderr: "ignore" }).exited;
31 await Bun.spawn(["git", "init", "-q", "-b", "main", seed], { env }).exited;
32 for (const text of ["one", "two"]) {
33 await Bun.write(join(seed, "f"), text);
34 await git(["add", "."]);
35 await git(["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", text]);
36 }
37 await git(["push", "-q", dir(), "main"]);
38 second = unwrap(await runGit(["rev-parse", "refs/heads/main"], { cwd: dir() }));
39 first = unwrap(await runGit(["rev-parse", "refs/heads/main~1"], { cwd: dir() }));
40 });
41
42 afterAll(async () => {
43 await rm(root, { recursive: true, force: true });
44 });
45
46 const pkt = (line: string) => `${(line.length + 4).toString(16).padStart(4, "0")}${line}`;
47 const negotiation = (want: string) => `${pkt(`want ${want} side-band-64k ofs-delta\n`)}0000${pkt("done\n")}`;
48
49 async function fetchOnce(share: PackShare | undefined, want: string, work: FetchWork): Promise<string> {
50 const request = new Request("http://forge.test/api/v1/runner/jobs/j/git/git-upload-pack", {
51 method: "POST",
52 headers: { "content-type": "application/x-git-upload-pack-request" },
53 body: negotiation(want),
54 });
55 const response = await serviceRpc(dir(), "git-upload-pack", request, { onlyWants: [want], ...(share === undefined ? {} : { share }), work });
56 return new TextDecoder("latin1").decode(await response.arrayBuffer());
57 }
58
59 test("N jobs fetching one commit cause one pack build, and the rest spawn nothing", async () => {
60 const share = createPackShare(join(root, "packs-a"));
61 const works = Array.from({ length: 6 }, newFetchWork);
62 const answers = await Promise.all(works.map((work) => fetchOnce(share, second, work)));
63 expect(share.builds()).toBe(1);
64 for (const answer of answers) {
65 expect(answer).toContain("PACK");
66 expect(answer).toBe(answers[0]!);
67 }
68 // Two processes in all (mkfifo for the pipe, then upload-pack), counted to the job that built;
69 // none to the five that shared.
70 expect(works.reduce((n, w) => n + w.processes, 0)).toBe(2);
71 expect(works.filter((w) => w.shared)).toHaveLength(5);
72 // A later job, after the first is whole, is served the same file.
73 const late = newFetchWork();
74 expect(await fetchOnce(share, second, late)).toBe(answers[0]!);
75 // One wait, the negotiation's read; nothing spawned, nothing read synchronously.
76 expect(late).toMatchObject({ processes: 0, awaits: 1, syncBytes: 0, shared: true });
77 // The job that built waited for the body, the git questions, the permit and the pipe: each
78 // counted where it was awaited, none read synchronously.
79 const builder = works.find((w) => !w.shared)!;
80 expect(builder.awaits).toBeGreaterThanOrEqual(4);
81 expect(builder.syncBytes).toBe(0);
82 expect(share.builds()).toBe(1);
83 console.log(`one job: before ${workWords("git fetch", works.find((w) => !w.shared)!)}; after ${workWords("git fetch", late)}`);
84 }, 30_000);
85
86 test("without a share every job builds its own pack: the counter sees each process", async () => {
87 const works = Array.from({ length: 3 }, newFetchWork);
88 await Promise.all(works.map((work) => fetchOnce(undefined, second, work)));
89 expect(works.map((w) => w.processes)).toEqual([2, 2, 2]);
90 }, 30_000);
91
92 test("another commit is another pack: the key is the commit id", async () => {
93 const share = createPackShare(join(root, "packs-b"));
94 const a = await fetchOnce(share, second, newFetchWork());
95 const b = await fetchOnce(share, first, newFetchWork());
96 expect(share.builds()).toBe(2);
97 expect(a).not.toBe(b);
98 }, 30_000);
99
100 test("a want beyond the job's ids is refused before anything is built", async () => {
101 const share = createPackShare(join(root, "packs-c"));
102 const request = new Request("http://forge.test/x", { method: "POST", body: negotiation(first) });
103 const response = await serviceRpc(dir(), "git-upload-pack", request, { onlyWants: [second], share, work: newFetchWork() });
104 expect(await response.text()).toContain("fetches only the commits its job names");
105 expect(share.builds()).toBe(0);
106 });
107
108 test("the advertisement is never shared: a moved branch is shown as it is now", async () => {
109 const share = createPackShare(join(root, "packs-d"));
110 const advertise = async (work: FetchWork) => {
111 const request = new Request("http://forge.test/x?service=git-upload-pack");
112 return (await advertiseRefs(dir(), "git-upload-pack", request, { onlyWants: [second], share, work })).text();
113 };
114 const before = newFetchWork();
115 expect(await advertise(before)).toContain(`${second} refs/heads/main`);
116 unwrap(await runGit(["update-ref", "refs/heads/main", first], { cwd: dir() }));
117 try {
118 const after = newFetchWork();
119 expect(await advertise(after)).toContain(`${first} refs/heads/main`);
120 expect(share.builds()).toBe(0);
121 expect([before.processes, after.processes]).toEqual([2, 2]);
122 } finally {
123 unwrap(await runGit(["update-ref", "refs/heads/main", second], { cwd: dir() }));
124 }
125 }, 30_000);
126
127 test("a whole answer is shared for SHARE_MS, then built again", async () => {
128 let clock = 1_000_000;
129 const share = createPackShare(join(root, "packs-e"), () => clock);
130 await fetchOnce(share, second, newFetchWork());
131 clock += 59_000;
132 await fetchOnce(share, second, newFetchWork());
133 expect(share.builds()).toBe(1);
134 clock += 2_000;
135 await fetchOnce(share, second, newFetchWork());
136 expect(share.builds()).toBe(2);
137 }, 30_000);
138
139 /** A build that gives `size` bytes of `fill`, as git would give a pack. */
140 const madeOf = (size: number, fill: number) => async () => ({
141 stream: new Response(new Uint8Array(size).fill(fill)).body!,
142 ok: Promise.resolve(true),
143 });
144
145 const drained = async (stream: ReadableStream<Uint8Array>) => (await new Response(stream).arrayBuffer()).byteLength;
146
147 test("whole answers are dropped oldest first once the files pass the byte bound", async () => {
148 const share = createPackShare(join(root, "packs-f"), Date.now, { bytes: 100, packBytes: 80 });
149 expect(await drained(await share.answer("a", madeOf(50, 1), newFetchWork()))).toBe(50);
150 expect(await drained(await share.answer("b", madeOf(60, 2), newFetchWork()))).toBe(60);
151 expect(share.onDisk()).toBe(110);
152 // The next fetch finds 110 bytes against a bound of 100: "a", the oldest, goes.
153 await drained(await share.answer("c", madeOf(10, 3), newFetchWork()));
154 expect(share.onDisk()).toBe(70);
155 const kept = newFetchWork();
156 await drained(await share.answer("b", madeOf(60, 2), kept));
157 expect(kept.shared).toBe(true);
158 const again = newFetchWork();
159 await drained(await share.answer("a", madeOf(50, 1), again));
160 expect(again.shared).toBe(false);
161 expect(share.builds()).toBe(4);
162 });
163
164 test("an answer past the per-pack bound leaves the share and its file goes with its reader", async () => {
165 const share = createPackShare(join(root, "packs-g"), Date.now, { bytes: 1_000, packBytes: 40 });
166 // The file is unlinked before the stream closes: drained, it is gone.
167 expect(await drained(await share.answer("big", madeOf(100, 9), newFetchWork()))).toBe(100);
168 expect(share.onDisk()).toBe(0);
169 const next = newFetchWork();
170 await drained(await share.answer("big", madeOf(100, 9), next));
171 expect(next.shared).toBe(false);
172 expect(share.builds()).toBe(2);
173 });
174
175 test("no new answer is shared while the files are at the byte bound", async () => {
176 const share = createPackShare(join(root, "packs-h"), Date.now, { bytes: 50, packBytes: 50 });
177 // Its bytes read, the stream kept open: the file stays and is counted.
178 const reader = (await share.answer("a", madeOf(50, 1), newFetchWork())).getReader();
179 expect((await reader.read()).value?.byteLength).toBe(50);
180 expect(share.onDisk()).toBe(50);
181 const alone = newFetchWork();
182 expect(await drained(await share.answer("b", madeOf(30, 2), alone))).toBe(30);
183 expect(share.builds()).toBe(1);
184 expect((await reader.read()).done).toBe(true);
185 });
186
187 test("the counter counts the real waits and synchronous reads, and nothing outside a fetch", async () => {
188 const work = newFetchWork();
189 await countingWork(work, async () => {
190 // A real operation awaited: a git process's answer takes some time to come.
191 await waited(runGit(["--version"], { cwd: root }));
192 notedSyncRead(48);
193 });
194 expect(work.awaits).toBe(1);
195 expect(work.waitedMs).toBeGreaterThan(0);
196 expect(work.syncBytes).toBe(48);
197 // Outside a counted fetch nothing is counted anywhere.
198 await waited(Promise.resolve());
199 notedSyncRead(10);
200 expect(work.awaits).toBe(1);
201 expect(work.syncBytes).toBe(48);
202 expect(workWords("git fetch", { ...work, waitedMs: 5 })).toBe(
203 "git fetch: built, 0 processes, 1 await (5 ms), 48 bytes read synchronously",
204 );
205 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs