diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 16ed527bb878b..f285a6c2b6ba0 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1014,6 +1014,203 @@ it.effect("resolves a branch's base once while its refs and branch config are un ).pipe(Effect.provide(layerTest)), ); +it.effect("keeps a branch's base cached while only other refs' commits move", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "origin", cwd]); + yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]); + yield* git(cwd, ["update-ref", "refs/remotes/origin/develop", "HEAD"]); + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/origin/HEAD", + `refs/remotes/origin/${initialBranch}`, + ]); + const other = `${yield* makeTmpDir()}/other`; + yield* git(cwd, ["worktree", "add", "-b", "other", other]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + yield* git(cwd, ["pack-refs", "--all"]); + const lookups = () => { + const count = spawnedArgs.filter((args) => + args.includes("branch.feature/x.t3-merge-base-ref"), + ).length; + spawnedArgs.length = 0; + return count; + }; + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + + // Another worktree's commits and a fetch moving a packed base ref add or remove no name. + yield* git(other, ["commit", "--allow-empty", "-m", "other"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(spawnedArgs.length, 6); + assert.equal(lookups(), 0); + yield* git(other, ["commit", "--allow-empty", "-m", "other again"]); + yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "other"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + + yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/develop"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* git(cwd, ["branch", "master"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + // Deleting a packed ref rewrites packed-refs without touching a loose file. + yield* git(cwd, ["update-ref", "-d", "refs/remotes/origin/develop"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* git(cwd, ["config", "branch.feature/x.t3-merge-base", "other"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("rereads the base after a nested remote's HEAD is retargeted", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "team/origin", cwd]); + yield* git(cwd, ["update-ref", `refs/remotes/team/origin/${initialBranch}`, "HEAD"]); + yield* git(cwd, ["update-ref", "refs/remotes/team/origin/develop", "HEAD"]); + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/team/origin/HEAD", + `refs/remotes/team/origin/${initialBranch}`, + ]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + const lookups = () => { + const count = spawnedArgs.filter((args) => + args.includes("branch.feature/x.t3-merge-base-ref"), + ).length; + spawnedArgs.length = 0; + return count; + }; + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/team/origin/HEAD", + "refs/remotes/team/origin/develop", + ]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("keeps the base cached when a remote branch has a HEAD path component", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "origin", cwd]); + yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]); + // A valid ref whose path has a directory named HEAD under refs/remotes. + yield* git(cwd, ["update-ref", "refs/remotes/origin/topic/HEAD/child", "HEAD"]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + const lookups = () => { + const count = spawnedArgs.filter((args) => + args.includes("branch.feature/x.t3-merge-base-ref"), + ).length; + spawnedArgs.length = 0; + return count; + }; + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("keeps one cached base per branch however often its refs change", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let lookupCount = 0; + const spawner = ChildProcessSpawner.make((command) => { + if ( + ChildProcess.isStandardCommand(command) && + command.args.map(String).includes("branch.feature/x.t3-merge-base-ref") + ) { + lookupCount++; + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const other = `${yield* makeTmpDir()}/other`; + yield* git(cwd, ["worktree", "add", "-b", "other", other]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "feature 1"]); + yield* git(cwd, ["branch", "develop"]); + const read = Effect.fnUntraced(function* () { + lookupCount = 0; + const status = yield* driver.statusDetailsLocal(cwd); + return { lookups: lookupCount, aheadCount: status.aheadCount }; + }); + const useBase = (base: string) => + git(cwd, ["config", "branch.feature/x.t3-merge-base", base]); + + yield* useBase(initialBranch); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: 1 }); + for (let round = 1; round <= 4; round++) { + // Commits here and in another worktree keep every ref name, so the base stays cached. + yield* git(cwd, ["commit", "--allow-empty", "-m", `feature ${round + 1}`]); + yield* git(other, ["commit", "--allow-empty", "-m", `other ${round}`]); + assert.deepStrictEqual(yield* read(), { lookups: 0, aheadCount: round + 1 }); + + yield* useBase("develop"); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round }); + // Returning to an earlier stamp resolves again: the entry under it was overwritten, not kept. + yield* useBase(initialBranch); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round + 1 }); + yield* git(cwd, ["branch", `scratch-${round}`]); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round + 1 }); + yield* git(cwd, ["branch", "-D", `scratch-${round}`]); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round + 1 }); + } + }), + ).pipe(Effect.provide(layerTest)), +); + it.effect.each([ { kind: "working-tree", request: { sourceKind: "working-tree" } }, { kind: "commit", request: { sourceKind: "commit", commitSha: "HEAD" } }, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 5d0df31809b4b..9d204f821f00c 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -193,7 +193,6 @@ class BaseBranchCacheKey extends Data.Class<{ cwd: string; refName: string; allowRemoteOfCurrent: boolean; - inputsStamp: string; }> {} class GitRefsSnapshotCacheKey extends Data.Class<{ @@ -2477,10 +2476,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return null; }); - // The effective config listing covers included, global, system and worktree config. Git writes - // packed-refs and each loose ref by rename, so their stats change whenever a ref could. Directory - // stats are left out: Git for Windows' no-op fetch touches refs/remotes/. - // Cost: one git process, a listing per refs directory and a stat per loose ref. + // Base selection reads config, which refs exist and each remote's HEAD target, never where a ref + // points, so commits and fetches keep the stamp. packed-refs names are re-read only when the file + // changes (repack, packed delete); a loose ref shadowing a packed one adds no name. Reftable keeps + // no names in files, so its table list's stat stands in for them. + const packedRefNames = new Map< + string, + { readonly token: string; readonly hash: string; readonly names: ReadonlySet } + >(); + const sha256Hex = (text: string) => + Effect.map(digest.digest(Digest.sha256, new TextEncoder().encode(text)), Hex.encode); const readBaseBranchInputsStamp = Effect.fn("GitVcsDriverCore.readBaseBranchInputsStamp")( function* (cwd: string, gitCommonDir: string) { const effectiveConfig = yield* executeGit( @@ -2490,9 +2495,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (effectiveConfig.exitCode !== 0 || effectiveConfig.stdoutTruncated) return null; - const configHash = Hex.encode( - yield* digest.digest(Digest.sha256, new TextEncoder().encode(effectiveConfig.stdout)), - ); const statToken = (target: string) => fileSystem.stat(target).pipe( Effect.map( @@ -2504,16 +2506,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed("-")), ); - const tokens = yield* Effect.forEach( - ["packed-refs", "reftable/tables.list"], - (name) => statToken(path.join(gitCommonDir, name)), + const packedRefsPath = path.join(gitCommonDir, "packed-refs"); + const [packedToken, reftableToken] = yield* Effect.all( + [statToken(packedRefsPath), statToken(path.join(gitCommonDir, "reftable", "tables.list"))], { concurrency: "unbounded" }, ); - const directories = [ - path.join(gitCommonDir, "refs", "heads"), - path.join(gitCommonDir, "refs", "remotes"), - ]; - const looseRefs: Array = []; + let packed = packedRefNames.get(gitCommonDir); + if (packed?.token !== packedToken) { + const contents = + packedToken === "-" + ? "" + : yield* fileSystem + .readFileString(packedRefsPath) + .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(""))); + const names = contents + .split("\n") + .map((line) => line.slice(line.indexOf(" ") + 1)) + .filter((name) => name.startsWith("refs/heads/") || name.startsWith("refs/remotes/")); + packed = { + token: packedToken, + hash: yield* sha256Hex(names.join("\0")), + names: new Set(names), + }; + packedRefNames.set(gitCommonDir, packed); + } + const remotesDirectory = path.join(gitCommonDir, "refs", "remotes"); + const directories = [path.join(gitCommonDir, "refs", "heads"), remotesDirectory]; + const looseNames: Array = []; + const remoteHeads: Array = []; for (let index = 0; index < directories.length; index++) { const directory = directories[index]!; const entries = yield* fileSystem @@ -2521,23 +2541,53 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed([]))); for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) { const entryPath = path.join(directory, entry.name); - if (entry.type === "Directory") directories.push(entryPath); - else looseRefs.push(entryPath); + if (entry.type === "Directory") { + directories.push(entryPath); + continue; + } + const name = path.relative(gitCommonDir, entryPath).split(path.sep).join("/"); + if (!packed.names.has(name)) looseNames.push(name); + // A remote name may contain "/", so its HEAD can sit deeper than refs/remotes/. + if (entry.name === "HEAD" && directory.startsWith(remotesDirectory + path.sep)) { + remoteHeads.push(entryPath); + } } } - tokens.push( - ...(yield* Effect.forEach( - looseRefs, - (ref) => Effect.map(statToken(ref), (token) => `${ref}=${token}`), - { concurrency: 16 }, - )), + const remoteHeadTargets = yield* Effect.forEach( + remoteHeads, + (head) => + fileSystem.readFileString(head).pipe( + Effect.map((target) => `${head}=${target}`), + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(`${head}=-`)), + ), + { concurrency: "unbounded" }, + ); + // Hashed: names alone reach ~1 MB in busy repositories, and keys behind a stale stamp + // linger in the cache until its capacity evicts them. + return yield* sha256Hex( + [ + effectiveConfig.stdout, + packed.hash, + reftableToken, + ...looseNames, + ...remoteHeadTargets, + ].join("\0"), ); - tokens.push(configHash); - return tokens.join("\0"); }, ); + const readCurrentBaseBranchInputsStamp = Effect.fnUntraced(function* (cwd: string) { + const gitCommonDir = (yield* resolveRepositoryPaths(cwd).pipe(Effect.orElseSucceed(() => null))) + ?.gitCommonDir; + if (gitCommonDir === undefined) return null; + return yield* readBaseBranchInputsStamp(cwd, gitCommonDir).pipe( + Effect.orElseSucceed(() => null), + ); + }); + // The stamp lives in the value, not the key: a key per stamp would leave every superseded + // stamp's entry behind until capacity evicts it, since TTL only expires a key that is read again. const baseBranchCache = yield* Cache.makeWith( Effect.fnUntraced(function* (key: BaseBranchCacheKey) { + const inputsStamp = yield* readCurrentBaseBranchInputsStamp(key.cwd); const trace = { dependsOnRemoteOfCurrent: false, degraded: false }; const base = yield* findBaseBranchForNoUpstream( key.cwd, @@ -2545,7 +2595,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowRemoteOfCurrent: key.allowRemoteOfCurrent }, trace, ); - return { base, ...trace }; + return { base, inputsStamp, ...trace }; }), { capacity: 2_048, @@ -2561,28 +2611,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* refName: string, options?: { readonly allowRemoteOfCurrent?: boolean }, ) { - const gitCommonDir = (yield* resolveRepositoryPaths(cwd).pipe( - Effect.orElseSucceed(() => null), - ))?.gitCommonDir; - const inputsStamp = - gitCommonDir === undefined - ? null - : yield* readBaseBranchInputsStamp(cwd, gitCommonDir).pipe( - Effect.orElseSucceed(() => null), - ); - if (inputsStamp === null) { - return yield* findBaseBranchForNoUpstream(cwd, refName, options); - } - const key = { - cwd: normalizeRepositoryPathsCacheKey(cwd), - refName, - inputsStamp, - }; + const key = { cwd: normalizeRepositoryPathsCacheKey(cwd), refName }; const allowRemoteOfCurrent = options?.allowRemoteOfCurrent === true; const cacheKey = new BaseBranchCacheKey({ ...key, allowRemoteOfCurrent }); + const cached = yield* Cache.getOption(baseBranchCache, cacheKey); + if (Option.isSome(cached)) { + const inputsStamp = yield* readCurrentBaseBranchInputsStamp(cwd); + if (inputsStamp !== null && inputsStamp === cached.value.inputsStamp) { + return cached.value.base; + } + yield* Cache.invalidate(baseBranchCache, cacheKey); + } const entry = yield* Cache.get(baseBranchCache, cacheKey); // A fallback forced by a failed remote lookup must not outlive the failure. - if (entry.degraded) { + if (entry.degraded || entry.inputsStamp === null) { yield* Cache.invalidate(baseBranchCache, cacheKey); } else if (!entry.dependsOnRemoteOfCurrent) { yield* Cache.set(