Fix Git ref refresh resource storms #4727
Mergedjuliusmarmingemerged 8 commits into
main fromrefs/pull/4727/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/vcs/GitVcsDriverCore.ts line 2287Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2117,16 +2191,5 @@2117- ),2118- executeGit(2119- "GitVcsDriver.listRefs.worktreeList",2120- input.cwd,2121- ["worktree", "list", "--porcelain"],2122- {2123- timeoutMs: 5_000,2124- allowNonZeroExit: true,2125- },2126- ),2127- remoteBranchResultEffect,2128- remoteNamesResultEffect,2129- branchRecencyPromise,2130- ],2131- { concurrency: "unbounded" },2132- );2191+ return {2192+ localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),2193+ remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),2194+ hasPrimaryRemote: remoteNames.includes("origin"),2195+ } satisfies GitRefsSnapshot;apps/server/src/vcs/GitVcsDriverCore.ts line 2423Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2221,11 +2274,10 @@2221- remoteBranch.remoteName = parsedRemoteRef.remoteName;2222- }2223- return Result.succeed(remoteBranch);2224- }).toSorted((a, b) => {2225- const aLastCommit = branchLastCommit.get(a.name) ?? 0;2226- const bLastCommit = branchLastCommit.get(b.name) ?? 0;2227- if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;2228- return a.name.localeCompare(b.name);2229- })2230- : [];2231-2274+ const snapshot = yield* resolveListRefsSnapshot(2275+ repositoryPaths.gitCommonDir,2276+ input.refresh === true,2277+ );2278+ const localBranches = snapshot.localBranches.map((ref) => ({2279+ ...ref,2280+ current:2281+ repositoryPaths.worktreeRoot !== null &&2282+ ref.worktreePath === repositoryPaths.worktreeRoot,2283+ }));packages/client-runtime/src/state/vcs.ts line 123Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -104,20 +104,3 @@104104 ).pipe(105105 Stream.map((connection) => (connection.phase === "connected" ? connection.generation : null)),106106 Stream.changes,107- Stream.switchMap((generation) =>108- generation === null109- ? Stream.empty110- : Stream.tick(VCS_REFS_REVALIDATE_INTERVAL).pipe(111- Stream.mapEffect(112- () =>113- refresh().pipe(114- Effect.map(Option.some),115- Effect.catch((error) =>116- Effect.logWarning("Could not refresh Git refs.").pipe(117- Effect.annotateLogs({118- environmentId,119- cwd: input.cwd,120- ...safeErrorLogAttributes(error),121- }),122- Effect.as(Option.none<VcsListRefsResult>()),123- ),
- apps/server/src/vcs/GitVcsDriverCore.ts line 1155Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -955,5 +1091,19 @@1091+ statusRemoteRefreshFailureCounts.delete(key);1092+ statusRemoteRefreshFailureCounts.set(key, nextCount);1093+ if (statusRemoteRefreshFailureCounts.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {1094+ const oldestKey = statusRemoteRefreshFailureCounts.keys().next().value;1095+ if (oldestKey !== undefined) {1096+ statusRemoteRefreshFailureCounts.delete(oldestKey);1097+ }1098+ }1099+ };1100+ const clearStatusRemoteRefreshFailures = (cacheKey: StatusRemoteRefreshCacheKey) => {1101+ statusRemoteRefreshFailureCounts.delete(statusRemoteRefreshFailureKey(cacheKey));1102+ };9551103 const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (9561104 cacheKey: StatusRemoteRefreshCacheKey,9571105 ) {958- yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);959- return true as const;1106+ return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(1107+ Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),1108+ Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),1109+ Effect.as(true as const),packages/client-runtime/src/state/vcs.ts line 92Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -82,11 +82,3 @@8282 return refs;8383 });848485- const cachedRefs = Stream.fromEffect(86- SubscriptionRef.get(supervisor.state).pipe(87- Effect.flatMap((connection) =>88- connection.phase === "connected"89- ? Effect.succeed(Option.none<VcsListRefsResult>())90- : Effect.succeed(cached),91- ),92- ),
- apps/server/src/vcs/GitVcsDriverCore.ts line 242Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -210,3 +227,10 @@210227 };211228 }212229230+function parseWorktreeBranchPaths(stdout: string): ReadonlyMap<string, string> {231+ const worktreePaths = new Map<string, string>();232+ let currentPath: string | null = null;233+ let currentBranch: string | null = null;234+ let currentPrunable = false;235+236+ const flush = () => {
- @@ -2223,9 +2337,12 @@2223- return Result.succeed(remoteBranch);2224- }).toSorted((a, b) => {2225- const aLastCommit = branchLastCommit.get(a.name) ?? 0;2226- const bLastCommit = branchLastCommit.get(b.name) ?? 0;2227- if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;2228- return a.name.localeCompare(b.name);2229- })2230- : [];2231-2337+ const snapshot = yield* resolveListRefsSnapshot(2338+ repositoryPaths.gitCommonDir,2339+ input.refresh === true,2340+ );2341+ const hasCurrentWorktreeBranch =2342+ repositoryPaths.worktreeRoot !== null &&2343+ snapshot.localBranches.some((ref) => ref.worktreePath === repositoryPaths.worktreeRoot);2344+ const localBranches = snapshot.localBranches.map((ref) => ({2345+ ...ref,2346+ current: hasCurrentWorktreeBranch2347+ ? ref.worktreePath === repositoryPaths.worktreeRoot2348+ : ref.name === repositoryPaths.currentBranch,
- @@ -107,18 +106,3 @@107106 Stream.switchMap((generation) =>108107 generation === null109108 ? Stream.empty110- : Stream.tick(VCS_REFS_REVALIDATE_INTERVAL).pipe(111- Stream.mapEffect(112- () =>113- refresh().pipe(114- Effect.map(Option.some),115- Effect.catch((error) =>116- Effect.logWarning("Could not refresh Git refs.").pipe(117- Effect.annotateLogs({118- environmentId,119- cwd: input.cwd,120- ...safeErrorLogAttributes(error),121- }),122- Effect.as(Option.none<VcsListRefsResult>()),123- ),124- ),
- @@ -160,3 +171,15 @@160171 readonly environmentId: EnvironmentId;161172 readonly input: VcsListRefsInput;162173 }) => listRefsByEnvironment(target.environmentId)(JSON.stringify(target.input));174+ const invalidateRefs = (175+ target: {176+ readonly environmentId: EnvironmentId;177+ readonly input: { readonly cwd: string };178+ },179+ registry: AtomRegistry.AtomRegistry,180+ ) => {181+ refsInvalidation.invalidate(registry, {182+ environmentId: target.environmentId,183+ cwd: target.input.cwd,184+ });185+ };
- @@ -202,18 +223,21 @@202223 }),203224 createRef: createEnvironmentRpcCommand(runtime, {204225 label: "environment-data:vcs:create-ref",205226 tag: WS_METHODS.vcsCreateRef,206227 scheduler: vcsCommandScheduler,207228 concurrency: vcsCommandConcurrency,229+ onSuccess: invalidateRefs,208230 }),209231 switchRef: createEnvironmentRpcCommand(runtime, {210232 label: "environment-data:vcs:switch-ref",211233 tag: WS_METHODS.vcsSwitchRef,212234 scheduler: vcsCommandScheduler,213235 concurrency: vcsCommandConcurrency,236+ onSuccess: invalidateRefs,214237 }),215238 init: createEnvironmentRpcCommand(runtime, {216239 label: "environment-data:vcs:init",217240 tag: WS_METHODS.vcsInit,218241 scheduler: vcsCommandScheduler,219242 concurrency: vcsCommandConcurrency,243+ onSuccess: invalidateRefs,
- @@ -82,12 +90,4 @@8290 return refs;8391 });849285- const cachedRefs = Stream.fromEffect(86- SubscriptionRef.get(supervisor.state).pipe(87- Effect.flatMap((connection) =>88- connection.phase === "connected"89- ? Effect.succeed(Option.none<VcsListRefsResult>())90- : Effect.succeed(cached),91- ),92- ),93- ).pipe(93+ const cachedRefs = Stream.fromEffect(Effect.succeed(cached)).pipe(@@ -489,3 +490,8 @@489490 }),490491 },491492 ).pipe(493+ Effect.tap(() =>494+ Effect.sync(() => {495+ invalidateVcsRefs(registry, target);496+ }),497+ ),
- packages/client-runtime/src/state/vcs.ts line 262Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -160,3 +151,4 @@160151 readonly environmentId: EnvironmentId;161152 readonly input: VcsListRefsInput;162153 }) => listRefsByEnvironment(target.environmentId)(JSON.stringify(target.input));154+ const invalidateRefs = (
- packages/client-runtime/src/state/vcsRefInvalidation.ts line 52OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+ * Removes the persisted snapshot before restarting live ref streams. This33+ * prevents a remount during the refresh window from replaying pre-mutation34+ * branch data.35+ */36+export const invalidateCachedVcsRefs = Effect.fn("VcsRefsState.invalidateCached")(function* (37+ registry: AtomRegistry.AtomRegistry,38+ target: CachedVcsRefsInvalidationTarget,39+) {40+ const cache = yield* EnvironmentCacheStore;41+ yield* cache.removeVcsRefs(target.environmentId, target.cwd).pipe(42+ Effect.catch((error) =>43+ Effect.logWarning("Could not remove invalidated cached Git refs.").pipe(44+ Effect.annotateLogs({45+ environmentId: target.environmentId,46+ cwd: target.cwd,47+ ...safeErrorLogAttributes(error),48+ }),49+ ),50+ ),51+ );52+ invalidateVcsRefs(registry, target);
- @@ -82,9 +90,3 @@8290 return refs;8391 });849285- const cachedRefs = Stream.fromEffect(86- SubscriptionRef.get(supervisor.state).pipe(87- Effect.flatMap((connection) =>88- connection.phase === "connected"89- ? Effect.succeed(Option.none<VcsListRefsResult>())90- : Effect.succeed(cached),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- packages/client-runtime/src/state/vcsRefInvalidation.ts lines 53 to 55OutdatedResolvedby juliusmarminge@@ -0,0 +35,21 @@35+ effect: Effect.Effect<A, E, R>,36+): Effect.Effect<A, E, R> {37+ return persistenceLock.withPermit(environmentId)(effect);38+}39+40+/**41+ * Restarts live ref streams and clears persisted snapshots while holding the42+ * same lock used by generation-checked refresh writes. A refresh that wins the43+ * lock is cleared afterward; one that loses observes the new revision and44+ * cannot repersist its pre-mutation result.45+ */46+export const invalidateCachedVcsRefs = Effect.fn("VcsRefsState.invalidateCached")(function* (47+ registry: AtomRegistry.AtomRegistry,48+ target: CachedVcsRefsInvalidationTarget,49+) {50+ const cache = yield* EnvironmentCacheStore;51+ yield* withVcsRefsPersistenceLock(52+ target.environmentId,53+ Effect.gen(function* () {54+ invalidateVcsRefs(registry, target);55+ yield* cache.clearVcsRefs(target.environmentId).pipe(
- apps/server/src/vcs/GitVcsDriverCore.ts line 246OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -210,3 +228,19 @@210228 };211229 }212230231+function parseWorktreeBranchPaths(stdout: string): ReadonlyMap<string, string> {232+ const worktreePaths = new Map<string, string>();233+ let currentPath: string | null = null;234+ let currentBranch: string | null = null;235+ let currentPrunable = false;236+237+ const flush = () => {238+ if (currentPath !== null && currentBranch !== null && !currentPrunable) {239+ worktreePaths.set(currentBranch, currentPath);240+ }241+ currentPath = null;242+ currentBranch = null;243+ currentPrunable = false;244+ };245+246+ for (const line of stdout.split("\n")) {
- @@ -2145,0 +2324,21 @@2324+ // The refresh cache owns the complete snapshot read, rather than only the2325+ // epoch bump. Slow repositories therefore remain singleflight for the2326+ // entire Git scan even when more refresh requests arrive after the2327+ // coalescing TTL would otherwise have elapsed.2328+ return Cache.get(listRefsRefreshSnapshotCache, gitCommonDir);2329+ }2330+ return Cache.get(2331+ listRefsSnapshotCache,2332+ new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }),2333+ );2334+ };2335+ const invalidateListRefsSnapshot = Effect.fn("invalidateListRefsSnapshot")(function* (2336+ cwd: string,2337+ ) {2338+ const repositoryPathsCacheKey = normalizeRepositoryPathsCacheKey(cwd);2339+ const repositoryPaths = yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey);2340+ if (repositoryPaths === null) return;2341+ yield* Cache.invalidate(listRefsRefreshSnapshotCache, repositoryPaths.gitCommonDir);2342+ bumpListRefsEpoch(repositoryPaths.gitCommonDir);2343+ yield* Cache.invalidate(repositoryPathsRefreshCache, repositoryPathsCacheKey);2344+ yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey);
- @@ -202,18 +277,21 @@202277 }),203278 createRef: createEnvironmentRpcCommand(runtime, {204279 label: "environment-data:vcs:create-ref",205280 tag: WS_METHODS.vcsCreateRef,206281 scheduler: vcsCommandScheduler,207282 concurrency: vcsCommandConcurrency,283+ onSuccess: invalidateRefs,208284 }),209285 switchRef: createEnvironmentRpcCommand(runtime, {210286 label: "environment-data:vcs:switch-ref",211287 tag: WS_METHODS.vcsSwitchRef,212288 scheduler: vcsCommandScheduler,213289 concurrency: vcsCommandConcurrency,290+ onSuccess: invalidateRefs,214291 }),215292 init: createEnvironmentRpcCommand(runtime, {216293 label: "environment-data:vcs:init",217294 tag: WS_METHODS.vcsInit,218295 scheduler: vcsCommandScheduler,219296 concurrency: vcsCommandConcurrency,297+ onSuccess: invalidateRefs,@@ -2231 +2394,21 @@2394+ function* (input) {2395+ const repositoryPaths = yield* resolveRepositoryPaths(input.cwd, input.refresh === true).pipe(2396+ Effect.catchTags({2397+ GitCommandError: (error) =>2398+ isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),2399+ }),2400+ );2401+ if (repositoryPaths === null) {2402+ return {2403+ refs: [],2404+ isRepo: false,2405+ hasPrimaryRemote: false,2406+ nextCursor: null,2407+ totalCount: 0,2408+ };2409+ }223124102411+ const snapshot = yield* resolveListRefsSnapshot(2412+ repositoryPaths.gitCommonDir,2413+ input.refresh === true,2414+ );@@ -0,0 +46,21 @@46+ */47+export const invalidateCachedVcsRefs = Effect.fn("VcsRefsState.invalidateCached")(function* (48+ registry: AtomRegistry.AtomRegistry,49+ target: CachedVcsRefsInvalidationTarget,50+) {51+ const cache = yield* EnvironmentCacheStore;52+ yield* withVcsRefsPersistenceLock(53+ target.environmentId,54+ Effect.gen(function* () {55+ yield* cache.clearVcsRefs(target.environmentId).pipe(56+ Effect.catch((error) =>57+ Effect.logWarning("Could not remove invalidated cached Git refs.").pipe(58+ Effect.annotateLogs({59+ environmentId: target.environmentId,60+ cwd: target.cwd,61+ ...safeErrorLogAttributes(error),62+ }),63+ ),64+ ),65+ );66+ invalidateVcsRefs(registry, target);
- packages/client-runtime/src/state/vcsRefInvalidation.ts line 39Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +19,21 @@19+ readonly persistedCacheReadable: boolean;20+}21+22+const stateByEnvironment = Atom.family((environmentId: EnvironmentId) =>23+ Atom.make<VcsRefsCacheState>({24+ revision: 0,25+ persistedCacheReadable: true,26+ }).pipe(Atom.withLabel(`environment-data:vcs:list-refs-state:${environmentId}`)),27+);28+const persistenceLock = PartitionedSemaphore.makeUnsafe<EnvironmentId>({ permits: 1 });29+30+export function vcsRefsCacheStateAtom(target: VcsRefsInvalidationTarget) {31+ return stateByEnvironment(target.environmentId);32+}33+34+export function invalidateVcsRefs(35+ registry: AtomRegistry.AtomRegistry,36+ target: VcsRefsInvalidationTarget,37+ persistedCacheReadable?: boolean,38+): void {39+ registry.update(vcsRefsCacheStateAtom(target), (state) => ({
- @@ -181,3 +288,4 @@181288 tag: WS_METHODS.vcsPull,182289 scheduler: vcsCommandScheduler,183290 concurrency: vcsCommandConcurrency,291+ onSettled: invalidateRefs,
- apps/web/src/state/paginatedBranches.ts lines 31 to 31OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+ return (12+ results.length > 1 &&13+ lastResult?.waiting === true &&14+ Option.isNone(AsyncResult.value(lastResult))15+ );16+}17+18+export function shouldLoadNextBranchPageAfterScroll({19+ previousScrollTop,20+ scrollTop,21+ scrollHeight,22+ clientHeight,23+ distanceThreshold = DEFAULT_NEXT_PAGE_DISTANCE_PX,24+}: {25+ previousScrollTop: number | null;26+ scrollTop: number;27+ scrollHeight: number;28+ clientHeight: number;29+ distanceThreshold?: number;30+}): boolean {31+ if (previousScrollTop === null || scrollTop <= previousScrollTop + 1) {
- @@ -0,0 +15,21 @@15+ );16+}17+18+export function shouldLoadNextBranchPageAfterScroll({19+ previousScrollTop,20+ scrollTop,21+ scrollHeight,22+ clientHeight,23+ distanceThreshold = DEFAULT_NEXT_PAGE_DISTANCE_PX,24+}: {25+ previousScrollTop: number | null;26+ scrollTop: number;27+ scrollHeight: number;28+ clientHeight: number;29+ distanceThreshold?: number;30+}): boolean {31+ if (previousScrollTop === null || scrollTop <= previousScrollTop) {32+ return false;33+ }34+35+ return scrollHeight - scrollTop - clientHeight <= distanceThreshold;
juliusmarminge merged this38a6e3c
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
bf4cae2f-84f1-4725-a1b6-03f7acf28615You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.