@devries-cameron20 / t3code-1 / commits / 6e2747921c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(server): git status refresh reads local status once unless refs moved (#29155)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Andrei committed Nov 15, 2026 at 02:29 UTC 6e2747921c54134fbd1f6ac6a7f27003d7ab3c8c
6 files changed +205 -5
apps/server/src/git/GitWorkflowService.ts
+2
@@ -67,6 +67,7 @@ export class GitWorkflowService extends Context.Service<
67 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
68 readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
69 readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
70 + readonly readRefSnapshot: (cwd: string) => Effect.Effect<string | null>;
71 readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
72 /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */
73 readonly headPath: (cwd: string) => Effect.Effect<string | null, never>;
@@ -390,6 +391,7 @@ export const make = Effect.gen(function* () {
391 }),
392 invalidateLocalStatus: gitManager.invalidateLocalStatus,
393 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
394 + readRefSnapshot: git.readRefSnapshot,
395 invalidateStatus: gitManager.invalidateStatus,
396 headPath: Effect.fn("GitWorkflowService.headPath")(function (cwd) {
397 return git
apps/server/src/vcs/GitVcsDriver.ts
+2
@@ -337,6 +337,8 @@ export class GitVcsDriver extends Context.Service<
337 cwd: string,
338 options?: GitRemoteStatusOptions,
339 ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
340 + /** Refs, HEAD and shallow boundaries. Null when the snapshot cannot be read. */
341 + readonly readRefSnapshot: (cwd: string) => Effect.Effect<string | null>;
342 readonly prepareCommitContext: (
343 cwd: string,
344 filePaths?: readonly string[],
apps/server/src/vcs/GitVcsDriverCore.test.ts
+94
@@ -5040,6 +5040,100 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
5040 }),
5041 );
5042
5043 + it.effect("a ref snapshot detects branch identity, ref and ancestry changes", () =>
5044 + Effect.gen(function* () {
5045 + const cwd = yield* makeTmpDir();
5046 + const remote = yield* makeTmpDir("git-vcs-driver-remote-");
5047 + const updater = yield* makeTmpDir("git-vcs-driver-updater-");
5048 + const { initialBranch } = yield* initRepoWithCommit(cwd);
5049 + yield* git(remote, ["init", "--bare"]);
5050 + yield* git(cwd, ["remote", "add", "origin", remote]);
5051 + yield* git(cwd, ["push", "-u", "origin", initialBranch]);
5052 + yield* git(updater, ["clone", remote, "."]);
5053 + yield* git(updater, ["config", "user.email", "test@test.com"]);
5054 + yield* git(updater, ["config", "user.name", "Test"]);
5055 + const driver = yield* GitVcsDriver.GitVcsDriver;
5056 + const snapshot = driver.readRefSnapshot(cwd);
5057 +
5058 + // Newer Git can create origin/HEAD on the first fetch.
5059 + yield* git(cwd, ["fetch", "origin"]);
5060 + const initial = yield* snapshot;
5061 + assert.isNotNull(initial);
5062 + yield* git(cwd, ["fetch", "origin"]);
5063 + assert.equal(yield* snapshot, initial);
5064 +
5065 + yield* git(cwd, ["branch", "same-commit"]);
5066 + const beforeCheckout = yield* snapshot;
5067 + const refsBeforeCheckout = yield* git(cwd, ["show-ref", "--head"]);
5068 + yield* git(cwd, ["checkout", "same-commit"]);
5069 + assert.equal(yield* git(cwd, ["show-ref", "--head"]), refsBeforeCheckout);
5070 + const afterCheckout = yield* snapshot;
5071 + assert.isNotNull(afterCheckout);
5072 + assert.notEqual(afterCheckout, beforeCheckout);
5073 + yield* git(cwd, ["checkout", "--detach"]);
5074 + assert.equal(yield* git(cwd, ["show-ref", "--head"]), refsBeforeCheckout);
5075 + const detached = yield* snapshot;
5076 + assert.isNotNull(detached);
5077 + assert.notEqual(detached, beforeCheckout);
5078 + assert.notEqual(detached, afterCheckout);
5079 + assert.equal(yield* snapshot, detached);
5080 + yield* git(cwd, ["checkout", initialBranch]);
5081 + assert.equal(yield* snapshot, beforeCheckout);
5082 + yield* git(cwd, ["branch", "-d", "same-commit"]);
5083 +
5084 + yield* writeTextFile(updater, "remote.txt", "remote\n");
5085 + yield* git(updater, ["add", "remote.txt"]);
5086 + yield* git(updater, ["commit", "-m", "remote commit"]);
5087 + yield* git(updater, ["push", "origin", initialBranch]);
5088 + assert.equal(yield* snapshot, initial);
5089 + yield* git(cwd, ["fetch", "origin"]);
5090 + const fetched = yield* snapshot;
5091 + assert.notEqual(fetched, initial);
5092 +
5093 + const shallow = yield* makeTmpDir("git-vcs-driver-shallow-");
5094 + yield* git(shallow, ["clone", "--depth=1", NodeURL.pathToFileURL(remote).href, "."]);
5095 + const shallowRefs = yield* git(shallow, ["show-ref", "--head"]);
5096 + const shallowSnapshot = yield* driver.readRefSnapshot(shallow);
5097 + assert.isNotNull(shallowSnapshot);
5098 + const shallowWorktree = yield* makeTmpDir("git-vcs-driver-shallow-worktree-");
5099 + yield* git(shallow, ["worktree", "add", "--detach", shallowWorktree]);
5100 + const worktreeSnapshot = yield* driver.readRefSnapshot(shallowWorktree);
5101 + assert.isNotNull(worktreeSnapshot);
5102 + yield* git(shallow, ["fetch", "--unshallow", "origin"]);
5103 + assert.equal(yield* git(shallow, ["show-ref", "--head"]), shallowRefs);
5104 + const unshallowSnapshot = yield* driver.readRefSnapshot(shallow);
5105 + const unshallowWorktreeSnapshot = yield* driver.readRefSnapshot(shallowWorktree);
5106 + assert.isNotNull(unshallowSnapshot);
5107 + assert.isNotNull(unshallowWorktreeSnapshot);
5108 + assert.notEqual(unshallowSnapshot, shallowSnapshot);
5109 + assert.notEqual(unshallowWorktreeSnapshot, worktreeSnapshot);
5110 +
5111 + yield* git(cwd, ["checkout", "--detach"]);
5112 + yield* git(cwd, ["commit", "--allow-empty", "-m", "detached"]);
5113 + assert.notEqual(yield* snapshot, fetched);
5114 +
5115 + const head = yield* git(cwd, ["rev-parse", "HEAD"]);
5116 + yield* driver.execute({
5117 + operation: "GitVcsDriver.test.git",
5118 + cwd,
5119 + args: ["update-ref", "--stdin"],
5120 + stdin: Array.from(
5121 + { length: 16_000 },
5122 + (_, index) => `create refs/heads/snapshot-${String(index).padStart(5, "0")} ${head}\n`,
5123 + ).join(""),
5124 + });
5125 + yield* git(cwd, ["pack-refs", "--all"]);
5126 + const large = yield* snapshot;
5127 + assert.isNotNull(large);
5128 + assert.isAbove(Buffer.byteLength(large ?? "", "utf8"), 1_000_000);
5129 + assert.equal(yield* snapshot, large);
5130 + yield* git(cwd, ["update-ref", "refs/heads/snapshot-00000", "HEAD~1"]);
5131 + assert.notEqual(yield* snapshot, large);
5132 +
5133 + assert.isNull(yield* driver.readRefSnapshot(yield* makeTmpDir()));
5134 + }),
5135 + );
5136 +
5137 it.effect("does not start Git auto-maintenance from background upstream fetches", () =>
5138 Effect.gen(function* () {
5139 const cwd = yield* makeTmpDir();
apps/server/src/vcs/GitVcsDriverCore.ts
+34
@@ -83,6 +83,7 @@ const FETCH_REMOTE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
83 const WORKTREE_INDEX_REFRESH_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
84 const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
85 const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
86 +const REF_SNAPSHOT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
87 const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
88 const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
89 const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
@@ -1733,6 +1734,38 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1734 ),
1735 });
1736
1737 + const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn(
1738 + "GitVcsDriver.readRefSnapshot",
1739 + )(
1740 + function* (cwd) {
1741 + const result = yield* executeGit(
1742 + "GitVcsDriver.readRefSnapshot",
1743 + cwd,
1744 + ["show-ref", "--head"],
1745 + {
1746 + allowNonZeroExit: true,
1747 + maxOutputBytes: REF_SNAPSHOT_MAX_OUTPUT_BYTES,
1748 + },
1749 + );
1750 + if (result.exitCode !== 0) return null;
1751 + const symbolicHead = yield* executeGit(
1752 + "GitVcsDriver.readRefSnapshot",
1753 + cwd,
1754 + ["symbolic-ref", "--quiet", "HEAD"],
1755 + { allowNonZeroExit: true },
1756 + );
1757 + // Exit 1 means detached HEAD; other failures require a full status read.
1758 + if (symbolicHead.exitCode !== 0 && symbolicHead.exitCode !== 1) return null;
1759 + // Deepening a shallow clone changes ancestry without moving refs.
1760 + const shallowPath = path.join(yield* resolveGitCommonDir(cwd), "shallow");
1761 + const shallow = (yield* fileSystem.exists(shallowPath))
1762 + ? yield* fileSystem.readFileString(shallowPath)
1763 + : "";
1764 + return `${result.stdout}\0${symbolicHead.stdout}\0${shallow}`;
1765 + },
1766 + Effect.orElseSucceed(() => null),
1767 + );
1768 +
1769 const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
1770 cwd: string,
1771 ) {
@@ -5929,6 +5962,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
5962 statusDetails,
5963 statusDetailsLocal,
5964 statusDetailsRemote,
5965 + readRefSnapshot,
5966 prepareCommitContext,
5967 commit: Effect.fnUntraced(function* (cwd, subject, body, options) {
5968 return yield* withListRefsInvalidation(cwd, commit(cwd, subject, body, options));
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+62
@@ -78,6 +78,7 @@ function layerTestFor(state: {
78 localInvalidationCalls: number;
79 remoteInvalidationCalls: number;
80 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
81 + refSnapshot?: string | null;
82 remoteStatusError?: GitManagerError;
83 backgroundWorkEnabled?: boolean;
84 automaticFetchInterval?: Effect.Effect<Duration.Duration>;
@@ -135,6 +136,8 @@ function layerTestFor(state: {
136 : (state.beforeCurrentBranch ?? Effect.void).pipe(
137 Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)),
138 ),
139 + readRefSnapshot: () =>
140 + Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)),
141 upstreamDivergence: () =>
142 Effect.sync(() =>
143 state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null
@@ -748,6 +751,7 @@ describe("VcsStatusBroadcaster", () => {
751 Layer.mock(GitWorkflowService.GitWorkflowService)({
752 localStatus: () => Effect.succeed(localStatus),
753 currentBranch: () => Effect.succeed(localStatus.refName),
754 + readRefSnapshot: () => Effect.succeed("refs"),
755 remoteStatus: () => Effect.succeed(remoteStatus),
756 invalidateLocalStatus: () => Effect.void,
757 invalidateRemoteStatus: () => Effect.void,
@@ -844,6 +848,7 @@ describe("VcsStatusBroadcaster", () => {
848 Layer.mock(GitWorkflowService.GitWorkflowService)({
849 localStatus: () => Effect.succeed(baseLocalStatus),
850 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
851 + readRefSnapshot: () => Effect.succeed("refs"),
852 remoteStatus: () =>
853 Effect.gen(function* () {
854 remoteReads += 1;
@@ -890,6 +895,7 @@ describe("VcsStatusBroadcaster", () => {
895 Layer.mock(GitWorkflowService.GitWorkflowService)({
896 localStatus: () => Effect.succeed(baseLocalStatus),
897 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
898 + readRefSnapshot: () => Effect.succeed("refs"),
899 remoteStatus: () =>
900 Effect.gen(function* () {
901 remoteReads += 1;
@@ -943,6 +949,7 @@ describe("VcsStatusBroadcaster", () => {
949 return state.currentLocalStatus;
950 }),
951 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
952 + readRefSnapshot: () => Effect.succeed("refs"),
953 remoteStatus: () =>
954 Effect.suspend(() => {
955 state.remoteStatusCalls += 1;
@@ -1160,6 +1167,7 @@ describe("VcsStatusBroadcaster", () => {
1167 branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 },
1168 };
1169 let cachedLocal: VcsStatusLocalResult | undefined;
1170 + let refSnapshot = "before";
1171 const readLocalStatus = () => Effect.sync(() => (cachedLocal ??= local));
1172 const layerTest = VcsStatusBroadcaster.layer.pipe(
1173 Layer.provideMerge(NodeServices.layer),
@@ -1177,6 +1185,7 @@ describe("VcsStatusBroadcaster", () => {
1185 }),
1186 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
1187 invalidateRemoteStatus: () => Effect.void,
1188 + readRefSnapshot: () => Effect.sync(() => refSnapshot),
1189 remoteStatus: () =>
1190 Deferred.succeed(fetchStarted, undefined).pipe(
1191 Effect.andThen(Deferred.await(finishFetch)),
@@ -1195,6 +1204,7 @@ describe("VcsStatusBroadcaster", () => {
1204 ...baseLocalStatus,
1205 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
1206 };
1207 + refSnapshot = "after";
1208 yield* Deferred.succeed(finishFetch, undefined);
1209 const status = yield* Fiber.join(refresh);
1210 assert.deepStrictEqual(status.branchChanges, local.branchChanges);
@@ -1202,6 +1212,58 @@ describe("VcsStatusBroadcaster", () => {
1212 });
1213 });
1214
1215 + it.effect("an explicit refresh re-reads local totals only after refs moved", () => {
1216 + const totals = (insertions: number): VcsStatusLocalResult => ({
1217 + ...baseLocalStatus,
1218 + branchChanges: { baseRef: "origin/main", insertions, deletions: 0 },
1219 + });
1220 + const state: Parameters<typeof layerTestFor>[0] = {
1221 + currentLocalStatus: totals(745),
1222 + currentRemoteStatus: remoteStatusWithPr,
1223 + localStatusCalls: 0,
1224 + remoteStatusCalls: 0,
1225 + localInvalidationCalls: 0,
1226 + remoteInvalidationCalls: 0,
1227 + };
1228 + return Effect.gen(function* () {
1229 + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1230 + const subscribed = yield* Deferred.make<void>();
1231 + const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
1232 + Stream.tap((event) =>
1233 + event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void,
1234 + ),
1235 + Stream.filter((event) => event._tag !== "snapshot"),
1236 + Stream.take(3),
1237 + Stream.runCollect,
1238 + Effect.forkScoped,
1239 + );
1240 + yield* Deferred.await(subscribed);
1241 +
1242 + state.localStatusCalls = 0;
1243 + yield* broadcaster.refreshStatus("/repo");
1244 + assert.equal(state.localStatusCalls, 1);
1245 +
1246 + state.localStatusCalls = 0;
1247 + state.currentRemoteStatus = baseRemoteStatus;
1248 + state.beforeRemoteStatus = Effect.sync(() => {
1249 + state.currentLocalStatus = totals(0);
1250 + state.refSnapshot = "moved";
1251 + });
1252 + const moved = yield* broadcaster.refreshStatus("/repo");
1253 + assert.equal(state.localStatusCalls, 2);
1254 + assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges);
1255 + assert.deepStrictEqual(
1256 + [...(yield* Fiber.join(events))].map((event) => event._tag),
1257 + ["remoteUpdated", "remoteUpdated", "localUpdated"],
1258 + );
1259 +
1260 + state.localStatusCalls = 0;
1261 + state.refSnapshot = null;
1262 + yield* broadcaster.refreshStatus("/repo");
1263 + assert.equal(state.localStatusCalls, 2);
1264 + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1265 + });
1266 +
1267 it.effect("publishes local status while an earlier lookup holds the remote lock", () => {
1268 const state: Parameters<typeof layerTestFor>[0] = {
1269 currentLocalStatus: baseLocalStatus,
apps/server/src/vcs/VcsStatusBroadcaster.ts
+11 -5
@@ -591,7 +591,7 @@ export const make = Effect.gen(function* () {
591 });
592
593 const refreshRemoteAndLocalTotals = Effect.fn("VcsStatusBroadcaster.refreshRemoteAndLocalTotals")(
594 - function* (cwd: string, policyCwd: string) {
594 + function* (cwd: string, policyCwd: string, refsBeforeLocalRead: string | null) {
595 return yield* withRemoteWriteLock(
596 cwd,
597 Effect.gen(function* () {
@@ -599,14 +599,19 @@ export const make = Effect.gen(function* () {
599 // Bump the PR lookup epoch after earlier remote writers have finished.
600 yield* workflow.invalidateStatus(cwd);
601 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
602 - // Fetch can move the base used for local Changes totals.
603 - yield* refreshLocalStatusCore(cwd);
602 // Without a fetch, the cached behind count cannot justify an automatic pull.
603 const pulled = refreshUpstream
604 ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd])
605 : null;
606 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
607 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
608 + // A fetch, ours or not, can move the base used for local Changes totals.
609 + if (
610 + refsBeforeLocalRead === null ||
611 + (yield* workflow.readRefSnapshot(cwd)) !== refsBeforeLocalRead
612 + ) {
613 + yield* refreshLocalStatusCore(cwd);
614 + }
615 const parts = yield* getStatusParts(cwd);
616 return mergeGitStatusParts(parts.local, parts.remote);
617 }),
@@ -618,13 +623,14 @@ export const make = Effect.gen(function* () {
623 "VcsStatusBroadcaster.refreshStatus",
624 )(function* (rawCwd, options) {
625 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
626 + const refsBeforeLocalRead = options?.localOnly ? null : yield* workflow.readRefSnapshot(cwd);
627 yield* refreshLocalStatusCore(cwd);
628 if (options?.localOnly) {
629 // Never cache a remote here: readers take `value: null` as "read and found no PR".
630 const parts = yield* getStatusParts(cwd);
631 return mergeGitStatusParts(parts.local, parts.remote);
632 }
627 - return yield* refreshRemoteAndLocalTotals(cwd, rawCwd);
633 + return yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead);
634 });
635
636 const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn(
@@ -635,7 +641,7 @@ export const make = Effect.gen(function* () {
641 // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct.
642 yield* refreshLocalStatusCore(cwd).pipe(
643 Effect.ensuring(Deferred.succeed(localDone, undefined)),
638 - Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd)),
644 + Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd, null)),
645 Effect.ignoreCause({ log: true }),
646 Effect.forkIn(broadcasterScope),
647 );