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

git-upload-pack for a runner job no longer holds the serving thread #17839

opened this

Merged 4h 26m ago, live in production

scout/forge:scout/17821-git-upload-pack-for-a-runner-job-no-long → main 0 commits fork

  • Merged. scout/17821-git-upload-pack-for-a-runner-job-no-long was merged into main as 91265d1.

Review

Sign in to review this change.
6 files changed +135 −34
scripts/test-honesty-allow.json −1
@@ -60,7 +60,6 @@
6060 "test/billing-replay.test.ts": {"wait":2},
6161 "test/boards-healthz-gap.test.ts": {"wait":1},
6262 "test/boot-beside-peer.test.ts": {"wait":2},
63 "test/boot-no-stall.test.ts": {"wait":1},
6463 "test/boot-production.test.ts": {"wait":5},
6564 "test/boundary-fork-objects.test.ts": {"wait":2},
6665 "test/boundary-outbound.test.ts": {"wait":2},
src/git/own_refs.ts +31 −11
@@ -33,6 +33,7 @@
3333 import { AsyncLocalStorage } from "node:async_hooks";
3434 import { closeSync, openSync, readdirSync, readSync } from "node:fs";
3535 import { join } from "node:path";
36 import { sliced } from "../kernel/breathe.ts";
3637 import { Gate, gitEnv, gitGate } from "./env.ts";
3738
3839 /** What a held reader is told at the git door, and what to do. */
@@ -835,6 +836,8 @@ async function refDeltaBases(
835836
836837 // ---- what a held reader's negotiation may ask about ----
837838
839 const LATIN1 = new TextDecoder("latin1");
840
838841 /** More held ids than this in one fetch's `have` and `shallow` lines are dropped unasked. */
839842 const ASKED_MAX = 64;
840843
@@ -881,35 +884,52 @@ export function heldNegotiation(
881884 };
882885
883886 const run = async (bytes: Uint8Array): Promise<Uint8Array> => {
884 const all = new Uint8Array(carry.length + bytes.length);
885 all.set(carry);
886 all.set(bytes, carry.length);
887 // No copy when nothing waits from the last piece: a whole negotiation is read where it lies.
888 let all = bytes;
889 if (carry.length > 0) {
890 all = new Uint8Array(carry.length + bytes.length);
891 all.set(carry);
892 all.set(bytes, carry.length);
893 }
887894 const packets: { raw: Uint8Array; id?: string }[] = [];
895 // The largest negotiation is a third of a million packets: read in slices, the thread handed
896 // back between them, so a runner's fetch never holds the pages it shares a thread with
897 // (#17821).
898 const slice = sliced();
899 const ids = new Set<string>();
888900 let at = 0;
889901 for (;;) {
902 if ((packets.length & 63) === 0 && slice.due()) await slice.breathe();
890903 if (all.length < at + 4) break;
891 const head = String.fromCharCode(...all.subarray(at, at + 4));
904 const head = String.fromCharCode(all[at]!, all[at + 1]!, all[at + 2]!, all[at + 3]!);
892905 if (!/^[0-9a-fA-F]{4}$/.test(head)) throw new Error("bad pkt-line");
893906 const length = parseInt(head, 16);
894907 if (length === 3 || length > 65_520) throw new Error("bad pkt-line");
895908 const size = length < 4 ? 4 : length;
896909 if (all.length < at + size) break;
897910 const raw = all.subarray(at, at + size);
898 const text = size > 4 ? new TextDecoder("latin1").decode(raw.subarray(4)) : "";
911 const text = size > 4 ? LATIN1.decode(raw.subarray(4)) : "";
899912 const m = /^(?:have|shallow) ([^\s\0]*)/.exec(text);
900 packets.push(m === null ? { raw } : { raw, id: m[1]!.toLowerCase() });
913 if (m === null) packets.push({ raw });
914 else {
915 const id = m[1]!.toLowerCase();
916 ids.add(id);
917 packets.push({ raw, id });
918 }
901919 at += size;
902920 }
903921 carry = all.slice(at);
904 await judge(new Set(packets.flatMap((p) => (p.id === undefined ? [] : [p.id]))));
905 const kept = packets.filter((p) => p.id === undefined || allowed.has(p.id) || verdicts.get(p.id) === true);
906 const out = new Uint8Array(kept.reduce((n, p) => n + p.raw.length, 0));
922 await judge(ids);
923 const out = new Uint8Array(packets.reduce((n, p) => n + p.raw.length, 0));
907924 let w = 0;
908 for (const p of kept) {
925 for (let i = 0; i < packets.length; i++) {
926 if ((i & 255) === 0 && slice.due()) await slice.breathe();
927 const p = packets[i]!;
928 if (p.id !== undefined && !allowed.has(p.id) && verdicts.get(p.id) !== true) continue;
909929 out.set(p.raw, w);
910930 w += p.raw.length;
911931 }
912 return out;
932 return out.subarray(0, w);
913933 };
914934
915935 return {
src/git/smart-http.ts +13 −3
@@ -7,7 +7,7 @@
77
88 import { holdForCaller } from "../http/caller.ts";
99 import { wasInternal } from "../http/peer.ts";
10 import { gunzipSync } from "node:zlib";
10 import { gunzip } from "node:zlib";
1111 import {
1212 closeNow,
1313 counted,
@@ -378,7 +378,7 @@ async function feedStdin(
378378 if (compressed === "too_large") return stop();
379379 let inflated: Uint8Array;
380380 try {
381 inflated = gunzipSync(compressed, { maxOutputLength: FETCH_MAX });
381 inflated = await inflate(compressed);
382382 } catch {
383383 return stop();
384384 }
@@ -412,12 +412,22 @@ async function negotiation(request: Request): Promise<Uint8Array | undefined> {
412412 if (body === "too_large") return undefined;
413413 if (!gzip) return body;
414414 try {
415 return gunzipSync(body, { maxOutputLength: FETCH_MAX });
415 return await inflate(body);
416416 } catch {
417417 return undefined;
418418 }
419419 }
420420
421 /**
422 * A gzipped negotiation inflated on zlib's worker, never the serving thread (#17821): a megabyte
423 * that grows to FETCH_MAX is hundreds of milliseconds of work. Past FETCH_MAX it rejects.
424 */
425 function inflate(body: Uint8Array): Promise<Uint8Array> {
426 return new Promise((done, fail) =>
427 gunzip(body, { maxOutputLength: FETCH_MAX }, (error, out) => (error === null ? done(out) : fail(error))),
428 );
429 }
430
421431 /** A stream that yields `head` and then everything from `rest`. */
422432 function prepend(
423433 head: Uint8Array,
test/boot-no-stall.test.ts +1 −19
@@ -15,6 +15,7 @@ import { group, wordsOf, type Finding } from "../src/flow/repeats.ts";
1515 import { getRepoById } from "../src/core/repos.ts";
1616 import { bigForge, PRODUCTION } from "./helpers/big-forge.ts";
1717 import { quietLogs } from "./helpers/globals.ts";
18 import { worstBlock } from "./helpers/worst-block.ts";
1819
1920 quietLogs();
2021
@@ -30,25 +31,6 @@ beforeAll(() => {
3031 }, 120_000);
3132 afterAll(() => rmSync(dir, { recursive: true, force: true }));
3233
33 /** The longest the loop went without waking while `work` ran, ms. */
34 async function worstBlock(work: () => Promise<unknown>): Promise<number> {
35 let last = performance.now();
36 let worst = 0;
37 const timer = setInterval(() => {
38 const now = performance.now();
39 worst = Math.max(worst, now - last - 5);
40 last = now;
41 }, 5);
42 try {
43 await work();
44 // The wake the work's last slice kept from running.
45 await new Promise((r) => setTimeout(r, 10));
46 } finally {
47 clearInterval(timer);
48 }
49 return worst;
50 }
51
5234 test("the review-repeat sweep over a week of findings never holds the thread", async () => {
5335 const repo = getRepoById(app.db, "r")!;
5436 const blocks: number[] = [];
test/helpers/worst-block.ts added +20
@@ -0,0 +1,20 @@
1 /** The longest the loop went without waking while `work` ran, ms (a 5 ms timer, less its own 5). */
2 export async function worstBlock(work: () => Promise<unknown>): Promise<number> {
3 let last = performance.now();
4 let worst = 0;
5 let woke: (() => void) | undefined;
6 const timer = setInterval(() => {
7 const now = performance.now();
8 worst = Math.max(worst, now - last - 5);
9 last = now;
10 woke?.();
11 }, 5);
12 try {
13 await work();
14 // The wake the work's last slice kept from running.
15 await new Promise<void>((done) => (woke = done));
16 } finally {
17 clearInterval(timer);
18 }
19 return worst;
20 }
test/runner-fetch-loop.test.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * A runner's fetch (`/api/v1/runner/jobs/:id/git/git-upload-pack`, held to its job's commits)
3 * leaves the serving thread free (#17821): its negotiation is inflated and read off the thread or
4 * in slices, so pages keep answering while the largest one a client may send is weighed.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { gzipSync } from "node:zlib";
11 import { runGit } from "../src/git/env.ts";
12 import { initBareRepo, repoDir } from "../src/git/repos.ts";
13 import { serviceRpc } from "../src/git/smart-http.ts";
14 import { FETCH_MAX } from "../src/http/limits.ts";
15 import { unwrap } from "../src/kernel/result.ts";
16 import { gitClientEnv } from "./helpers/git-client.ts";
17 import { worstBlock } from "./helpers/worst-block.ts";
18
19 let root: string;
20 let tip: string;
21 const dir = () => repoDir(root, "ada", "job");
22
23 beforeAll(async () => {
24 root = await mkdtemp(join(tmpdir(), "forge-runner-loop-"));
25 unwrap(await initBareRepo(dir()));
26 const seed = join(root, "seed");
27 const env = gitClientEnv();
28 const git = (args: string[]) => Bun.spawn(["git", ...args], { cwd: seed, env, stdout: "ignore", stderr: "ignore" }).exited;
29 await Bun.spawn(["git", "init", "-q", "-b", "main", seed], { env }).exited;
30 await Bun.write(join(seed, "f"), "one");
31 await git(["add", "."]);
32 await git(["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "one"]);
33 await git(["push", "-q", dir(), "main"]);
34 tip = unwrap(await runGit(["rev-parse", "refs/heads/main"], { cwd: dir() }));
35 });
36
37 afterAll(async () => {
38 await rm(root, { recursive: true, force: true });
39 });
40
41 const pkt = (line: string) => `${(line.length + 4).toString(16).padStart(4, "0")}${line}`;
42
43 /** The largest negotiation a fetch may send: one want, then haves up to FETCH_MAX, gzipped. */
44 function hugeNegotiation(): Uint8Array {
45 const have = pkt(`have ${"1".repeat(40)}\n`);
46 const head = `${pkt(`want ${tip}\n`)}0000`;
47 const count = Math.floor((FETCH_MAX - head.length - 20) / have.length);
48 return gzipSync(`${head}${have.repeat(count)}${pkt("done\n")}`);
49 }
50
51 test("a runner's largest negotiation never holds the serving thread past 150 ms", async () => {
52 const body = hugeNegotiation();
53 let answer = "";
54 const gap = await worstBlock(async () => {
55 const request = new Request("http://forge.test/api/v1/runner/jobs/j/git/git-upload-pack", {
56 method: "POST",
57 headers: { "content-type": "application/x-git-upload-pack-request", "content-encoding": "gzip" },
58 body,
59 });
60 const response = await serviceRpc(dir(), "git-upload-pack", request, { onlyWants: [tip] });
61 answer = new TextDecoder("latin1").decode(await response.arrayBuffer());
62 });
63 console.log(`runner fetch: longest loop gap ${gap.toFixed(1)} ms`);
64 // Same bytes out: git answered the want with a pack.
65 expect(answer).toContain("PACK");
66 // Before #17821 one fetch held it 860-970 ms (a synchronous inflate, then one unbroken parse);
67 // now 25-50 ms, in slices of SLICE_MS. The bound leaves room for a loaded machine, not the old
68 // path.
69 expect(gap).toBeLessThan(150);
70 }, 60_000);

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

Keyboard shortcuts

Docs