TypeScript
perf(server): idle status polls and PR sweeps start fewer git processes (#16272)
Theo Brownedcbaf0527998
diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.tsindex a4674ad7d57..730f1bd0a35 100644--- a/apps/server/src/git/GitManager.test.ts+++ b/apps/server/src/git/GitManager.test.ts@@ -1071,6 +1071,49 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {}),);+ it.effect("a branch tracking origin reads origin's URL once per PR lookup", () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["checkout", "-b", "feature/origin-once"]);+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/origin-once"]);++ const gitConfigReads: string[] = [];+ const { manager } = yield* makeManager({+ gitConfigReads,+ ghScenario: {+ prListSequence: [+ // Fake gh returns raw JSON stdout, matching the CLI boundary under test.+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify([+ {+ number: 217,+ title: "Origin once PR",+ url: "https://github.com/pingdotgg/t3code/pull/217",+ baseRefName: "main",+ headRefName: "feature/origin-once",+ state: "OPEN",+ updatedAt: "2026-04-03T15:00:00Z",+ },+ ]),+ ],+ },+ });++ yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature/origin-once" });+ gitConfigReads.length = 0;+ const pullRequest = yield* manager.branchPullRequest({+ cwd: repoDir,+ branch: "feature/origin-once",+ });++ expect(pullRequest?.number).toBe(217);+ expect(gitConfigReads.filter((key) => key === "remote.origin.url")).toHaveLength(1);+ }),+ );+it.effect("turn-end refresh finds a new PR and keeps known PRs cached", () =>Effect.gen(function* () {const repoDir = yield* makeTempDir("t3code-git-manager-");diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.tsindex 3d5cdb5b8b2..cb22f9a9b4c 100644--- a/apps/server/src/git/GitManager.ts+++ b/apps/server/src/git/GitManager.ts@@ -1404,17 +1404,25 @@ export const make = Effect.gen(function* () {};});+ // Returns [head remote, origin]. Most branches track origin, so read it once.+ const resolveHeadAndOriginContexts = (cwd: string, remoteName: string | null) =>+ remoteName === "origin"+ ? resolveRemoteRepositoryContext(cwd, "origin").pipe(+ Effect.map((origin) => [origin, origin] as const),+ )+ : Effect.all(+ [+ resolveRemoteRepositoryContext(cwd, remoteName),+ resolveRemoteRepositoryContext(cwd, "origin"),+ ],+ { concurrency: "unbounded" },+ );+const resolvePrLookupRepositoryIdentity = Effect.fn("resolvePrLookupRepositoryIdentity")(function* (cwd: string, branch: string, remoteNameOverride?: string) {const remoteName =remoteNameOverride ?? (yield* readConfigValueNullable(cwd, `branch.${branch}.remote`));- const [headRemote, targetRemote] = yield* Effect.all(- [- resolveRemoteRepositoryContext(cwd, remoteName),- resolveRemoteRepositoryContext(cwd, "origin"),- ],- { concurrency: "unbounded" },- );+ const [headRemote, targetRemote] = yield* resolveHeadAndOriginContexts(cwd, remoteName);return {remoteName,headRemoteUrlKey:@@ -1438,12 +1446,9 @@ export const make = Effect.gen(function* () {const shouldProbeLocalBranchSelector =headBranchFromUpstream.length === 0 || headBranch === details.branch;- const [remoteRepository, originRepository] = yield* Effect.all(- [- resolveRemoteRepositoryContext(cwd, remoteName),- resolveRemoteRepositoryContext(cwd, "origin"),- ],- { concurrency: "unbounded" },+ const [remoteRepository, originRepository] = yield* resolveHeadAndOriginContexts(+ cwd,+ remoteName,);const isCrossRepository =diff --git a/apps/server/src/vcs/VcsDriverRegistry.test.ts b/apps/server/src/vcs/VcsDriverRegistry.test.tsindex f88b33e8456..d302ef106ac 100644--- a/apps/server/src/vcs/VcsDriverRegistry.test.ts+++ b/apps/server/src/vcs/VcsDriverRegistry.test.ts@@ -1,7 +1,9 @@import { assert, it, describe } from "@effect/vitest";import * as NodeServices from "@effect/platform-node/NodeServices";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 { ChildProcessSpawner } from "effect/process";import * as VcsProcess from "./VcsProcess.ts";@@ -43,9 +45,10 @@ describe("VcsDriverRegistry", () => {}).pipe(Effect.provide(layer));});- it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {- const calls: VcsProcess.VcsProcessInput[] = [];- const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(+ // Answers detection like git: the nearest folder at or above the cwd, up to+ // `rootDir`, that holds `.git` is the repository.+ const makeDiskBackedLayer = (rootDir: string, calls: string[]) =>+ Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(Layer.provide(NodeServices.layer),Layer.provide(Layer.mock(VcsProjectConfig.VcsProjectConfig)({@@ -55,86 +58,139 @@ describe("VcsDriverRegistry", () => {Layer.provide(Layer.mock(VcsProcess.VcsProcess)({run: (input) =>- Effect.sync(() => {- calls.push(input);- const normalizedArgs =- input.args[0] === "-C" && input.args.length >= 2 ? input.args.slice(2) : input.args;- const command = normalizedArgs.join(" ");- if (command === "rev-parse --is-inside-work-tree") {- return processOutput("true\n");+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const command = normalizeGitArgs(input.args).join(" ");+ calls.push(command);+ let repoDir: string | null = input.cwd;+ while (repoDir !== null && !(yield* fs.exists(path.join(repoDir, ".git")))) {+ repoDir = repoDir === rootDir ? null : path.dirname(repoDir);}- if (command === "rev-parse --show-toplevel") {- return processOutput("/repo\n");+ if (repoDir === null) {+ return {+ ...processOutput(""),+ exitCode: ChildProcessSpawner.ExitCode(128),+ stderr: "fatal: not a git repository",+ };}+ if (command === "rev-parse --is-inside-work-tree") return processOutput("true\n");+ if (command === "rev-parse --show-toplevel") return processOutput(`${repoDir}\n`);if (command === "rev-parse --git-common-dir") {- return processOutput("/repo/.git\n");+ return processOutput(`${path.relative(input.cwd, path.join(repoDir, ".git"))}\n`);}return processOutput("");- }),+ }).pipe(Effect.provide(NodeServices.layer), Effect.orDie),}),),);- return Effect.gen(function* () {- const registry = yield* VcsDriverRegistry.VcsDriverRegistry;- const first = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });- const second = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });-- assert.equal(first.repository.rootPath, "/repo");- assert.equal(second.repository.rootPath, "/repo");- assert.deepStrictEqual(- calls.map((call) => normalizeGitArgs(call.args).join(" ")),- [+ it.effect("caches repository detection for repeated resolves in the same cwd and kind", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });+ yield* fs.makeDirectory(path.join(repoDir, ".git"));+ const calls: string[] = [];++ yield* Effect.gen(function* () {+ const registry = yield* VcsDriverRegistry.VcsDriverRegistry;+ const first = yield* registry.resolve({ cwd: repoDir, requestedKind: "git" });+ const second = yield* registry.resolve({ cwd: repoDir, requestedKind: "git" });++ assert.equal(first.repository.rootPath, repoDir);+ assert.equal(second.repository.rootPath, repoDir);+ assert.deepStrictEqual(calls, ["rev-parse --is-inside-work-tree","rev-parse --show-toplevel","rev-parse --git-common-dir",- ],- );- }).pipe(Effect.provide(layer));- });+ ]);+ }).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));+ }).pipe(Effect.provide(NodeServices.layer)),+ );- it.effect("detects a repository created after a negative lookup", () => {- let insideWorkTreeChecks = 0;- const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(- Layer.provide(NodeServices.layer),- Layer.provide(- Layer.mock(VcsProjectConfig.VcsProjectConfig)({- resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),- }),- ),- Layer.provide(- Layer.mock(VcsProcess.VcsProcess)({- run: (input) =>- Effect.sync(() => {- const command = normalizeGitArgs(input.args).join(" ");- if (command === "rev-parse --is-inside-work-tree") {- insideWorkTreeChecks += 1;- return insideWorkTreeChecks === 1- ? {- ...processOutput(""),- exitCode: ChildProcessSpawner.ExitCode(128),- stderr: "fatal: not a git repository",- }- : processOutput("true\n");- }- if (command === "rev-parse --show-toplevel") {- return processOutput("/repo\n");- }- if (command === "rev-parse --git-common-dir") {- return processOutput("/repo/.git\n");- }- return processOutput("");- }),- }),- ),- );+ it.effect("detects again when a cached repository is removed from disk", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });+ yield* fs.makeDirectory(path.join(repoDir, ".git"));+ const calls: string[] = [];- return Effect.gen(function* () {- const registry = yield* VcsDriverRegistry.VcsDriverRegistry;+ yield* Effect.gen(function* () {+ const registry = yield* VcsDriverRegistry.VcsDriverRegistry;+ assert.equal((yield* registry.detect({ cwd: repoDir }))?.repository.rootPath, repoDir);- assert.equal(yield* registry.detect({ cwd: "/repo" }), null);- assert.equal((yield* registry.detect({ cwd: "/repo" }))?.repository.rootPath, "/repo");- assert.equal(insideWorkTreeChecks, 2);- }).pipe(Effect.provide(layer));- });+ yield* fs.remove(path.join(repoDir, ".git"), { recursive: true });++ assert.equal(yield* registry.detect({ cwd: repoDir }), null);+ assert.equal(calls.filter((call) => call === "rev-parse --is-inside-work-tree").length, 2);+ }).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("detects again when git init creates a repository inside a cached one", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });+ const projectDir = path.join(parentDir, "project");+ yield* fs.makeDirectory(path.join(parentDir, ".git"));+ yield* fs.makeDirectory(projectDir);+ const calls: string[] = [];++ yield* Effect.gen(function* () {+ const registry = yield* VcsDriverRegistry.VcsDriverRegistry;+ assert.equal((yield* registry.detect({ cwd: projectDir }))?.repository.rootPath, parentDir);++ yield* fs.makeDirectory(path.join(projectDir, ".git"));++ assert.equal(+ (yield* registry.detect({ cwd: projectDir }))?.repository.rootPath,+ projectDir,+ );+ }).pipe(Effect.provide(makeDiskBackedLayer(parentDir, calls)));+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("detects again when git init creates a repository between the cwd and its root", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });+ const middleDir = path.join(parentDir, "a");+ const cwd = path.join(middleDir, "b");+ yield* fs.makeDirectory(path.join(parentDir, ".git"));+ yield* fs.makeDirectory(cwd, { recursive: true });+ const calls: string[] = [];++ yield* Effect.gen(function* () {+ const registry = yield* VcsDriverRegistry.VcsDriverRegistry;+ assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, parentDir);++ yield* fs.makeDirectory(path.join(middleDir, ".git"));++ assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, middleDir);+ }).pipe(Effect.provide(makeDiskBackedLayer(parentDir, calls)));+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("detects a repository created after a negative lookup", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" });+ const calls: string[] = [];++ yield* Effect.gen(function* () {+ const registry = yield* VcsDriverRegistry.VcsDriverRegistry;+ assert.equal(yield* registry.detect({ cwd: repoDir }), null);++ yield* fs.makeDirectory(path.join(repoDir, ".git"));++ assert.equal((yield* registry.detect({ cwd: repoDir }))?.repository.rootPath, repoDir);+ assert.equal(calls.filter((call) => call === "rev-parse --is-inside-work-tree").length, 2);+ }).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));+ }).pipe(Effect.provide(NodeServices.layer)),+ );});diff --git a/apps/server/src/vcs/VcsDriverRegistry.ts b/apps/server/src/vcs/VcsDriverRegistry.tsindex f40e1dadea3..35275d819a2 100644--- a/apps/server/src/vcs/VcsDriverRegistry.ts+++ b/apps/server/src/vcs/VcsDriverRegistry.ts@@ -3,7 +3,9 @@ import * as Context from "effect/Context";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";+import * as Path from "effect/Path";import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";import { VcsUnsupportedOperationError } from "@t3tools/contracts";@@ -12,7 +14,10 @@ import * as VcsProjectConfig from "./VcsProjectConfig.ts";import * as VcsDriver from "./VcsDriver.ts";const DETECTION_CACHE_CAPACITY = 2_048;-const DETECTION_CACHE_TTL = Duration.seconds(2);+// Status polls detect every open cwd each tick, and detection costs three git+// processes. `detect` re-checks each hit against the disk, so this TTL only+// bounds rare changes those stats cannot see.+const DETECTION_CACHE_TTL = Duration.minutes(5);export interface VcsDriverResolveInput {readonly cwd: string;@@ -61,6 +66,8 @@ function parseDetectionCacheKey(key: string): {}export const make = Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;const git = yield* GitVcsDriver.makeVcsDriver;const drivers: Partial<Record<VcsDriverKind, VcsDriver.VcsDriver["Service"]>> = {@@ -111,8 +118,44 @@ export const make = Effect.gen(function* () {return yield* detectWithDriver("git", git, input.cwd);});- const detectionCache = yield* Cache.makeWith<string, VcsDriverHandle | null, VcsError>(- (key) => detectResolvedKind(parseDetectionCacheKey(key)),+ // The cwd and each parent below the repository root. A new `.git` in any of+ // them means `git init` made a nested repository. Falls back to the cwd alone+ // when the root is not above it, such as a cwd reached through a symlink.+ const foldersBelowRoot = (cwd: string, rootPath: string) => {+ const relative = path.relative(path.resolve(rootPath), path.resolve(cwd));+ if (relative.startsWith("..") || path.isAbsolute(relative)) return [cwd];+ return Array.from({ length: relative.split(path.sep).length }, (_, levelsUp) =>+ path.resolve(cwd, ...Array<string>(levelsUp).fill("..")),+ );+ };++ // What `detect` re-checks on every cache hit, using stats instead of git.+ const readDiskState = (cwd: string, repository: VcsRepositoryIdentity) =>+ Effect.all({+ gitEntries: Effect.forEach(foldersBelowRoot(cwd, repository.rootPath), (folder) =>+ fileSystem.exists(path.join(folder, ".git")),+ ),+ repositoryOnDisk: Effect.forEach(+ repository.metadataPath === null+ ? [cwd]+ : [cwd, path.resolve(cwd, repository.metadataPath)],+ (target) => fileSystem.exists(target),+ ).pipe(Effect.map((results) => results.every(Boolean))),+ }).pipe(Effect.orElseSucceed(() => null));++ const detectionCache = yield* Cache.makeWith<+ string,+ { readonly handle: VcsDriverHandle; readonly gitEntries: ReadonlyArray<boolean> } | null,+ VcsError+ >(+ (key) =>+ Effect.gen(function* () {+ const input = parseDetectionCacheKey(key);+ const handle = yield* detectResolvedKind(input);+ if (handle === null) return null;+ const disk = yield* readDiskState(input.cwd, handle.repository);+ return { handle, gitEntries: disk?.gitEntries ?? [] };+ }),{capacity: DETECTION_CACHE_CAPACITY,timeToLive: Exit.match({@@ -122,10 +165,24 @@ export const make = Effect.gen(function* () {},);+ // A hit is stale when its worktree or `.git` folder was removed, or when+ // `git init` created a nested repository between the cwd and its root.const detect: VcsDriverRegistry["Service"]["detect"] = Effect.fn("VcsDriverRegistry.detect")(function* (input) {const requestedKind = yield* projectConfig.resolveKind(input);- return yield* Cache.get(detectionCache, detectionCacheKey({ cwd: input.cwd, requestedKind }));+ const key = detectionCacheKey({ cwd: input.cwd, requestedKind });+ const cached = yield* Cache.get(detectionCache, key);+ if (cached === null) return null;+ const disk = yield* readDiskState(input.cwd, cached.handle.repository);+ if (+ disk?.repositoryOnDisk &&+ disk.gitEntries.length === cached.gitEntries.length &&+ disk.gitEntries.every((exists, index) => exists === cached.gitEntries[index])+ ) {+ return cached.handle;+ }+ yield* Cache.invalidate(detectionCache, key);+ return (yield* Cache.get(detectionCache, key))?.handle ?? null;},);