TypeScript
perf(server): git status runs in parallel and repo detection spawns 3x fewer git processes (#27103)
Julius Marminge7c29f2d20be6
diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.tsindex c7a06c3bdc3..88ca1eed8f5 100644--- a/apps/server/src/vcs/GitVcsDriver.test.ts+++ b/apps/server/src/vcs/GitVcsDriver.test.ts@@ -1006,6 +1006,24 @@ it.effect("GitVcsDriver treats a missing git executable as outside any repositor}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);+it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(+ "GitVcsDriver detects a repository whose path contains a newline",+ () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-newline-repo-" });+ const cwd = path.join(parent, "multi\nline");+ yield* fileSystem.makeDirectory(cwd);+ yield* runGit(cwd, ["init"]);+ const driver = yield* GitVcsDriver.makeVcsDriverShape();++ const repository = yield* driver.detectRepository(cwd);+ assert.strictEqual(repository?.rootPath, yield* fileSystem.realPath(cwd));+ assert.strictEqual(repository?.metadataPath, ".git");+ }).pipe(Effect.scoped, Effect.provide(layerGitContract)),+);+it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")("GitVcsDriver still fails detection when git exists but cannot be spawned",() =>diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.tsindex acbf817462c..95833200a1b 100644--- a/apps/server/src/vcs/GitVcsDriver.ts+++ b/apps/server/src/vcs/GitVcsDriver.ts@@ -587,25 +587,43 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (const detectRepository: VcsDriver.VcsDriver["Service"]["detectRepository"] = Effect.fn("detectRepository",)(function* (cwd) {- if (!(yield* isInsideWorkTree(cwd))) {- return null;- }-- const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [- "rev-parse",- "--show-toplevel",- ]);- const gitCommonDir = yield* gitCommand(+ // One spawn answers all three; outside a work tree it exits non-zero or prints "false".+ const result = yield* gitCommand(vcsProcess,- "GitVcsDriver.detectRepository.commonDir",+ "GitVcsDriver.detectRepository",cwd,- ["rev-parse", "--git-common-dir"],- ).pipe(Effect.orElseSucceed(() => null));+ ["rev-parse", "--is-inside-work-tree", "--show-toplevel", "--git-common-dir"],+ {+ allowNonZeroExit: true,+ timeoutMs: 5_000,+ maxOutputBytes: 16_384,+ },+ ).pipe(Effect.catchIf(isMissingExecutable, () => Effect.succeed(null)));+ if (result === null || result.exitCode !== 0) return null;+ const lines = result.stdout.replace(/\r?\n$/u, "").split(/\r?\n/u);+ if (lines[0]?.trim() !== "true") return null;+ // A newline inside a path breaks the line framing; ask for each path on its own.+ if (lines.length !== 3) {+ const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository", cwd, [+ "rev-parse",+ "--show-toplevel",+ ]);+ const gitCommonDir = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository", cwd, [+ "rev-parse",+ "--git-common-dir",+ ]).pipe(Effect.orElseSucceed(() => null));+ return {+ kind: "git" as const,+ rootPath: root.stdout.trim(),+ metadataPath: gitCommonDir?.stdout.trim() || null,+ freshness: yield* nowFreshness(),+ };+ }return {kind: "git" as const,- rootPath: root.stdout.trim(),- metadataPath: gitCommonDir?.stdout.trim() || null,+ rootPath: lines[1]!.trim(),+ metadataPath: lines[2]!.trim() || null,freshness: yield* nowFreshness(),};});diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex c486c6744cb..03f0286ce50 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -2091,7 +2091,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*return yield* lockError;}}- const statusResult = yield* executeGitWithStableDiagnostics(+ const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(+ Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),+ );+ const statusCacheKey = repositoryPaths?.gitCommonDir;+ const readStatus = executeGitWithStableDiagnostics("GitVcsDriver.statusDetails.status",cwd,statusArgs,@@ -2105,34 +2109,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),}),);-- if (statusResult === null) {- return NON_REPOSITORY_STATUS_DETAILS;- }-- if (statusResult.exitCode !== 0) {- if (isNonRepositoryGitStderr(statusResult.stderr)) {- return NON_REPOSITORY_STATUS_DETAILS;- }- return yield* new GitCommandError({- ...gitCommandContext({- operation: "GitVcsDriver.statusDetails.status",- cwd,- args: statusArgs,- }),- detail: "Git status failed.",- exitCode: statusResult.exitCode,- stdoutLength: statusResult.stdout.length,- stderrLength: statusResult.stderr.length,- });- }-- const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(- Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),- );- const statusCacheKey = repositoryPaths?.gitCommonDir;- const [numstatEntries, defaultBranch, hasPrimaryRemote] = yield* Effect.all(+ // diff-index does not read status output, so both spawn together; a non-repository discards it.+ const [statusResult, numstatResult, defaultBranch, hasPrimaryRemote] = yield* Effect.all([+ readStatus,// Porcelain diff rewrites indexes despite GIT_OPTIONAL_LOCKS=0; plumbing with -M preserves rename detection.executeGitWithStableDiagnostics("GitVcsDriver.statusDetails.numstat",@@ -2178,6 +2158,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*}),);}),+ Effect.result,),statusCacheKey? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null))@@ -2188,6 +2169,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*],{ concurrency: "unbounded" },);+ if (statusResult === null) {+ return NON_REPOSITORY_STATUS_DETAILS;+ }++ if (statusResult.exitCode !== 0) {+ if (isNonRepositoryGitStderr(statusResult.stderr)) {+ return NON_REPOSITORY_STATUS_DETAILS;+ }+ return yield* new GitCommandError({+ ...gitCommandContext({+ operation: "GitVcsDriver.statusDetails.status",+ cwd,+ args: statusArgs,+ }),+ detail: "Git status failed.",+ exitCode: statusResult.exitCode,+ stdoutLength: statusResult.stdout.length,+ stderrLength: statusResult.stderr.length,+ });+ }++ const numstatEntries = yield* Effect.fromResult(numstatResult);const statusStdout = statusResult.stdout;let refName: string | null = null;@@ -2231,25 +2234,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*}}- const fallbackAheadCount =- includeDivergence && !upstreamRef && refName- ? yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0))- : null;-- if (fallbackAheadCount !== null) {- aheadCount = fallbackAheadCount;- behindCount = 0;- }-const isDefaultBranch =refName !== null &&(refName === defaultBranch ||(defaultBranch === null && (refName === "main" || refName === "master")));- if (includeDivergence && refName && !isDefaultBranch) {- aheadOfDefaultCount =- fallbackAheadCount !== null- ? fallbackAheadCount- : yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0));+ const needsFallbackAhead = includeDivergence && !upstreamRef && refName !== null;+ const needsAheadOfDefault = includeDivergence && refName !== null && !isDefaultBranch;+ const [baseAheadCount, branchChanges] = yield* Effect.all(+ [+ refName !== null && (needsFallbackAhead || needsAheadOfDefault)+ ? computeAheadCountAgainstBase(cwd, refName, {+ knownOriginDefaultBranch: defaultBranch,+ }).pipe(Effect.orElseSucceed(() => 0))+ : Effect.succeed(0),+ options?.includeBranchChanges+ ? readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName, {+ knownOriginDefaultBranch: defaultBranch,+ }).pipe(Effect.orElseSucceed(() => undefined))+ : Effect.undefined,+ ],+ { concurrency: "unbounded" },+ );++ if (needsFallbackAhead) {+ aheadCount = baseAheadCount;+ behindCount = 0;+ }+ if (needsAheadOfDefault) {+ aheadOfDefaultCount = baseAheadCount;}const fileStatMap = new Map<string, { insertions: number; deletions: number }>();@@ -2276,12 +2288,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*}files.sort((a, b) => a.path.localeCompare(b.path));- const branchChanges = options?.includeBranchChanges- ? yield* readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName).pipe(- Effect.orElseSucceed(() => undefined),- )- : undefined;-return {isRepo: true,hasOriginRemote: hasPrimaryRemote,@@ -3014,6 +3020,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*cwd: string,branch: string | null,explicitBaseRef?: string,+ knownOriginDefaultBranch: string | null = null,) {const base =explicitBaseRef !== undefined@@ -3025,9 +3032,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*: explicitBaseRef,}): branch- ? yield* resolveBaseBranchForNoUpstream(cwd, branch, { allowRemoteOfCurrent: true }).pipe(- Effect.orElseSucceed(() => null),- )+ ? yield* resolveBaseBranchForNoUpstream(cwd, branch, {+ allowRemoteOfCurrent: true,+ knownOriginDefaultBranch,+ }).pipe(Effect.orElseSucceed(() => null)): null;if (base === null) return { baseRef: null, mergeBase: "HEAD" };const { baseRef, comparisonRef } = base;@@ -3058,8 +3066,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const readBranchChangeTotals = Effect.fn("readBranchChangeTotals")(function* (cwd: string,branch: string | null,+ options?: { readonly knownOriginDefaultBranch: string | null },) {- const { baseRef, mergeBase } = yield* resolveReviewMergeBase(cwd, branch);+ const { baseRef, mergeBase } = yield* resolveReviewMergeBase(+ cwd,+ branch,+ undefined,+ options?.knownOriginDefaultBranch ?? null,+ );const untracked = yield* prepareUntrackedReviewIndex(cwd, []);if (untracked === null) {return yield* new GitCommandError({diff --git a/apps/server/src/vcs/VcsDriverRegistry.test.ts b/apps/server/src/vcs/VcsDriverRegistry.test.tsindex e5c81697748..b6f7dae8137 100644--- a/apps/server/src/vcs/VcsDriverRegistry.test.ts+++ b/apps/server/src/vcs/VcsDriverRegistry.test.ts@@ -21,6 +21,8 @@ const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({const normalizeGitArgs = (args: ReadonlyArray<string>): ReadonlyArray<string> =>args[0] === "-C" && args.length >= 2 ? args.slice(2) : args;+const DETECT_COMMAND = "rev-parse --is-inside-work-tree --show-toplevel --git-common-dir";+describe("VcsDriverRegistry", () => {const makeDiskBackedLayer = (rootDir: string, calls: string[]) =>Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe(@@ -49,10 +51,10 @@ describe("VcsDriverRegistry", () => {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(`${path.relative(input.cwd, path.join(repoDir, ".git"))}\n`);+ if (command === DETECT_COMMAND) {+ return processOutput(+ `true\n${repoDir}\n${path.relative(input.cwd, path.join(repoDir, ".git"))}\n`,+ );}return processOutput("");}).pipe(Effect.provide(NodeServices.layer), Effect.orDie),@@ -75,7 +77,7 @@ describe("VcsDriverRegistry", () => {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);+ assert.equal(calls.filter((call) => call === DETECT_COMMAND).length, 2);}).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));}).pipe(Effect.provide(NodeServices.layer)),);@@ -118,7 +120,7 @@ describe("VcsDriverRegistry", () => {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);+ assert.equal(calls.filter((call) => call === DETECT_COMMAND).length, 2);}).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls)));}).pipe(Effect.provide(NodeServices.layer)),);diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.tsindex e2055e34005..00218397481 100644--- a/apps/server/src/vcs/VcsProcess.ts+++ b/apps/server/src/vcs/VcsProcess.ts@@ -83,8 +83,7 @@ const gitMetricOperations = new Set(["GitVcsDriver.checkpoints.resolveGitCommonDir","GitVcsDriver.checkpoints.resolveHeadCommit","GitVcsDriver.checkpoints.restoreCheckpoint",- "GitVcsDriver.detectRepository.commonDir",- "GitVcsDriver.detectRepository.root",+ "GitVcsDriver.detectRepository","GitVcsDriver.filterIgnoredPaths","GitVcsDriver.initRepository","GitVcsDriver.isInsideWorkTree",diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.tsindex cc1b6d24e38..042f8274543 100644--- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts+++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts@@ -76,6 +76,7 @@ function layerTestFor(state: {backgroundWorkEnabled?: boolean;automaticFetchInterval?: Effect.Effect<Duration.Duration>;beforeRemoteStatus?: Effect.Effect<void>;+ beforeLocalStatus?: Effect.Effect<void>;fileSystem?: FileSystem.FileSystem;pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"];}) {@@ -95,9 +96,11 @@ function layerTestFor(state: {Layer.provide(Layer.mock(GitWorkflowService.GitWorkflowService)({localStatus: () =>- Effect.sync(() => {+ Effect.suspend(() => {state.localStatusCalls += 1;- return state.currentLocalStatus;+ return (state.beforeLocalStatus ?? Effect.void).pipe(+ Effect.as(state.currentLocalStatus),+ );}),currentBranch: () => Effect.sync(() => state.currentLocalStatus.refName),remoteStatus: (_input, options) =>@@ -163,6 +166,47 @@ function layerBackgroundPolicy(shouldRunScopeWork: (scope: BackgroundScope) => b}describe("VcsStatusBroadcaster", () => {+ it.effect("refreshes queued behind a running one share the next git status read", () => {+ const state: Parameters<typeof layerTestFor>[0] = {+ currentLocalStatus: baseLocalStatus,+ currentRemoteStatus: baseRemoteStatus,+ localStatusCalls: 0,+ remoteStatusCalls: 0,+ localInvalidationCalls: 0,+ remoteInvalidationCalls: 0,+ fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),+ };++ return Effect.gen(function* () {+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;+ const started = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ state.beforeLocalStatus = Deferred.succeed(started, undefined).pipe(+ Effect.andThen(Deferred.await(release)),+ );+ const running = yield* broadcaster+ .refreshLocalStatus("/repo")+ .pipe(Effect.forkScoped({ startImmediately: true }));+ yield* Deferred.await(started);+ // Requested while the first read runs, so that read may predate their change.+ state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };+ const queued = yield* Effect.all(+ [broadcaster.refreshLocalStatus("/repo"), broadcaster.refreshLocalStatus("/repo")],+ { concurrency: "unbounded" },+ ).pipe(Effect.forkScoped({ startImmediately: true }));+ yield* Deferred.succeed(release, undefined);++ assert.isFalse((yield* Fiber.join(running)).hasWorkingTreeChanges);+ const [second, third] = yield* Fiber.join(queued);+ assert.isTrue(second.hasWorkingTreeChanges);+ assert.isTrue(third.hasWorkingTreeChanges);+ assert.strictEqual(state.localStatusCalls, 2);++ yield* broadcaster.refreshLocalStatus("/repo");+ assert.strictEqual(state.localStatusCalls, 3);+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);+ });+it.effect("publishes a terminal branch switch without reading remote status", () => {const state = {currentLocalStatus: baseLocalStatus,diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.tsindex 8ce1b225d12..a8839d0c1cd 100644--- a/apps/server/src/vcs/VcsStatusBroadcaster.ts+++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts@@ -359,11 +359,30 @@ export const make = Effect.gen(function* () {);});+ // A refresh that started after a request saw every change that request could mean, so queued+ // callers share it instead of each running git status again.+ const localRefreshLocks = yield* KeyedLock.make<string>();+ const localRefreshRequests = new Map<string, number>();+ const localRefreshResults = new Map<+ string,+ { readonly startedAt: number; readonly local: VcsStatusLocalResult }+ >();const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(function* (cwd: string) {- yield* workflow.invalidateLocalStatus(cwd);- const local = yield* workflow.localStatus({ cwd });- return yield* updateCachedLocalStatus(cwd, local, { publish: true });+ const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;+ localRefreshRequests.set(cwd, requestedAt);+ return yield* localRefreshLocks.withLock(+ cwd,+ Effect.gen(function* () {+ const shared = localRefreshResults.get(cwd);+ if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local;+ const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;+ yield* workflow.invalidateLocalStatus(cwd);+ const local = yield* workflow.localStatus({ cwd });+ localRefreshResults.set(cwd, { startedAt, local });+ return yield* updateCachedLocalStatus(cwd, local, { publish: true });+ }),+ );},);