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
Merged 17h 14m ago, live in production
torque/forge:torque/17975-runner-jobs-git-upload-pack-count-the-wo → main 0 commits fork
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"; | ||
| 35 | 35 | import { join } from "node:path"; |
| 36 | 36 | import { sliced } from "../kernel/breathe.ts"; |
| 37 | 37 | import { Gate, gitEnv, gitGate } from "./env.ts"; |
| 38 | import { notedProcess, notedSyncRead, waited } from "./fetch_work.ts"; | |
| 38 | 39 | |
| 39 | 40 | /** What a held reader is told at the git door, and what to do. */ |
| 40 | 41 | export const OWN_REFS_ONLY = |
| @@ -252,7 +253,9 @@ async function ask( | ||
| 252 | 253 | args: readonly string[], |
| 253 | 254 | stdin?: string, |
| 254 | 255 | ): 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(); | |
| 256 | 259 | const proc = Bun.spawn(["git", ...args], { |
| 257 | 260 | cwd: dir, |
| 258 | 261 | env: gitEnv(), |
| @@ -270,7 +273,7 @@ async function ask( | ||
| 270 | 273 | } finally { |
| 271 | 274 | clearTimeout(timer); |
| 272 | 275 | } |
| 273 | }); | |
| 276 | })); | |
| 274 | 277 | } |
| 275 | 278 | |
| 276 | 279 | /** `oids` that `dir`'s store holds (its lenders' included), with each one's type. */ |
| @@ -819,6 +822,7 @@ async function refDeltaBases( | ||
| 819 | 822 | const head = new Uint8Array(16 + 32); |
| 820 | 823 | for (const { offset, hashBytes } of entries) { |
| 821 | 824 | const read = readSync(fd, head, 0, head.length, offset); |
| 825 | notedSyncRead(read); | |
| 822 | 826 | let at = 0; |
| 823 | 827 | let byte = head[at++]!; |
| 824 | 828 | const type = (byte >> 4) & 7; |
src/git/pull-pipe.ts +2
| @@ -19,6 +19,7 @@ import { | ||
| 19 | 19 | } from "node:fs"; |
| 20 | 20 | import { tmpdir } from "node:os"; |
| 21 | 21 | import { join } from "node:path"; |
| 22 | import { notedProcess } from "./fetch_work.ts"; | |
| 22 | 23 | |
| 23 | 24 | export interface PullPipe { |
| 24 | 25 | /** Hand to `Bun.spawn` as `stdout`; call `sealed()` once it has spawned. */ |
| @@ -45,6 +46,7 @@ export async function pullPipe( | ||
| 45 | 46 | onCancel: () => void = () => undefined, |
| 46 | 47 | ): Promise<PullPipe> { |
| 47 | 48 | const path = fifoPath(); |
| 49 | notedProcess(); | |
| 48 | 50 | const made = Bun.spawn(["mkfifo", "-m", "600", path], { |
| 49 | 51 | stdin: "ignore", |
| 50 | 52 | stdout: "ignore", |
src/git/smart-http.ts +77 −7
| @@ -22,6 +22,8 @@ import { transferDeadline, type Stall } from "./progress.ts"; | ||
| 22 | 22 | import { pacer } from "./pace.ts"; |
| 23 | 23 | import { bundleConfig } from "./bundle_uri.ts"; |
| 24 | 24 | 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"; | |
| 25 | 27 | |
| 26 | 28 | export type GitService = "git-upload-pack" | "git-receive-pack"; |
| 27 | 29 | |
| @@ -114,6 +116,31 @@ export interface SmartHttpOptions { | ||
| 114 | 116 | * a held reader's, so every want is seen before git is given it. |
| 115 | 117 | */ |
| 116 | 118 | 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" }); | |
| 117 | 144 | } |
| 118 | 145 | |
| 119 | 146 | /** How long a fetch's negotiation may go without a byte before it ends. */ |
| @@ -130,9 +157,9 @@ export async function advertiseRefs( | ||
| 130 | 157 | request: Request, |
| 131 | 158 | options: SmartHttpOptions = {}, |
| 132 | 159 | ): 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 | ); | |
| 136 | 163 | |
| 137 | 164 | const preamble = new TextEncoder().encode( |
| 138 | 165 | pktLine(`# service=${service}\n`) + FLUSH, |
| @@ -152,18 +179,28 @@ export async function advertiseRefs( | ||
| 152 | 179 | * Request body streams to git's stdin (gunzipped if the client compressed |
| 153 | 180 | * it); git's stdout streams back as the response. |
| 154 | 181 | */ |
| 155 | export async function serviceRpc( | |
| 182 | export function serviceRpc( | |
| 156 | 183 | repoDir: string, |
| 157 | 184 | service: GitService, |
| 158 | 185 | request: Request, |
| 159 | 186 | 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, | |
| 160 | 196 | ): Promise<Response> { |
| 161 | 197 | // A held reader's request is read whole first (it is the negotiation, a few |
| 162 | 198 | // kilobytes): what it wants is asked of the fork's own refs, then git gets it. |
| 163 | 199 | let read: Uint8Array | undefined; |
| 164 | 200 | const only = options.onlyWants; |
| 201 | const work = options.work; | |
| 165 | 202 | if ((options.ownRefsOnly === true || only !== undefined) && service === "git-upload-pack") { |
| 166 | read = await negotiation(request); | |
| 203 | read = await waited(negotiation(request)); | |
| 167 | 204 | const asked = read === undefined ? "bad" : wantsOf(read); |
| 168 | 205 | const beyond = asked !== "bad" && only !== undefined && asked.wants.some((want) => !only.includes(want)); |
| 169 | 206 | if ( |
| @@ -179,6 +216,16 @@ export async function serviceRpc( | ||
| 179 | 216 | }, |
| 180 | 217 | }); |
| 181 | 218 | } |
| 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 | } | |
| 182 | 229 | // What git is told it has and what it is told is shallow is held too. |
| 183 | 230 | try { |
| 184 | 231 | read = await heldNegotiation(repoDir, only).push(read!); |
| @@ -211,6 +258,28 @@ export async function serviceRpc( | ||
| 211 | 258 | }); |
| 212 | 259 | } |
| 213 | 260 | |
| 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 | ||
| 214 | 283 | /** |
| 215 | 284 | * Spawn one pack service, holding a transfer permit for its whole life. |
| 216 | 285 | * |
| @@ -235,7 +304,7 @@ async function spawnService( | ||
| 235 | 304 | options: SmartHttpOptions, |
| 236 | 305 | extraArgs: readonly string[], |
| 237 | 306 | ) { |
| 238 | const permit = await transferGate.acquire(); | |
| 307 | const permit = await waited(transferGate.acquire()); | |
| 239 | 308 | const release = (): void => { |
| 240 | 309 | permit(); |
| 241 | 310 | options.release?.(); |
| @@ -257,7 +326,8 @@ async function spawnService( | ||
| 257 | 326 | let pipe: PullPipe | undefined; |
| 258 | 327 | let proc: Bun.Subprocess<"pipe", number, "ignore">; |
| 259 | 328 | try { |
| 260 | pipe = await pullPipe(() => proc.kill("SIGKILL")); | |
| 329 | pipe = await waited(pullPipe(() => proc.kill("SIGKILL"))); | |
| 330 | notedProcess(); | |
| 261 | 331 | proc = Bun.spawn( |
| 262 | 332 | serviceCommand( |
| 263 | 333 | service, |
src/http/api/runners.ts +31 −4
| @@ -43,7 +43,11 @@ import { buildOf } from "../../kernel/version.ts"; | ||
| 43 | 43 | import { inFlight } from "../../perf/live.ts"; |
| 44 | 44 | import { appendRunLog } from "../../runs/log.ts"; |
| 45 | 45 | import { RUNNER_VERSION_HEADER } from "../../runner/upgrade.ts"; |
| 46 | import { join } from "node:path"; | |
| 46 | 47 | 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"; | |
| 47 | 51 | import type { Ctx, Handler } from "../context.ts"; |
| 48 | 52 | import { STRANGER_MAX } from "../limits.ts"; |
| 49 | 53 | import { apiError, body, boundedBody, json, notFound, str, tryAgain, unauthorized } from "../respond.ts"; |
| @@ -105,6 +109,18 @@ function readLend(raw: unknown): LendInput | undefined { | ||
| 105 | 109 | }; |
| 106 | 110 | } |
| 107 | 111 | |
| 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 | ||
| 108 | 124 | export function runnerRoutes(router: Router<Handler>): void { |
| 109 | 125 | router.add("POST", "/api/v1/admin/runners", async (ctx) => { |
| 110 | 126 | const denied = accountAdmin(ctx, "admin"); |
| @@ -347,22 +363,33 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 347 | 363 | }); |
| 348 | 364 | |
| 349 | 365 | // 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) => { | |
| 351 | 367 | const mine = held(ctx); |
| 352 | 368 | if ( |
| 353 | 369 | mine === undefined || |
| 354 | 370 | ctx.url.searchParams.get("service") !== "git-upload-pack" |
| 355 | 371 | ) |
| 356 | 372 | 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, { | |
| 358 | 376 | onlyWants: mine.job.wants, |
| 377 | share: packShareOf(ctx.app), | |
| 378 | work, | |
| 359 | 379 | }); |
| 380 | mine.ear.lines("", [workWords("git refs", work)]); | |
| 381 | return answer; | |
| 360 | 382 | }); |
| 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) => { | |
| 362 | 384 | const mine = held(ctx); |
| 363 | 385 | 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, { | |
| 365 | 388 | onlyWants: mine.job.wants, |
| 389 | share: packShareOf(ctx.app), | |
| 390 | work, | |
| 366 | 391 | }); |
| 392 | mine.ear.lines("", [workWords("git fetch", work)]); | |
| 393 | return answer; | |
| 367 | 394 | }); |
| 368 | 395 | } |
test/job-slices.test.ts +1
| @@ -300,6 +300,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 300 | 300 | * on. |
| 301 | 301 | */ |
| 302 | 302 | 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", | |
| 303 | 304 | "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", |
| 304 | 305 | "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", |
| 305 | 306 | "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 @@ | ||
| 2 | 2 | * Every synchronous file or process call on a request path is named here, with |
| 3 | 3 | * its reason (#17885). A stall comes back one cause at a time: a `readFileSync` |
| 4 | 4 | * 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: | |
| 7 | 7 | * a new call fails until it is cached, sliced, moved off the thread or named |
| 8 | 8 | * with a reason; a call that went away fails until its row shrinks, so the list |
| 9 | 9 | * only shrinks. It reads the source as text and never runs it, as |
| @@ -14,7 +14,20 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; | ||
| 14 | 14 | import { join, relative } from "node:path"; |
| 15 | 15 | |
| 16 | 16 | 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 | ]; | |
| 18 | 31 | const SYNC = ["spawnSync", "execSync", "readFileSync", "readdirSync", "statSync", "writeFileSync", "appendFileSync"] as const; |
| 19 | 32 | type SyncCall = (typeof SYNC)[number]; |
| 20 | 33 |
new above
offline