From 96ec3c8f864bd7482ae90fe6c49f95aaf31550e2 Mon Sep 17 00:00:00 2001 From: Alex Vallone <39172404+amv146@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:18:50 -0800 Subject: [PATCH 1/4] perf(server): status subscribe and branch switch no longer read local Git status twice The second local status read after the remote read now runs only if refs moved since the first, using the same ref snapshot refreshStatus already uses. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/vcs/VcsStatusBroadcaster.test.ts | 113 +++++++++++++++++- apps/server/src/vcs/VcsStatusBroadcaster.ts | 94 +++++++++++---- 2 files changed, 185 insertions(+), 22 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 08fad4ae56aff..afeb0def040bc 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -80,6 +80,7 @@ function layerTestFor(state: { remoteStatusRefreshUpstreamValues?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; + beforeRefSnapshot?: Effect.Effect; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; automaticFetchInterval?: Effect.Effect; @@ -142,7 +143,11 @@ function layerTestFor(state: { Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), readRefSnapshot: () => - Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), + (state.beforeRefSnapshot ?? Effect.void).pipe( + Effect.andThen( + Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), + ), + ), upstreamDivergence: () => Effect.sync(() => state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null @@ -2284,3 +2289,109 @@ it.effect("does not replay older queued branches after a new subscriber snapshot yield* Fiber.join(subscriber); }).pipe(Effect.provide(layerTestFor(state))); }); + +// `remoteUpdated` is published after the first poll has decided whether to re-read local status. +const subscribeForFirstPoll = Effect.fn("test.subscribeForFirstPoll")(function* ( + b: VcsStatusBroadcaster.VcsStatusBroadcaster["Service"], +) { + const polled = yield* Deferred.make(); + yield* b.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => + event._tag === "remoteUpdated" ? Deferred.succeed(polled, undefined) : Effect.void, + ), + Effect.forkScoped({ startImmediately: true }), + ); + return polled; +}); + +it.effect("a retried first poll reads local status again", () => { + const state = newState(); + state.currentRemoteStatus = baseRemoteStatus; + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const firstFailed = yield* Deferred.make(); + let attempts = 0; + state.beforeRemoteStatus = Effect.suspend(() => + attempts++ === 0 + ? Deferred.succeed(firstFailed, undefined).pipe( + Effect.andThen( + Effect.fail( + new GitManagerError({ operation: "test", cwd: "/repo", detail: "offline" }), + ), + ), + ) + : Effect.void, + ); + const polled = yield* subscribeForFirstPoll(b); + yield* Deferred.await(firstFailed); + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(polled); + // The initial load, then the retry: its baseline was spent on the failed attempt. + assert.strictEqual(state.localStatusCalls, 2); + }).pipe(Effect.provide(layerTestFor(state))); +}); + +it.effect("a first subscription's poll re-reads when its load reused a cached result", () => { + const state = newState(); + state.currentRemoteStatus = baseRemoteStatus; + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + // Caches local status without a remote, so the subscription's load reads nothing itself. + yield* b.refreshStatus("/repo", { localOnly: true }); + yield* Deferred.await(yield* subscribeForFirstPoll(b)); + // The refresh's read, then the poll's: a probe cannot certify a read it did not precede. + assert.strictEqual(state.localStatusCalls, 2); + }).pipe(Effect.provide(layerTestFor(state))); +}); + +it.effect.each([ + { refs: "unchanged", localReads: 1 }, + { refs: "moved", localReads: 2 }, +] as const)( + "a first subscription's poll re-reads local status only when refs moved (%j)", + ({ refs, localReads }) => { + const state = newState(); + state.currentRemoteStatus = baseRemoteStatus; + if (refs === "moved") { + state.beforeRemoteStatus = Effect.sync(() => { + state.refSnapshot = "moved"; + }); + } + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* Deferred.await(yield* subscribeForFirstPoll(b)); + assert.strictEqual(state.localStatusCalls, localReads); + }).pipe(Effect.provide(layerTestFor(state))); + }, +); + +it.effect.each([ + { refs: "unchanged", localReads: 1 }, + { refs: "moved", localReads: 2 }, + // A probe that never finishes certifies nothing and must not hold up the remote read. + { refs: "unfinished", localReads: 2 }, +] as const)( + "a checkout re-reads local status after its remote read only when refs moved (%j)", + ({ refs, localReads }) => { + const state = newState(); + state.currentRemoteStatus = baseRemoteStatus; + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* b.getStatus({ cwd: "/repo" }); + state.localStatusCalls = 0; + if (refs === "unfinished") state.beforeRefSnapshot = Effect.never; + const remoteStarted = yield* Deferred.make(); + const releaseRemote = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.succeed(remoteStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRemote)), + ); + yield* b.refreshAfterCheckout("/repo"); + yield* Deferred.await(remoteStarted); + if (refs === "moved") state.refSnapshot = "moved"; + yield* Deferred.succeed(releaseRemote, undefined); + // The checkout's background refresh holds the remote lock until its local decision is made. + yield* b.refreshPullRequestStatus("/repo"); + assert.strictEqual(state.localStatusCalls, localReads); + }).pipe(Effect.provide(layerTestFor(state))); + }, +); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index b691b9d2978a2..45428790257e4 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -158,6 +158,11 @@ interface ActiveHeadWatcher { readonly subscriberCount: number; } +interface InitialRefs { + /** Emptied by the poll that reads it, so the long-lived loop does not keep the snapshot. */ + refs: string | null; +} + interface ActiveRemotePoller { readonly fiber: Fiber.Fiber; readonly subscriberCount: number; @@ -417,8 +422,23 @@ export const make = Effect.gen(function* () { return yield* updateCachedLocalStatus(cwd, yield* readLocalStatus(cwd), observation, options); }); + // Runs a fresh local read with a ref probe started just before it, so the probe's `show-ref` is + // queued ahead of the read it certifies. The refs come back only if the probe finished by the end + // of the read; otherwise null, and the caller repeats the read as it did before. + const withRefProbe = Effect.fn("VcsStatusBroadcaster.withRefProbe")(function* ( + cwd: string, + read: Effect.Effect, + ) { + const probe = yield* workflow + .readRefSnapshot(cwd) + .pipe(Effect.forkIn(broadcasterScope, { startImmediately: true })); + const result = yield* read; + const exit = probe.pollUnsafe(); + return { result, refs: exit !== undefined && Exit.isSuccess(exit) ? exit.value : null }; + }); + const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")( - function* (cwd: string) { + function* (cwd: string, initialRefs?: InitialRefs) { const cached = yield* getCachedStatus(cwd); if (cached?.local) { if (cached.local.includesBranchChanges || !wantsBranchChanges(cwd)) { @@ -428,12 +448,16 @@ export const make = Effect.gen(function* () { yield* workflow.invalidateLocalStatus(cwd); return yield* loadLocalStatus(cwd, { publish: true }); } - return yield* loadLocalStatus(cwd); + if (initialRefs === undefined) return yield* loadLocalStatus(cwd); + // Only a read made here can be certified; a cached result may predate the probe. + const { result, refs } = yield* withRefProbe(cwd, loadLocalStatus(cwd)); + initialRefs.refs = refs; + return result; }, ); - const getOrLoadLocalStatus = (cwd: string) => - localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd)); + const getOrLoadLocalStatus = (cwd: string, initialRefs?: InitialRefs) => + localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd, initialRefs)); const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) { const cached = yield* getCachedStatus(cwd); @@ -505,6 +529,20 @@ export const make = Effect.gen(function* () { }, ); + // A fetch, ours or not, can move the base used for local Changes totals. Without a baseline + // snapshot there is nothing to compare, so the read always happens. + const refreshLocalStatusUnlessRefsUnchanged = Effect.fn( + "VcsStatusBroadcaster.refreshLocalStatusUnlessRefsUnchanged", + )(function* (cwd: string, refsBeforeLocalRead: string | null) { + if ( + refsBeforeLocalRead !== null && + (yield* workflow.readRefSnapshot(cwd)) === refsBeforeLocalRead + ) { + return; + } + yield* refreshLocalStatusCore(cwd); + }); + const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn( "VcsStatusBroadcaster.refreshLocalStatus", )(function* (rawCwd) { @@ -625,6 +663,8 @@ export const make = Effect.gen(function* () { options?: { readonly refreshUpstream?: boolean; readonly policyCwds?: ReadonlyArray; + /** Refs before a local read the caller just made, which a read of unmoved refs would repeat. */ + readonly refsBeforeLocalRead?: string | null; }, ) { return yield* withRemoteWriteLock( @@ -637,7 +677,7 @@ export const make = Effect.gen(function* () { : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]); if (pulled !== null) return pulled.remote; // Base refs and merge bases can move without changing divergence counts. - yield* refreshLocalStatusCore(cwd); + yield* refreshLocalStatusUnlessRefsUnchanged(cwd, options?.refsBeforeLocalRead ?? null); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), ); @@ -658,13 +698,7 @@ export const make = Effect.gen(function* () { : null; if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); - // A fetch, ours or not, can move the base used for local Changes totals. - if ( - refsBeforeLocalRead === null || - (yield* workflow.readRefSnapshot(cwd)) !== refsBeforeLocalRead - ) { - yield* refreshLocalStatusCore(cwd); - } + yield* refreshLocalStatusUnlessRefsUnchanged(cwd, refsBeforeLocalRead); const parts = yield* getStatusParts(cwd); return mergeGitStatusParts(parts.local, parts.remote); }), @@ -693,12 +727,13 @@ export const make = Effect.gen(function* () { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); const localDone = yield* Deferred.make(); // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct. - yield* refreshLocalStatusCore(cwd).pipe( - Effect.ensuring(Deferred.succeed(localDone, undefined)), - Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd, null)), - Effect.ignoreCause({ log: true }), - Effect.forkIn(broadcasterScope), - ); + yield* Effect.gen(function* () { + const { refs } = yield* withRefProbe( + cwd, + refreshLocalStatusCore(cwd).pipe(Effect.ensuring(Deferred.succeed(localDone, undefined))), + ); + yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refs); + }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(broadcasterScope)); yield* Deferred.await(localDone); }); @@ -725,6 +760,7 @@ export const make = Effect.gen(function* () { cwd: string, demandCwdsRef: Ref.Ref>, refreshImmediately: boolean, + initialRefs: InitialRefs, ) { const consecutiveFailuresRef = yield* Ref.make(0); const needsInitialRefreshRef = yield* Ref.make(refreshImmediately); @@ -754,9 +790,13 @@ export const make = Effect.gen(function* () { return activeInterval; } + // Only the first attempt follows the read made with this subscription; a retry reads again. + const refsBeforeLocalRead = initialRefs.refs; + initialRefs.refs = null; const exit = yield* refreshRemoteStatus(cwd, { refreshUpstream: !Duration.isZero(configuredInterval), policyCwds: [...demandCwds.keys()], + refsBeforeLocalRead, }).pipe(Effect.exit); if (Exit.isSuccess(exit)) { yield* Ref.set(needsInitialRefreshRef, false); @@ -806,6 +846,7 @@ export const make = Effect.gen(function* () { cwd: string, demandCwd: string, refreshImmediately: boolean, + initialRefs: InitialRefs, ) { yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => { const existing = activePollers.get(cwd); @@ -828,7 +869,7 @@ export const make = Effect.gen(function* () { return Ref.make>(new Map([[demandCwd, 1]])).pipe( Effect.flatMap((demandCwds) => - makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe( + makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately, initialRefs).pipe( Effect.forkIn(broadcasterScope), Effect.map((fiber) => { const nextPollers = new Map(activePollers); @@ -1113,14 +1154,25 @@ export const make = Effect.gen(function* () { const subscription = yield* PubSub.subscribe(changesPubSub); // Watch before reading so a checkout in between still publishes. yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd)); - const initialLocal = yield* getOrLoadLocalStatus(cwd); + // A cached remote means no immediate poll, so nothing would use the refs. Otherwise a fresh + // load records them for that poll. + const initialRefs: InitialRefs = { refs: null }; + const initialLocal = yield* getOrLoadLocalStatus( + cwd, + input.includeRemote !== false && (yield* getCachedStatus(cwd))?.remote == null + ? initialRefs + : undefined, + ); const cachedStatus = yield* getCachedStatus(cwd); const initialRemote = cachedStatus?.remote?.value ?? null; if (input.includeRemote !== false) { + const refreshImmediately = + cachedStatus?.remote === null || cachedStatus?.remote === undefined; yield* retainRemotePoller( cwd, input.cwd, - cachedStatus?.remote === null || cachedStatus?.remote === undefined, + refreshImmediately, + refreshImmediately ? initialRefs : { refs: null }, ); } const release = From e1fced8296324066c399e7251c693ec8d2ccb5e7 Mon Sep 17 00:00:00 2001 From: Alex Vallone <39172404+amv146@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:33:20 -0800 Subject: [PATCH 2/4] fix(server): certify the first subscription read from git, not the status cache The workflow caches local status for one second, so a cached read could predate the ref probe and be certified as fresh. Invalidate before the probed read. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/server/src/vcs/VcsStatusBroadcaster.test.ts | 8 +++++--- apps/server/src/vcs/VcsStatusBroadcaster.ts | 1 + 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index afeb0def040bc..fc964fe52310b 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -2345,11 +2345,11 @@ it.effect("a first subscription's poll re-reads when its load reused a cached re }); it.effect.each([ - { refs: "unchanged", localReads: 1 }, - { refs: "moved", localReads: 2 }, + { refs: "unchanged", localReads: 1, invalidations: 1 }, + { refs: "moved", localReads: 2, invalidations: 2 }, ] as const)( "a first subscription's poll re-reads local status only when refs moved (%j)", - ({ refs, localReads }) => { + ({ refs, localReads, invalidations }) => { const state = newState(); state.currentRemoteStatus = baseRemoteStatus; if (refs === "moved") { @@ -2361,6 +2361,8 @@ it.effect.each([ const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; yield* Deferred.await(yield* subscribeForFirstPoll(b)); assert.strictEqual(state.localStatusCalls, localReads); + // The certified read must come from git, not the workflow's one-second cache. + assert.strictEqual(state.localInvalidationCalls, invalidations); }).pipe(Effect.provide(layerTestFor(state))); }, ); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 45428790257e4..66707f9244909 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -450,6 +450,7 @@ export const make = Effect.gen(function* () { } if (initialRefs === undefined) return yield* loadLocalStatus(cwd); // Only a read made here can be certified; a cached result may predate the probe. + yield* workflow.invalidateLocalStatus(cwd); const { result, refs } = yield* withRefProbe(cwd, loadLocalStatus(cwd)); initialRefs.refs = refs; return result; From 8572329447d08a75c7f7c0246e9d0af33baa3166 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 06:11:38 +0000 Subject: [PATCH 3/4] refactor(server): take the ref snapshot before the local read it vouches for A probe forked alongside the read could see refs that moved after git status read them, then skip the re-read that would have caught the move. Reading the snapshot first, as refreshStatus already does, closes that window and drops the fork. Co-Authored-By: Claude Opus 5.5 --- .../src/vcs/VcsStatusBroadcaster.test.ts | 12 +----- apps/server/src/vcs/VcsStatusBroadcaster.ts | 37 +++++-------------- 2 files changed, 12 insertions(+), 37 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 1f900ffe13940..b398eef243ee4 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -80,7 +80,6 @@ function layerTestFor(state: { remoteStatusRefreshUpstreamValues?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; - beforeRefSnapshot?: Effect.Effect; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; automaticFetchInterval?: Effect.Effect; @@ -143,11 +142,7 @@ function layerTestFor(state: { Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), readRefSnapshot: () => - (state.beforeRefSnapshot ?? Effect.void).pipe( - Effect.andThen( - Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), - ), - ), + Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), upstreamDivergence: () => Effect.sync(() => state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null @@ -2508,7 +2503,7 @@ it.effect("a first subscription's poll re-reads when its load reused a cached re // Caches local status without a remote, so the subscription's load reads nothing itself. yield* b.refreshStatus("/repo", { localOnly: true }); yield* Deferred.await(yield* subscribeForFirstPoll(b)); - // The refresh's read, then the poll's: a probe cannot certify a read it did not precede. + // The refresh's read, then the poll's: a snapshot cannot vouch for a read it did not precede. assert.strictEqual(state.localStatusCalls, 2); }).pipe(Effect.provide(layerTestFor(state))); }); @@ -2537,8 +2532,6 @@ it.effect.each([ it.effect.each([ { refs: "unchanged", localReads: 1 }, { refs: "moved", localReads: 2 }, - // A probe that never finishes certifies nothing and must not hold up the remote read. - { refs: "unfinished", localReads: 2 }, ] as const)( "a checkout re-reads local status after its remote read only when refs moved (%j)", ({ refs, localReads }) => { @@ -2548,7 +2541,6 @@ it.effect.each([ const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; yield* b.getStatus({ cwd: "/repo" }); state.localStatusCalls = 0; - if (refs === "unfinished") state.beforeRefSnapshot = Effect.never; const remoteStarted = yield* Deferred.make(); const releaseRemote = yield* Deferred.make(); state.beforeRemoteStatus = Deferred.succeed(remoteStarted, undefined).pipe( diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index f9df063c6eb75..129efef323934 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -476,21 +476,6 @@ export const make = Effect.gen(function* () { return yield* updateCachedLocalStatus(cwd, yield* readLocalStatus(cwd), observation, options); }); - // Runs a fresh local read with a ref probe started just before it, so the probe's `show-ref` is - // queued ahead of the read it certifies. The refs come back only if the probe finished by the end - // of the read; otherwise null, and the caller repeats the read as it did before. - const withRefProbe = Effect.fn("VcsStatusBroadcaster.withRefProbe")(function* ( - cwd: string, - read: Effect.Effect, - ) { - const probe = yield* workflow - .readRefSnapshot(cwd) - .pipe(Effect.forkIn(broadcasterScope, { startImmediately: true })); - const result = yield* read; - const exit = probe.pollUnsafe(); - return { result, refs: exit !== undefined && Exit.isSuccess(exit) ? exit.value : null }; - }); - const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")( function* (cwd: string, initialRefs?: InitialRefs) { const cached = yield* getCachedStatus(cwd); @@ -502,11 +487,9 @@ export const make = Effect.gen(function* () { yield* workflow.invalidateLocalStatus(cwd); return yield* loadLocalStatus(cwd, { publish: true }); } - if (initialRefs === undefined) return yield* loadLocalStatus(cwd); - // Only a read made here can be certified; a cached result may predate the probe. - const { result, refs } = yield* withRefProbe(cwd, loadLocalStatus(cwd)); - initialRefs.refs = refs; - return result; + // Only a read made here follows the snapshot; a cached result may predate it. + if (initialRefs !== undefined) initialRefs.refs = yield* workflow.readRefSnapshot(cwd); + return yield* loadLocalStatus(cwd); }, ); @@ -770,13 +753,13 @@ export const make = Effect.gen(function* () { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); const localDone = yield* Deferred.make(); // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct. - yield* Effect.gen(function* () { - const { refs } = yield* withRefProbe( - cwd, - refreshLocalStatusCore(cwd).pipe(Effect.ensuring(Deferred.succeed(localDone, undefined))), - ); - yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refs); - }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(broadcasterScope)); + yield* workflow.readRefSnapshot(cwd).pipe( + Effect.tap(() => refreshLocalStatusCore(cwd)), + Effect.ensuring(Deferred.succeed(localDone, undefined)), + Effect.flatMap((refs) => refreshRemoteAndLocalTotals(cwd, rawCwd, refs)), + Effect.ignoreCause({ log: true }), + Effect.forkIn(broadcasterScope), + ); yield* Deferred.await(localDone); }); From add4601d12e408a3f24543f065b06a339ed0f000 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 08:18:05 +0000 Subject: [PATCH 4/4] perf(server): a checkout's HEAD watch shares the checkout's local read The HEAD watcher asked for its local read only after its own remote read, so the switchRef refresh that had already read the new branch could not serve it and every checkout still ran git status twice. Record the request when the HEAD event arrives so any read started after the move covers it. Co-Authored-By: Claude Opus 5.5 --- .../src/vcs/VcsStatusBroadcaster.test.ts | 49 +++++++++++++++++++ apps/server/src/vcs/VcsStatusBroadcaster.ts | 37 +++++++++----- 2 files changed, 75 insertions(+), 11 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index b157db36cebb7..5564d8b340061 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -1982,6 +1982,55 @@ describe("VcsStatusBroadcaster", () => { }), ); + it.effect("a checkout's own refresh also serves the HEAD watch it set off", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath: "/repo/.git/HEAD", + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: () => Effect.succeed(true), + watch: (_target, options) => + Stream.fromQueue(events).pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))), + }), + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const subscribed = yield* Deferred.make(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach(() => Deferred.succeed(subscribed, undefined)), + Effect.forkScoped, + ); + yield* Deferred.await(subscribed); + + // `git switch` moves HEAD before the switchRef RPC starts its own refresh. + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "other" }; + state.localStatusCalls = 0; + const watchReading = yield* Deferred.make(); + const releaseWatch = yield* Deferred.make(); + state.beforeRemoteStatus = Deferred.succeed(watchReading, undefined).pipe( + Effect.andThen(Deferred.await(releaseWatch)), + ); + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + yield* Deferred.await(watchReading); + state.beforeRemoteStatus = Effect.void; + yield* broadcaster.refreshAfterCheckout("/repo"); + yield* Deferred.succeed(releaseWatch, undefined); + // Queued behind the watch's and the checkout's remote reads. + yield* broadcaster.refreshPullRequestStatus("/repo"); + assert.strictEqual(state.localStatusCalls, 1); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }), + ); + it.effect("subscribers share one HEAD watch that ends with the last of them", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index e4df8ec360ece..289913ef5d412 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -531,10 +531,16 @@ export const make = Effect.gen(function* () { ); }, Effect.scoped); + const requestLocalRefresh = (cwd: string) => { + const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1; + localRefreshRequests.set(cwd, requestedAt); + return requestedAt; + }; + + // `earlierRequest` lets a caller that learned of a change earlier share any read started since. const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")( - function* (cwd: string) { - const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1; - localRefreshRequests.set(cwd, requestedAt); + function* (cwd: string, earlierRequest?: number) { + const requestedAt = earlierRequest ?? requestLocalRefresh(cwd); return yield* localRefreshLocks.withLock( cwd, Effect.gen(function* () { @@ -561,14 +567,14 @@ export const make = Effect.gen(function* () { // snapshot there is nothing to compare, so the read always happens. const refreshLocalStatusUnlessRefsUnchanged = Effect.fn( "VcsStatusBroadcaster.refreshLocalStatusUnlessRefsUnchanged", - )(function* (cwd: string, refsBeforeLocalRead: string | null) { + )(function* (cwd: string, refsBeforeLocalRead: string | null, localRequestedAt?: number) { if ( refsBeforeLocalRead !== null && (yield* workflow.readRefSnapshot(cwd)) === refsBeforeLocalRead ) { return; } - yield* refreshLocalStatusCore(cwd); + yield* refreshLocalStatusCore(cwd, localRequestedAt); }); const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn( @@ -693,6 +699,7 @@ export const make = Effect.gen(function* () { readonly policyCwds?: ReadonlyArray; /** Refs before a local read the caller just made, which a read of unmoved refs would repeat. */ readonly refsBeforeLocalRead?: string | null; + readonly localRequestedAt?: number; }, ) { return yield* withRemoteWriteLock( @@ -705,7 +712,11 @@ export const make = Effect.gen(function* () { : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]); if (pulled !== null) return pulled.remote; // Base refs and merge bases can move without changing divergence counts. - yield* refreshLocalStatusUnlessRefsUnchanged(cwd, options?.refsBeforeLocalRead ?? null); + yield* refreshLocalStatusUnlessRefsUnchanged( + cwd, + options?.refsBeforeLocalRead ?? null, + options?.localRequestedAt, + ); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), ); @@ -1058,12 +1069,12 @@ export const make = Effect.gen(function* () { }); const reconcileCheckedOutRef = Effect.fn("VcsStatusBroadcaster.reconcileCheckedOutRef")( - function* (cwd: string) { + function* (cwd: string, localRequestedAt: number) { if (!detailedSubscribers.has(cwd)) return; if ((yield* getCachedStatus(cwd))?.remote) { - yield* refreshRemoteStatus(cwd, { refreshUpstream: false }); + yield* refreshRemoteStatus(cwd, { refreshUpstream: false, localRequestedAt }); } else { - yield* refreshLocalStatusCore(cwd); + yield* refreshLocalStatusCore(cwd, localRequestedAt); } }, ); @@ -1097,12 +1108,16 @@ export const make = Effect.gen(function* () { : Effect.succeed(false), ), Stream.filter((event) => path.basename(event.path) === "HEAD"), + // Requested on arrival, so a checkout's own refresh that starts later also serves this move. + Stream.map(() => requestLocalRefresh(cwd)), // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh. Stream.buffer({ capacity: 1, strategy: "sliding" }), - Stream.mapEffect(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))), + Stream.tap(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))), // Detailed status waits behind its own reads; the branch keeps up on the stage above. Stream.buffer({ capacity: 1, strategy: "sliding" }), - Stream.runForEach(() => retryCheckedOutRef(cwd, reconcileCheckedOutRef(cwd))), + Stream.runForEach((requestedAt) => + retryCheckedOutRef(cwd, reconcileCheckedOutRef(cwd, requestedAt)), + ), ); });