diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 863ccc0c7b697..1319174766471 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -36,7 +36,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud - Always compare refs with `ab ` on the same machine rather than comparing isolated runs. - Use `scaling` to separate per-thread cost from fixed server overhead, and `--soak ` to - spot rising heap slopes (leaks). + spot rising heap slopes (leaks). A leak only shows in code the soak drives, so give a new + subsystem with long-lived state a part in its workload. - Steer server work by `working`: many worktree threads editing files at once with one client subscribed to all of them. Turns per minute that stay flat as threads are added mean the server, not the agents, is the bottleneck. diff --git a/scripts/server-metrics-forge.ts b/scripts/server-metrics-forge.ts new file mode 100644 index 0000000000000..1422bc25f6436 --- /dev/null +++ b/scripts/server-metrics-forge.ts @@ -0,0 +1,614 @@ +// A fake GitHub Enterprise host for the server-metrics soak: the GitHub API the server polls for a +// web client, and a git remote it fetches from, both over HTTPS on loopback. +// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http2 server; the proxy is raw. +import * as NodeHttp from "node:http"; +import * as NodeHttp2 from "node:http2"; +import * as NodeNet from "node:net"; + +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { + PullRequestListInput, + PullRequestListResult, + PullRequestRef, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Console from "effect/Console"; +import * as Duration from "effect/Duration"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; + +import { run, ScenarioError } from "./scenarios/shell.ts"; + +const OWNER = "bench"; +const REPO = "project"; +const TOKEN = "ghp_bench_fake"; +/** + * The host the project's origin names. It carries no port because pull request listings key a + * GitHub host without one, so the server reaches it on 443 through a proxy that tunnels it here. + */ +const HOST = "bench.test"; + +export interface ForgeRequest { + readonly at: number; + readonly method: string; + readonly path: string; + /** The GraphQL operation name, for GraphQL requests. */ + readonly operation: string | undefined; + readonly status: number; +} + +const GraphQlRequest = Schema.Struct({ + query: Schema.optional(Schema.String), + operationName: Schema.optional(Schema.NullOr(Schema.String)), + variables: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))), +}); +const decodeGraphQl = Schema.decodeUnknownEffect(Schema.fromJsonString(GraphQlRequest)); + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +/** FNV-1a, enough to tell bodies apart. */ +const hash = (text: string) => { + let value = 0x811c9dc5; + for (let index = 0; index < text.length; index++) { + value = Math.imul(value ^ text.charCodeAt(index), 0x01000193) >>> 0; + } + return value.toString(16); +}; + +interface Failure { + readonly message: string; +} + +interface FakePullRequest { + readonly number: number; + readonly head: string; + oid: string; +} + +/** Serves the fake host until the scope closes. */ +export const serveFakeGitHub = Effect.fn("serverMetrics.serveFakeGitHub")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-forge-" }); + const keyFile = path.join(dir, "key.pem"); + const certFile = path.join(dir, "cert.pem"); + yield* run("openssl", [ + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-days", + "2", + "-subj", + `/CN=${HOST}`, + "-addext", + `subjectAltName=DNS:${HOST}`, + "-keyout", + keyFile, + "-out", + certFile, + ]); + const bare = path.join(dir, `${REPO}.git`); + yield* run("git", ["init", "-q", "--bare", bare]); + const requests: ForgeRequest[] = []; + const host = HOST; + const pullRequests: Array = [ + { number: 1, head: "bench/feature", oid: "0".repeat(40) }, + ...[2, 3, 4, 5].map((number) => ({ + number, + head: `bench/other-${number}`, + oid: "0".repeat(40), + })), + ]; + + const actor = { __typename: "User", id: "U_bench", login: OWNER, name: "Bench", avatarUrl: "" }; + /** Every field any of the polled reads selects; decoders ignore the ones a read did not ask for. */ + const pullRequestNode = (pr: FakePullRequest, now: number) => { + const minute = Math.floor(now / 60_000); + const at = (offsetMinutes: number) => + DateTime.formatIso(DateTime.makeUnsafe((minute - offsetMinutes) * 60_000)); + // The branch PR's CI reruns every other minute, so checks and their rollup keep changing. + const running = pr.number === 1 && minute % 2 === 0; + return { + __typename: "PullRequest", + id: `PR_bench_${pr.number}`, + number: pr.number, + title: `Bench change ${pr.number}`, + url: `https://${host}/${OWNER}/${REPO}/pull/${pr.number}`, + body: "A pull request the soak polls.", + baseRefName: "main", + headRefName: pr.head, + headRefOid: pr.oid, + state: "OPEN", + isDraft: false, + mergeable: "MERGEABLE", + mergeStateStatus: running ? "BLOCKED" : "CLEAN", + reviewDecision: null, + additions: 1, + deletions: 0, + changedFiles: 1, + createdAt: at(600 + pr.number), + updatedAt: at(0), + mergedAt: null, + mergeCommit: null, + mergedBy: null, + closedAt: null, + isCrossRepository: false, + maintainerCanModify: false, + headRepository: { name: REPO, nameWithOwner: `${OWNER}/${REPO}`, viewerPermission: "ADMIN" }, + headRepositoryOwner: { __typename: "User", login: OWNER }, + headRef: { id: `REF_bench_${pr.number}` }, + repository: { nameWithOwner: `${OWNER}/${REPO}` }, + author: actor, + autoMergeRequest: null, + viewerCanUpdate: true, + viewerDidAuthor: true, + viewerCanUpdateBranch: false, + baseRef: { compare: { behindBy: 0 } }, + reviewRequests: { nodes: [] }, + latestReviews: { nodes: [] }, + labels: { nodes: [] }, + commits: { + nodes: [ + { + commit: { + statusCheckRollup: { + state: running ? "PENDING" : "SUCCESS", + contexts: { + nodes: [ + { + __typename: "CheckRun", + name: "test", + status: running ? "IN_PROGRESS" : "COMPLETED", + conclusion: running ? null : "SUCCESS", + startedAt: at(1), + completedAt: running ? null : at(0), + detailsUrl: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`, + checkSuite: { + workflowRun: { + event: "pull_request", + runNumber: minute, + workflow: { id: "W_bench", name: "CI" }, + }, + }, + }, + { + __typename: "StatusContext", + context: "lint", + state: "SUCCESS", + targetUrl: null, + createdAt: at(5), + description: "Lint passed", + }, + ], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + }, + }, + ], + }, + }; + }; + const repositorySettings = { + mergeCommitAllowed: true, + squashMergeAllowed: true, + rebaseMergeAllowed: true, + autoMergeAllowed: false, + viewerPermission: "ADMIN", + }; + const page = (nodes: ReadonlyArray) => ({ + pageInfo: { hasNextPage: false, endCursor: null }, + nodes, + }); + + /** The `data` of a GraphQL answer, each aliased slice (`_0_repository`) answered on its own. */ + const answer = ( + operation: string, + variables: Readonly>, + now: number, + ): Record | undefined => { + const prefixes = new Set( + Object.keys(variables).map((name) => /^(_\d+_)?/.exec(name)?.[1] ?? ""), + ); + if (prefixes.size === 0) prefixes.add(""); + const data: Record = {}; + for (const prefix of prefixes) { + const variable = (name: string) => variables[`${prefix}${name}`]; + const byNumber = pullRequests.find((pr) => pr.number === variable("number")); + const single = byNumber === undefined ? null : pullRequestNode(byNumber, now); + const all = pullRequests.map((pr) => pullRequestNode(pr, now)); + switch (operation) { + case "PullRequestsByHead": + case "PullRequestHeads": + data[`${prefix}repository`] = { + pullRequests: page(all.filter((pr) => pr.headRefName === variable("head"))), + }; + break; + case "PullRequestList": + data[`${prefix}repository`] = { pullRequests: page(all) }; + break; + case "PullRequestSearch": + data[`${prefix}search`] = page(all); + break; + case "PullRequestByNumber": + case "PullRequestSummary": + case "PullRequestStats": + case "PullRequestCheckContexts": + data[`${prefix}repository`] = { pullRequest: single }; + break; + case "PullRequestCore": + data[`${prefix}repository`] = { ...repositorySettings, pullRequest: single }; + break; + case "RoutingIdentityViewer": + data[`${prefix}viewer`] = { databaseId: 1, login: OWNER }; + break; + case "ActorAvatars": { + const ids = variable("ids"); + data[`${prefix}nodes`] = (Array.isArray(ids) ? ids : []).map(() => actor); + break; + } + default: + return undefined; + } + } + return data; + }; + + /** REST answers by path under /api/v3; the body moves each minute where real polling sees change. */ + const restAnswer = (path: string, now: number): unknown => { + const minute = Math.floor(now / 60_000); + const repository = `repos/${OWNER}/${REPO}`; + if (path === "user") + return { login: OWNER, id: 1, name: "Bench", avatar_url: "", type: "User" }; + if (path === repository) { + return { + id: 1, + node_id: "R_bench", + name: REPO, + full_name: `${OWNER}/${REPO}`, + private: false, + default_branch: "main", + html_url: `https://${host}/${OWNER}/${REPO}`, + owner: { login: OWNER, id: 1, type: "User" }, + permissions: { admin: true, maintain: true, push: true, triage: true, pull: true }, + }; + } + if (path === `${repository}/actions/runs`) { + return { + total_count: minute % 2 === 0 ? 1 : 0, + workflow_runs: + minute % 2 === 0 + ? [ + { + id: minute, + name: "CI", + html_url: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`, + status: "in_progress", + }, + ] + : [], + }; + } + return undefined; + }; + + const serveGit = Effect.fn("serverMetrics.fakeGitHub.git")(function* (relative: string) { + if (relative.split("/").includes("..")) return HttpServerResponse.empty({ status: 404 }); + const file = path.join(bare, relative); + const body = yield* fs.readFile(file).pipe(Effect.option); + return body._tag === "Some" + ? HttpServerResponse.uint8Array(body.value, { contentType: "application/octet-stream" }) + : HttpServerResponse.empty({ status: 404 }); + }); + + const app = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = new URL(request.url, "https://127.0.0.1"); + const gitPrefix = `/${OWNER}/${REPO}.git/`; + let operation: string | undefined; + let response: HttpServerResponse.HttpServerResponse; + if (url.pathname.startsWith(gitPrefix)) { + // Dumb HTTP: a static info/refs makes git fall back to reading the bare repository's files. + response = yield* serveGit(url.pathname.slice(gitPrefix.length)); + } else if (url.pathname === "/api/graphql") { + const raw = yield* request.text; + const body = yield* decodeGraphQl(raw).pipe( + Effect.orElseSucceed((): typeof GraphQlRequest.Type => ({})), + ); + operation = + body.operationName ?? + /\b(?:query|mutation)\s+(\w+)/.exec(body.query ?? "")?.[1] ?? + "anonymous"; + const data = answer(operation, body.variables ?? {}, yield* Clock.currentTimeMillis); + response = + data === undefined + ? HttpServerResponse.jsonUnsafe({ message: "Not Found" }, { status: 404 }) + : HttpServerResponse.jsonUnsafe({ data }); + } else { + const body = url.pathname.startsWith("/api/v3/") + ? restAnswer(url.pathname.slice("/api/v3/".length), yield* Clock.currentTimeMillis) + : undefined; + if (body === undefined) { + response = HttpServerResponse.jsonUnsafe( + { message: "Not Found", documentation_url: "https://docs.github.com/rest" }, + { status: 404 }, + ); + } else { + // A weak validator of the body, so an unchanged answer revalidates as a 304. + const text = encodeJson(body); + const etag = `W/"${text.length.toString(16)}-${hash(text)}"`; + response = + request.headers["if-none-match"] === etag + ? HttpServerResponse.empty({ status: 304, headers: { etag } }) + : HttpServerResponse.text(text, { + contentType: "application/json", + headers: { etag }, + }); + } + } + requests.push({ + at: yield* Clock.currentTimeMillis, + method: request.method, + path: url.pathname + url.search, + operation, + status: response.status, + }); + return response; + }).pipe(Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500 }))); + + const key = yield* fs.readFileString(keyFile); + const cert = yield* fs.readFileString(certFile); + const context = yield* Layer.build( + NodeHttpServer.layer(() => NodeHttp2.createSecureServer({ key, cert, allowHTTP1: true }), { + port: 0, + host: "127.0.0.1", + }), + ); + const port = yield* Effect.gen(function* () { + yield* HttpServer.serveEffect(Effect.interruptible(app)); + const { address } = yield* HttpServer.HttpServer; + return address._tag === "UnixPathAddress" ? 0 : address.port; + }).pipe(Effect.provide(context)); + // Tunnels only the fake host, so nothing the server sends through it reaches the internet. + const tunnels = new Set(); + const proxy = NodeHttp.createServer((_request, response) => { + response.writeHead(405).end(); + }); + proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => { + if (request.url !== `${HOST}:443`) { + client.end("HTTP/1.1 403 Forbidden\r\n\r\n"); + return; + } + const upstream = NodeNet.connect(port, "127.0.0.1", () => { + client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + upstream.pipe(client); + client.pipe(upstream); + }); + for (const socket of [client, upstream]) { + tunnels.add(socket); + socket.on("close", () => tunnels.delete(socket)); + socket.on("error", () => { + client.destroy(); + upstream.destroy(); + }); + } + }); + const proxyPort = yield* Effect.acquireRelease( + Effect.callback((resume) => { + proxy.once("error", (error) => + resume( + Effect.fail(new ScenarioError({ message: `the fake GitHub proxy: ${error.message}` })), + ), + ); + proxy.listen(0, "127.0.0.1", () => { + const address = proxy.address(); + resume(Effect.succeed(typeof address === "object" && address !== null ? address.port : 0)); + }); + }), + () => + Effect.callback((resume) => { + for (const socket of tunnels) socket.destroy(); + proxy.closeAllConnections(); + proxy.close(() => resume(Effect.void)); + }), + ); + const proxyUrl = `http://127.0.0.1:${proxyPort}`; + + /** Publishes the project to the fake remote and checks out a branch with an open PR. */ + const setupProject = Effect.fn("serverMetrics.fakeGitHub.setupProject")(function* ( + project: string, + ) { + const git = (args: ReadonlyArray) => run("git", args, { cwd: project }); + yield* git(["switch", "-q", "-c", "bench/feature"]); + yield* fs.writeFileString(path.join(project, "FEATURE.md"), "# feature\n"); + yield* git(["add", "."]); + yield* git([ + "-c", + "user.email=bench@t3.codes", + "-c", + "user.name=bench", + "commit", + "-qm", + "feature", + ]); + yield* git(["push", "-q", bare, "main", "bench/feature"]); + yield* run("git", ["--git-dir", bare, "update-server-info"]); + yield* git(["remote", "add", "origin", `https://${host}/${OWNER}/${REPO}.git`]); + yield* git(["config", "http.sslCAInfo", certFile]); + yield* git(["config", "http.proxy", proxyUrl]); + // A developer's NO_PROXY could send this past the proxy, which is the only route to the host. + const hostEnvironment = yield* HostProcess.Environment; + yield* run("git", ["fetch", "-q", "origin"], { + cwd: project, + env: { + ...Object.fromEntries( + Object.entries(hostEnvironment).filter( + (entry): entry is [string, string] => entry[1] !== undefined, + ), + ), + NO_PROXY: "", + no_proxy: "", + GIT_SSL_CAINFO: certFile, + }, + }); + yield* git(["branch", "-q", "--set-upstream-to", "origin/bench/feature"]); + const [feature, main] = (yield* git(["rev-parse", "HEAD", "main"])).stdout.trim().split("\n"); + for (const pr of pullRequests) pr.oid = (pr.number === 1 ? feature : main) ?? pr.oid; + setupRequests = requests.length; + publishedMain = main; + }); + + let pushes = 0; + /** Lands a commit on the remote's main, so the server's next fetch transfers something. */ + const advanceRemote = Effect.gen(function* () { + const git = (args: ReadonlyArray) => run("git", ["--git-dir", bare, ...args]); + const commit = (yield* git([ + "-c", + "user.email=bench@t3.codes", + "-c", + "user.name=bench", + "commit-tree", + "main^{tree}", + "-p", + "main", + "-m", + `upstream ${++pushes}`, + ])).stdout.trim(); + yield* git(["update-ref", "refs/heads/main", commit]); + yield* git(["update-server-info"]); + }); + + /** Requests the project setup made before the server started, which `verify` leaves out. */ + let setupRequests = 0; + let publishedMain: string | undefined; + let fetchedPush = false; + let completedPolls = 0; + const failures: Array = []; + /** + * What a web client with the pull requests sidebar and the branch's PR open asks for: the list, + * then the branch PR's summary and checks, every 30 s until interrupted. Failures are kept, not + * thrown, so one bad answer does not end the soak. + */ + const pollLikeWebClient = Effect.fn("serverMetrics.fakeGitHub.poll")(function* (rpc: { + readonly list: (input: PullRequestListInput) => Effect.Effect; + readonly summary: (input: PullRequestRef) => Effect.Effect; + readonly checks: (input: PullRequestRef) => Effect.Effect; + }) { + const record = (what: string) => (error: Failure) => + Effect.sync(() => { + failures.push(`${what}: ${error.message}`); + }); + while (true) { + const listed = yield* rpc + .list({ state: "open" }) + .pipe(Effect.tapError(record("pullRequests.list")), Effect.option); + const entry = + listed._tag === "Some" + ? listed.value.entries.find((row) => row.headBranch === "bench/feature") + : undefined; + if (listed._tag === "Some" && entry === undefined) { + failures.push(`pullRequests.list: no branch PR in ${listed.value.entries.length} rows`); + } + if (entry !== undefined) { + const ref = { + projectId: entry.projectId, + host: entry.host, + repository: entry.repository, + number: entry.number, + }; + const completed = yield* Effect.all([rpc.summary(ref), rpc.checks(ref)]).pipe( + Effect.as(true), + Effect.catch((error) => + record("pullRequests.summary/checks")(error).pipe(Effect.as(false)), + ), + ); + if (completed) completedPolls++; + } + yield* Effect.sleep(Duration.seconds(30)); + } + }); + + return { + host, + /** The server's view of the host: the fake token and CA, and none of the developer's logins. */ + env: { + GH_HOST: host, + GH_ENTERPRISE_TOKEN: TOKEN, + GITHUB_ENTERPRISE_TOKEN: "", + GH_TOKEN: "", + GITHUB_TOKEN: "", + // An empty gh config, so a gh the server runs has no login for any host. + GH_CONFIG_DIR: path.join(dir, "gh"), + NODE_EXTRA_CA_CERTS: certFile, + // Overrides a developer's own GIT_SSL_CAINFO, which would win over the repository's setting. + GIT_SSL_CAINFO: certFile, + NODE_USE_ENV_PROXY: "1", + HTTPS_PROXY: proxyUrl, + https_proxy: proxyUrl, + // The fake Anthropic API and the server's own loopback listeners stay direct. + NO_PROXY: "127.0.0.1,localhost,::1", + no_proxy: "127.0.0.1,localhost,::1", + }, + setupProject, + advanceRemote, + /** Records whether the project's origin/main moved past setup, i.e. the server fetched a push. */ + checkFetched: (project: string) => + run("git", ["rev-parse", "refs/remotes/origin/main"], { cwd: project }).pipe( + Effect.map(({ stdout }) => { + fetchedPush = stdout.trim() !== publishedMain; + }), + ), + requests: requests as ReadonlyArray, + pollLikeWebClient, + /** + * Prints what the server asked for, and fails unless it polled pull requests and checks and + * fetched from the remote. Poller failures are reported, not fatal: a long soak can see one. + */ + verify: Effect.gen(function* () { + const counts = new Map(); + for (const request of requests.slice(setupRequests)) { + const key = + request.operation ?? + (request.path.startsWith(`/${OWNER}/${REPO}.git/`) + ? request.status !== 200 + ? undefined + : request.path.startsWith(`/${OWNER}/${REPO}.git/info/refs`) + ? "git fetch" + : undefined + : `${request.method} ${request.path.replace(/\?.*/, "")} ${request.status}`); + if (key !== undefined) counts.set(key, (counts.get(key) ?? 0) + 1); + } + const listed = [...counts].map(([key, count]) => `${key} ×${count}`).join(", "); + yield* Console.error(`fake GitHub served ${requests.length} requests: ${listed}`); + if (failures.length > 0) { + yield* Console.error( + `fake GitHub: ${failures.length} client polls failed, first: ${failures[0]}`, + ); + } + const missing = [ + "PullRequestsByHead", + "PullRequestSearch", + "PullRequestCore", + "git fetch", + ].filter((key) => !counts.has(key)); + if (pushes > 0 && !fetchedPush) missing.push("a fetch that brought in a pushed commit"); + if (completedPolls === 0) missing.push("one full client poll (list, summary, checks)"); + if (missing.length > 0) { + return yield* new ScenarioError({ + message: `the soak never reached the fake GitHub for ${missing.join(", ")}`, + }); + } + }), + }; +}); + +export type FakeGitHub = Effect.Success>; diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index b06e08a590af0..bab911ab9124f 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -37,6 +37,8 @@ const Soak = Schema.Struct({ minutes: Schema.Number, heapMBPerHour: Schema.Number, rssMBPerHour: Schema.Number, + /** Processes below the server, so agent or git children that outlive their thread show. */ + childProcessesPerHour: Schema.optional(Schema.Number), }); const MachineState = Schema.Struct({ @@ -161,6 +163,14 @@ export const HeapGrowth = Schema.Struct({ MB: Schema.Number, }); +/** An object whose retained size grew at every soak snapshot, and how it is reached. */ +export const RetainerGrowth = Schema.Struct({ + path: Schema.String, + MB: Schema.Number, + retainedMB: Schema.Number, +}); +export type RetainerGrowth = typeof RetainerGrowth.Type; + export const ServerMetrics = Schema.Struct({ meta: Schema.Record( Schema.String, @@ -170,6 +180,7 @@ export const ServerMetrics = Schema.Struct({ /** Top CPU self time (ms) and allocated MB by function, from the last run. */ profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), + soakRetainerGrowth: Schema.optional(Schema.Array(RetainerGrowth)), }); export type ServerMetrics = typeof ServerMetrics.Type; @@ -703,19 +714,24 @@ export function summarizeProfiles( return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; } +const TypeNames = Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])); export const HeapSnapshot = Schema.Struct({ snapshot: Schema.Struct({ meta: Schema.Struct({ node_fields: Schema.Array(Schema.String), - node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), + node_types: TypeNames, + edge_fields: Schema.Array(Schema.String), + edge_types: TypeNames, }), }), nodes: Schema.Array(Schema.Number), + edges: Schema.Array(Schema.Number), strings: Schema.Array(Schema.String), }); +type HeapSnapshot = typeof HeapSnapshot.Type; /** Self size by constructor from a V8 heap snapshot. */ -export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { +export function heapByConstructor(snapshot: HeapSnapshot) { const fields = snapshot.snapshot.meta.node_fields; const typeNames = snapshot.snapshot.meta.node_types[0]; const types = Array.isArray(typeNames) ? typeNames : []; @@ -757,6 +773,253 @@ export function heapGrowth( .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); } +interface Retainer { + readonly retained: number; + /** The id of the node that dominates this one, none for the root. */ + readonly dominator: number | undefined; + /** Empty below `pathBytes`: such a node is only kept to compare sizes across snapshots. */ + readonly path: string; +} + +const TEXT_NODES = new Set(["string", "concatenated string", "sliced string", "regexp", "number"]); +const IDENTIFIER = /^[A-Za-z_$#][\w$]{0,48}$/; + +/** + * Retained size by node id for every node retaining at least `minBytes`, and for those retaining + * `pathBytes` the shortest strong path from the root to it. Node ids are stable within one process, so snapshots of one + * server line up. Paths name only code: string contents and non-identifier keys are left out. + */ +export function heapRetainers(snapshot: HeapSnapshot, minBytes = 16_000, pathBytes = 256_000) { + const { meta } = snapshot.snapshot; + const nodeFields = meta.node_fields.length; + const edgeFields = meta.edge_fields.length; + const list = (names: typeof meta.node_types) => { + const first = names[0]; + return Array.isArray(first) ? first : []; + }; + const nodeTypes = list(meta.node_types); + const edgeTypes = list(meta.edge_types); + const [typeAt, nameAt, idAt, sizeAt, edgeCountAt] = [ + "type", + "name", + "id", + "self_size", + "edge_count", + ].map((field) => meta.node_fields.indexOf(field)) as [number, number, number, number, number]; + const [edgeTypeAt, edgeNameAt, toAt] = ["type", "name_or_index", "to_node"].map((field) => + meta.edge_fields.indexOf(field), + ) as [number, number, number]; + const { nodes, edges, strings } = snapshot; + const count = nodes.length / nodeFields; + const firstEdge = new Uint32Array(count + 1); + for (let node = 0, offset = 0; node < count; node++) { + firstEdge[node] = offset; + offset += nodes[node * nodeFields + edgeCountAt]! * edgeFields; + firstEdge[node + 1] = offset; + } + const weak = edgeTypes.indexOf("weak"); + const shortcut = edgeTypes.indexOf("shortcut"); + const strong = (edge: number) => + edges[edge + edgeTypeAt] !== weak && edges[edge + edgeTypeAt] !== shortcut; + const target = (edge: number) => edges[edge + toAt]! / nodeFields; + + // Postorder from the root, then dominators by Cooper, Harvey and Kennedy's iteration. + const postorder = new Int32Array(count).fill(-1); + const order = new Int32Array(count); + const stack = new Int32Array(count); + const cursor = new Uint32Array(count); + const seen = new Uint8Array(count); + let depth = 0; + let visited = 0; + stack[depth++] = 0; + seen[0] = 1; + cursor[0] = firstEdge[0]!; + while (depth > 0) { + const node = stack[depth - 1]!; + if (cursor[node]! < firstEdge[node + 1]!) { + const edge = cursor[node]!; + cursor[node] = edge + edgeFields; + const next = target(edge); + if (strong(edge) && !seen[next]) { + seen[next] = 1; + cursor[next] = firstEdge[next]!; + stack[depth++] = next; + } + } else { + depth--; + postorder[node] = visited; + order[visited++] = node; + } + } + const predecessorStart = new Uint32Array(count + 1); + for (let node = 0; node < count; node++) { + if (!seen[node]) continue; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + if (strong(edge)) predecessorStart[target(edge) + 1]!++; + } + } + for (let node = 0; node < count; node++) predecessorStart[node + 1]! += predecessorStart[node]!; + const predecessors = new Int32Array(predecessorStart[count]!); + const fill = predecessorStart.slice(0, count); + for (let node = 0; node < count; node++) { + if (!seen[node]) continue; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + if (strong(edge)) predecessors[fill[target(edge)]!++] = node; + } + } + const dominator = new Int32Array(count).fill(-1); + dominator[0] = 0; + const intersect = (left: number, right: number) => { + while (left !== right) { + while (postorder[left]! < postorder[right]!) left = dominator[left]!; + while (postorder[right]! < postorder[left]!) right = dominator[right]!; + } + return left; + }; + for (let changed = true; changed;) { + changed = false; + for (let index = visited - 2; index >= 0; index--) { + const node = order[index]!; + let found = -1; + for (let at = predecessorStart[node]!; at < predecessorStart[node + 1]!; at++) { + const predecessor = predecessors[at]!; + if (dominator[predecessor] === -1) continue; + found = found === -1 ? predecessor : intersect(predecessor, found); + } + if (found !== -1 && dominator[node] !== found) { + dominator[node] = found; + changed = true; + } + } + } + const retained = new Float64Array(count); + for (let node = 0; node < count; node++) retained[node] = nodes[node * nodeFields + sizeAt]!; + for (let index = 0; index < visited - 1; index++) { + const node = order[index]!; + retained[dominator[node]!]! += retained[node]!; + } + + const parent = new Int32Array(count).fill(-1); + const parentEdge = new Int32Array(count).fill(-1); + const queue = new Int32Array(count); + let head = 0; + let tail = 0; + queue[tail++] = 0; + parent[0] = 0; + while (head < tail) { + const node = queue[head++]!; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + const next = target(edge); + if (!strong(edge) || parent[next] !== -1) continue; + parent[next] = node; + parentEdge[next] = edge; + queue[tail++] = next; + } + } + const nodeType = (node: number) => nodeTypes[nodes[node * nodeFields + typeAt]!] ?? "?"; + const label = (node: number) => { + const type = nodeType(node); + if (TEXT_NODES.has(type)) return `(${type})`; + const name = strings[nodes[node * nodeFields + nameAt]!] ?? ""; + const shown = name.length > 60 || /["'`\n\\]|:\/\/|(^|\s)\/[\w.]/.test(name) ? "?" : name; + if (type === "object") return shown; + if (type === "closure") return `${shown || "(anonymous)"}()`; + return `(${type}${shown ? ` ${shown}` : ""})`; + }; + const edgeName = (edge: number) => { + const type = edgeTypes[edges[edge + edgeTypeAt]!]; + const value = edges[edge + edgeNameAt]!; + if (type === "element" || type === "hidden") return `[${value}]`; + const name = strings[value] ?? ""; + return IDENTIFIER.test(name) ? name : ""; + }; + const pathTo = (node: number) => { + const steps: string[] = []; + for (let at = node; at !== 0 && steps.length < 40; at = parent[at]!) { + if (parent[at] === -1) return "(unreachable)"; + const from = parent[at]!; + steps.push( + from === 0 || nodeType(from) === "synthetic" + ? edgeName(parentEdge[at]!) + : `${label(from)}.${edgeName(parentEdge[at]!)}`, + ); + if (nodeType(from) === "synthetic") break; + } + const shown = steps.reverse(); + return [...(shown.length > 6 ? ["…", ...shown.slice(-6)] : shown), label(node)].join(" → "); + }; + const result = new Map(); + for (let node = 0; node < count; node++) { + if (!seen[node] || retained[node]! < minBytes) continue; + result.set(nodes[node * nodeFields + idAt]!, { + retained: retained[node]!, + dominator: node === 0 ? undefined : nodes[dominator[node]! * nodeFields + idAt]!, + path: + retained[node]! < pathBytes + ? "" + : nodeType(node) === "synthetic" + ? label(node) + : pathTo(node), + }); + } + return result; +} + +/** + * The objects whose retained size grew from each snapshot to the next, at least `minBytes` in all. + * An object is left out when a reported object it dominates holds at least 80% of its growth: of + * a chain that grew by about the same amount, only the deepest is kept, the container holding the + * growth. Nested objects whose growth differs are each reported. + */ +export function retainerGrowth( + snapshots: ReadonlyArray>, + minBytes = 1_000_000, +) { + const last = snapshots.at(-1); + if (last === undefined || snapshots.length < 2) return []; + const growth = new Map(); + for (const [id, { retained, path }] of last) { + if (path === "" || path.startsWith("(synthetic")) continue; + const sizes = [ + ...snapshots.slice(0, -1).map((snapshot) => snapshot.get(id)?.retained ?? 0), + retained, + ]; + const grewEachTime = sizes.every((size, index) => index === 0 || size > sizes[index - 1]!); + const grown = retained - sizes[0]!; + if (grewEachTime && grown >= minBytes) growth.set(id, grown); + } + const ancestors = (id: number) => { + const found: number[] = []; + for (let at = last.get(id)?.dominator; at !== undefined && found.length < 500;) { + found.push(at); + at = last.get(at)?.dominator; + } + return found; + }; + // Deepest first, so every descendant is decided before its ancestors: a row is left out + // only when a reported descendant holds at least 80% of its growth. + const heldBelow = new Map(); + const kept: Array<[number, number]> = []; + const depth = new Map([...growth.keys()].map((id) => [id, ancestors(id).length])); + const order = [...growth].toSorted((a, b) => depth.get(b[0])! - depth.get(a[0])!); + for (const [id, grown] of order) { + if ((heldBelow.get(id) ?? 0) >= grown * 0.8) continue; + kept.push([id, grown]); + for (const ancestor of ancestors(id)) { + heldBelow.set(ancestor, Math.max(heldBelow.get(ancestor) ?? 0, grown)); + } + } + const rows: RetainerGrowth[] = kept + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([id, grown]) => ({ + path: last.get(id)!.path, + MB: round(grown / 1e6, 2), + retainedMB: round(last.get(id)!.retained / 1e6, 2), + })); + return rows; +} + const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String)); const spellings: ReadonlyArray<(path: string) => string> = [ (path) => path, diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 6597e9297514b..9baf6a86369a2 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -9,6 +9,7 @@ import { activityRenewalMissed, describeFailure, heapGrowth, + heapRetainers, loadWarnings, nextActivityReport, noiseReport, @@ -16,6 +17,7 @@ import { parsePsCpuTime, profileMismatch, parseRunSelection, + retainerGrowth, pathRewrites, pathSpellings, ServerMetrics, @@ -467,6 +469,87 @@ describe("heapGrowth", () => { }); }); +describe("heapRetainers", () => { + it("sums what each object alone keeps alive and names only code on the way to it", () => { + // root → Holder.cache → Map → [0] array → [0] string; Holder also points at the string weakly. + const node = (type: number, name: number, id: number, size: number, edges: number) => [ + type, + name, + id, + size, + edges, + ]; + const retainers = heapRetainers( + { + snapshot: { + meta: { + node_fields: ["type", "name", "id", "self_size", "edge_count"], + node_types: [["synthetic", "object", "array", "string"]], + edge_fields: ["type", "name_or_index", "to_node"], + edge_types: [["property", "element", "weak", "hidden"]], + }, + }, + nodes: [ + ...node(0, 4, 1, 0, 1), + ...node(1, 1, 3, 100, 2), + ...node(1, 2, 5, 50, 1), + ...node(2, 0, 7, 1_000, 1), + ...node(3, 5, 9, 500, 0), + ], + edges: [0, 6, 5, 0, 3, 10, 2, 0, 20, 3, 0, 15, 1, 0, 20], + strings: ["", "Holder", "Map", "cache", "(GC roots)", "a secret", "holder"], + }, + 0, + 0, + ); + expect(retainers.get(5)).toEqual({ + retained: 1_550, + dominator: 3, + path: "holder → Holder.cache → Map", + }); + expect(retainers.get(3)?.retained).toBe(1_650); + expect(retainers.get(9)?.path).toBe("holder → Holder.cache → Map.[0] → (array).[0] → (string)"); + }); +}); + +describe("retainerGrowth", () => { + const at = (sizes: Record) => + new Map( + Object.entries(sizes).map(([id, retained]) => [ + Number(id), + { retained, dominator: Number(id) === 3 ? undefined : 3, path: `node ${id}` }, + ]), + ); + it("reports the deepest object holding the growth, and only growth at every snapshot", () => { + const growth = retainerGrowth([ + at({ 3: 1_000_000, 5: 900_000, 7: 2_000_000 }), + at({ 3: 3_000_000, 5: 2_900_000, 7: 4_000_000 }), + at({ 3: 5_000_000, 5: 4_900_000, 7: 3_500_000 }), + ]); + expect(growth).toEqual([{ path: "node 5", MB: 4, retainedMB: 4.9 }]); + }); + it("keeps an ancestor its reported descendant does not account for", () => { + // A chain 1 → 2 → 3 growing by 7, 6 and 5 MB, and 4 under 1 growing by 2 MB. + const chain = (scale: number) => + new Map( + [ + [1, 7, undefined], + [2, 6, 1], + [3, 5, 2], + [4, 2, 1], + ].map(([id, mb, dominator]) => [ + id!, + { retained: (10 + mb! * scale) * 1e6, dominator, path: `node ${id}` }, + ]), + ); + expect(retainerGrowth([chain(0), chain(0.5), chain(1)]).map(({ path }) => path)).toEqual([ + "node 1", + "node 3", + "node 4", + ]); + }); +}); + describe("slope", () => { it("fits the cost per thread", () => { const points: Array = [ diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 9fa06fcfdea5c..6f553bcea38c1 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -57,6 +57,7 @@ import * as Scope from "effect/Scope"; import * as Socket from "effect/socket/Socket"; import { run } from "./scenarios/shell.ts"; +import { serveFakeGitHub, type FakeGitHub } from "./server-metrics-forge.ts"; import { compareMetrics, CpuProfile, @@ -65,6 +66,9 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + heapRetainers, + retainerGrowth, + type RetainerGrowth, competingBetween, loadWarnings, noiseReport, @@ -135,6 +139,9 @@ const RECONNECT_CLIENTS = 3; const RECONNECT_THREADS = 10; /** Clients that drop and reconnect at once in the opt-in storm, each holding one thread. */ const STORM_CLIENTS = 20; +/** Threads the soak keeps open; every few turns the oldest is replaced. */ +const SOAK_THREADS = 10; +const SOAK_CHURN_TURNS = 4; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; const LoopStats = Schema.Struct({ @@ -523,7 +530,8 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); const json = chunks.join(""); chunks.length = 0; - return heapByConstructor(yield* decodeJson(HeapSnapshot)(json)); + const snapshot = yield* decodeJson(HeapSnapshot)(json); + return { byConstructor: heapByConstructor(snapshot), retainers: heapRetainers(snapshot) }; }), }; }); @@ -582,7 +590,8 @@ const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: n } } else if (platform === "darwin") { const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]); - for (const line of Option.getOrElse(table, () => "").split("\n")) { + if (Option.isNone(table)) return yield* new MetricsError({ message: "ps listed no processes" }); + for (const line of table.value.split("\n")) { const [child, parent] = line.trim().split(/\s+/).map(Number); if (child && parent) add(child, parent); } @@ -611,6 +620,8 @@ interface Environment { interface ServerOptions { /** A base dir `migrate-dev-db` prepared; the server starts on a copy of its database. */ readonly seed?: string; + /** A fake GitHub host the project's origin points at. */ + readonly forge?: FakeGitHub; } /** Transcript text: paths there are words in a conversation, which the server never acts on. */ @@ -834,12 +845,14 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( yield* fs.makeDirectory(project); yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n"); for (const args of [ - ["init", "-q", "-b", "main"], + // Loose refs on purpose: the soak writes them as files, which a reftable store would ignore. + ["-c", "init.defaultRefFormat=files", "init", "-q", "-b", "main"], ["add", "."], ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], ]) { yield* run("git", args, { cwd: project }); } + if (options.forge !== undefined) yield* options.forge.setupProject(project); const baseDir = path.join(directory, "base"); // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); @@ -872,6 +885,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", OTEL_SDK_DISABLED: "true", T3CODE_DEV_SEED: "0", + ...options.forge?.env, }; const port = yield* freePort; const started = yield* nowMs; @@ -1025,6 +1039,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( return { readyMs, + pid, startedAt: started, origin: `http://127.0.0.1:${port}`, /** The seeded projects' clones; none without a seed. */ @@ -1247,6 +1262,8 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( threadId: string, item: OrchestrationV2ThreadStreamItem, ) => Effect.Effect = () => Effect.void, + /** How long the server may go silent before the client drops the connection or a report fails. */ + pingTimeout?: Duration.Input, ) { const http = yield* HttpClient.HttpClient; // Headers alone do not finish a request; the deadline covers the body too. @@ -1265,7 +1282,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ); const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))(ticketBody); const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( + RpcClient.layerProtocolSocket(pingTimeout === undefined ? {} : { pingTimeout }).pipe( Layer.provide( Socket.layerWebSocket( `${server.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, @@ -1279,6 +1296,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( // client costs, so the first such loss is kept for `healthy` to report. const lost = yield* Ref.make(undefined); const ready = Effect.fn("serverMetrics.subscription")(function* ( + name: string, stream: Stream.Stream, isReady: (item: A) => boolean, onItem: (item: A) => Effect.Effect = () => Effect.void, @@ -1294,8 +1312,10 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( Effect.andThen(isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void), ), ), - Effect.andThen(lose("a subscription ended")), - Effect.catchCause(() => lose("a subscription failed")), + Effect.andThen(lose(`the ${name} subscription ended`)), + Effect.catchCause((cause) => + lose(`the ${name} subscription failed: ${describeFailure(Cause.squash(cause))}`), + ), Effect.forkScoped, ); return Deferred.await(synchronized); @@ -1317,7 +1337,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }).pipe( // A server that keeps the socket open but never answers would otherwise hang the scenario. Effect.timeoutOrElse({ - duration: Duration.seconds(15), + duration: pingTimeout ?? Duration.seconds(15), orElse: () => new MetricsError({ message: "an activity report got no answer" }), }), ); @@ -1346,6 +1366,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( const synchronized = (item: { readonly kind: string }) => item.kind === "synchronized"; const waits = [ yield* ready( + "shell", client["orchestration.subscribeShell"]({ requestCompletionMarker: true, omitIdleSubagents: true, @@ -1353,9 +1374,10 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), synchronized, ), - yield* ready(client.subscribeVcsStatus({ cwd: server.project }), () => true), + yield* ready("VCS status", client.subscribeVcsStatus({ cwd: server.project }), () => true), ...(yield* Effect.forEach(threadIds, (threadId) => ready( + `thread ${threadId}`, client["orchestration.subscribeThread"]({ threadId: ThreadId.make(threadId), requestCompletionMarker: true, @@ -1390,6 +1412,14 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( creationSource: "web", dispatchMode: { type: "start_immediately" }, }), + rpc: client, + /** Archives or deletes a thread the way the sidebar does. */ + retire: (type: "thread.archive" | "thread.delete", threadId: string, commandId: string) => + client["orchestration.dispatchCommand"]({ + type, + commandId: CommandId.make(commandId), + threadId: ThreadId.make(threadId), + }), /** Fails if any of this client's subscriptions or reports was lost since it attached. */ healthy: Effect.flatMap(Ref.get(lost), (message) => message === undefined ? Effect.void : Effect.fail(new MetricsError({ message })), @@ -1640,6 +1670,7 @@ interface RunOptions { /** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; + const platform = yield* HostProcess.Platform; const path = yield* Path.Path; const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); @@ -1658,6 +1689,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; const profiles: Record = {}; let soakHeapGrowth: ReturnType | undefined; + let soakRetainerGrowth: ReadonlyArray | undefined; const withServer = ( name: string, body: (server: Server) => Effect.Effect, @@ -1916,50 +1948,165 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption ); } if (options.soakMinutes > 0) { - yield* withServer("soak", (server) => - Effect.gen(function* () { - const threads = yield* openThreads(server, 0, 10); - yield* Effect.sleep(Duration.seconds(60)); - // The snapshot inflates RSS once, so the slopes start after it. - const before = yield* server.snapshot; - const samples: Array<{ hours: number; window: Window }> = []; - const start = yield* nowMs; - const elapsed = Effect.map(nowMs, (now) => now - start); - const takeSample = Effect.gen(function* () { - samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); - }); - let nextSample = 0; - for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { - if ((yield* elapsed) >= nextSample) { - yield* takeSample; - nextSample += 120_000; + const forge = yield* serveFakeGitHub(); + yield* withServer( + "soak", + (server) => + Effect.gen(function* () { + let threads = yield* openThreads(server, 0, SOAK_THREADS); + // A busy repository under a web client: thousands of loose remote-tracking refs, more + // arriving every turn as fetches and agent branches add them, so caches keyed by ref + // state churn the way they do on a real checkout. + const head = (yield* run("git", ["rev-parse", "HEAD"], { cwd: server.project })).stdout; + // Under a remote with no config, so no fetch (or a host's fetch.prune) can delete them. + const remotes = path.join(server.project, ".git", "refs", "remotes", "mirror"); + yield* fs.makeDirectory(remotes, { recursive: true }); + yield* Effect.forEach( + Array.from({ length: 3_000 }, (_, index) => index), + (index) => fs.writeFileString(path.join(remotes, `bench-${index}`), head), + { concurrency: 64, discard: true }, + ); + // A reftable store (GIT_DEFAULT_REF_FORMAT can still pick one) ignores refs written as files. + const listed = yield* run( + "git", + ["for-each-ref", "--count=3000", "refs/remotes/mirror/"], + { + cwd: server.project, + }, + ); + if (listed.stdout.trim().split("\n").length < 3_000) { + return yield* new MetricsError({ message: "git does not see the soak's loose refs" }); } - // Round robin, so two soaks send the same turns to the same threads. - const threadId = threads[turn % threads.length]; - if (threadId === undefined) - return yield* new MetricsError({ message: "no soak threads" }); - const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); - if (sent.exitCode !== 0) { - return yield* new MetricsError({ - message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, - }); + const token = yield* server.issueToken; + // The client gets a scope of its own so each churn cycle can drop it and reconnect. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); + // Each client also polls pull requests the way the sidebar and an open PR do. + const connect = Effect.fn("serverMetrics.soakClient")(function* ( + threadIds: ReadonlyArray, + ) { + // A heap snapshot pauses the server for longer than the default 5 s ping timeout. + const client = yield* attachClient( + server, + token, + threadIds, + undefined, + Duration.minutes(2), + ); + yield* forge + .pollLikeWebClient({ + list: client.rpc["pullRequests.list"], + summary: client.rpc["pullRequests.summary"], + checks: client.rpc["pullRequests.checks"], + }) + .pipe(Effect.forkScoped); + return client; + }); + let scope = yield* clientScope; + let client = yield* connect(threads).pipe(Scope.provide(scope)); + yield* Effect.sleep(Duration.seconds(60)); + // The first snapshot inflates RSS once, so the slopes start after it. + const snapshots = [yield* server.snapshot]; + const samples: Array<{ + hours: number; + window: Window; + rssMB: number; + processes: number | null; + }> = []; + const start = yield* nowMs; + const elapsed = Effect.map(nowMs, (now) => now - start); + let snapshotRssMB = 0; + const takeSample = Effect.gen(function* () { + const hours = (yield* elapsed) / 3_600_000; + const window = yield* server.measure(5); + // Windows lists no descendants, which is not the same as having none. + const processes = + platform === "win32" + ? null + : yield* descendantsOf(server.pid).pipe( + Effect.map((found) => found.length), + // Unknown, not zero: a failed probe leaves the process slope out. + Effect.orElseSucceed(() => null), + ); + samples.push({ hours, window, rssMB: window.rssMB - snapshotRssMB, processes }); + yield* Console.error( + `soak ${round(hours * 60)} min: heap ${window.heapAfterGcMB} MB, RSS ${window.rssMB} MB${processes === null ? "" : `, ${processes} child processes`}`, + ); + }); + let nextSample = 0; + for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { + if (snapshots.length === 1 && (yield* elapsed) >= options.soakMinutes * 30_000) { + // RSS the snapshot itself added stays off the slope: later samples drop the step. + const before = (yield* sample(server.pid)).rss; + snapshots.push(yield* server.snapshot); + snapshotRssMB = Math.max(0, ((yield* sample(server.pid)).rss - before) / 1e6); + } + if ((yield* elapsed) >= nextSample) { + yield* takeSample; + nextSample += 120_000; + } + // Users come and go: a new thread replaces the oldest, which is archived and deleted, + // and the client reconnects, so state kept per thread or per connection must be freed. + if (turn > 0 && turn % SOAK_CHURN_TURNS === 0) { + yield* client.healthy; + const [fresh] = yield* openThreads(server, SOAK_THREADS + turn, 1); + const [oldest, ...rest] = threads; + if (fresh === undefined || oldest === undefined) + return yield* new MetricsError({ message: "no soak thread to churn" }); + threads = [...rest, fresh]; + const retiring = client; + yield* Scope.close(scope, Exit.void); + // A loss while the replacement thread started still counts against the run. + yield* retiring.healthy.pipe( + Effect.mapError( + (error) => new MetricsError({ message: `the retired client: ${error.message}` }), + ), + ); + scope = yield* clientScope; + client = yield* connect(threads).pipe(Scope.provide(scope)); + yield* forge.advanceRemote; + yield* client.retire("thread.archive", oldest, `bench-archive-${turn}`); + yield* client.retire("thread.delete", oldest, `bench-delete-${turn}`); + } + // Round robin, so two soaks send the same turns to the same threads. + const threadId = threads[turn % threads.length]; + if (threadId === undefined) + return yield* new MetricsError({ message: "no soak threads" }); + yield* fs.writeFileString(path.join(remotes, `soak-${turn}`), head); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } + yield* Effect.sleep( + Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed))), + ); } - yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); - } - yield* takeSample; - const perHour = (pick: (window: Window) => number) => - round(slope(samples.map(({ hours, window }) => [hours, pick(window)]))); - measured.soak = { - minutes: options.soakMinutes, - heapMBPerHour: perHour((window) => window.heapAfterGcMB), - rssMBPerHour: perHour((window) => window.rssMB), - }; - soakHeapGrowth = heapGrowth(before, yield* server.snapshot); - }), + yield* takeSample; + yield* client.healthy; + yield* forge.checkFetched(server.project); + const perHour = (pick: (sample: (typeof samples)[number]) => number) => + round(slope(samples.map((sample) => [sample.hours, pick(sample)]))); + measured.soak = { + minutes: options.soakMinutes, + heapMBPerHour: perHour(({ window }) => window.heapAfterGcMB), + rssMBPerHour: perHour(({ rssMB }) => rssMB), + ...(samples.some(({ processes }) => processes === null) + ? {} + : { childProcessesPerHour: perHour(({ processes }) => processes ?? 0) }), + }; + snapshots.push(yield* server.snapshot); + soakHeapGrowth = heapGrowth(snapshots[0]!.byConstructor, snapshots.at(-1)!.byConstructor); + soakRetainerGrowth = retainerGrowth(snapshots.map((snapshot) => snapshot.retainers)); + }), + { forge }, ); + yield* forge.verify; } measured.machine = yield* machine; - return { measured: measured as Measured, profiles, soakHeapGrowth }; + return { measured: measured as Measured, profiles, soakHeapGrowth, soakRetainerGrowth }; }, Effect.scoped); const machineLoad = Effect.gen(function* () { @@ -2277,7 +2424,7 @@ const runFlags = { soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( - "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", + "Minutes of soak: 10 threads under one web client, a short turn every 30 s in a project with 3,000 loose remote refs that gains one per turn. From minute 2, every 2 minutes a new thread replaces the oldest (archived, then deleted), the client reconnects and a fake GitHub remote gains a commit; the client polls that host's pull requests and checks. Reports heap, RSS and child-process slopes per hour, the constructors that grew, and the objects whose retained size grew at each of three snapshots with the path that holds them. Needs openssl on PATH and Node 24.5 or later. Runs alone unless --only names more.", ), Flag.withDefault(0), ), @@ -2381,6 +2528,7 @@ const runCommand = Command.make( runs, ...(last ? { profiles: last.profiles } : {}), ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + ...(last?.soakRetainerGrowth ? { soakRetainerGrowth: last.soakRetainerGrowth } : {}), }); }, Effect.scoped), ).pipe(