diff --git a/src/relay/git-handler-status-ops.test.ts b/src/relay/git-handler-status-ops.test.ts index 47ddb8a67..d55e86d75 100644 --- a/src/relay/git-handler-status-ops.test.ts +++ b/src/relay/git-handler-status-ops.test.ts @@ -5,6 +5,7 @@ import * as path from 'path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { GitExec } from './git-handler-ops' import { getStatusOp } from './git-handler-status-ops' +import { clearNoEffectiveUpstreamStatusCache } from './git-status-upstream-negative-cache' const LARGE_STATUS_ENTRY_COUNT = 150_000 @@ -16,14 +17,20 @@ function buildLargeStatusOutput(count: number): string { return lines.join('\n') } +function buildBranchStatusOutput(head: string, branch: string): string { + return [`# branch.oid ${head}`, `# branch.head ${branch}`].join('\n') +} + describe('getStatusOp', () => { let tmpDir: string beforeEach(() => { + clearNoEffectiveUpstreamStatusCache() tmpDir = mkdtempSync(path.join(tmpdir(), 'relay-git-status-')) }) afterEach(async () => { + clearNoEffectiveUpstreamStatusCache() await fs.rm(tmpDir, { recursive: true, force: true }) }) @@ -70,4 +77,142 @@ describe('getStatusOp', () => { expect(result.didHitLimit).toBeUndefined() expect(result.entries).toHaveLength(5) }) + + it('caches no-effective-upstream probes across status polls for the same head', async () => { + const git = vi.fn(async (args) => { + if (args.includes('status')) { + return { stdout: buildBranchStatusOutput('abc123', 'feature'), stderr: '' } + } + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + throw new Error('fatal: no upstream configured for branch feature') + } + throw new Error(`No upstream fixture for git ${args.join(' ')}`) + }) + + const first = await getStatusOp(git, { worktreePath: tmpDir }) + const firstCallCount = git.mock.calls.length + const second = await getStatusOp(git, { worktreePath: tmpDir }) + + expect(first.upstreamStatus).toEqual({ hasUpstream: false, ahead: 0, behind: 0 }) + expect(second.upstreamStatus).toEqual(first.upstreamStatus) + expect(git.mock.calls).toHaveLength(firstCallCount + 1) + expect( + git.mock.calls.filter(([args]) => args[0] === 'rev-parse' && args.includes('HEAD@{u}')) + ).toHaveLength(1) + expect( + git.mock.calls.filter( + ([args]) => args[0] === 'rev-parse' && args.includes('refs/remotes/origin/feature') + ) + ).toHaveLength(1) + }) + + it('coalesces concurrent no-effective-upstream probes', async () => { + const git = vi.fn(async (args) => { + if (args.includes('status')) { + return { stdout: buildBranchStatusOutput('abc123', 'feature'), stderr: '' } + } + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + await Promise.resolve() + throw new Error('fatal: no upstream configured for branch feature') + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/feature')) { + await Promise.resolve() + throw new Error('missing remote branch') + } + throw new Error(`No upstream fixture for git ${args.join(' ')}`) + }) + + await Promise.all([ + getStatusOp(git, { worktreePath: tmpDir }), + getStatusOp(git, { worktreePath: tmpDir }), + getStatusOp(git, { worktreePath: tmpDir }) + ]) + + expect( + git.mock.calls.filter(([args]) => args[0] === 'rev-parse' && args.includes('HEAD@{u}')) + ).toHaveLength(1) + expect( + git.mock.calls.filter( + ([args]) => args[0] === 'rev-parse' && args.includes('refs/remotes/origin/feature') + ) + ).toHaveLength(1) + }) + + it('invalidates cached no-effective-upstream probes when the branch changes', async () => { + let branch = 'feature' + const git = vi.fn(async (args) => { + if (args.includes('status')) { + return { stdout: buildBranchStatusOutput('abc123', branch), stderr: '' } + } + if (args[0] === 'symbolic-ref') { + return { stdout: `${branch}\n`, stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + throw new Error(`fatal: no upstream configured for branch ${branch}`) + } + if (args[0] === 'rev-parse' && args.some((arg) => arg.startsWith('refs/remotes/origin/'))) { + throw new Error('missing remote branch') + } + throw new Error(`No upstream fixture for git ${args.join(' ')}`) + }) + + await getStatusOp(git, { worktreePath: tmpDir }) + branch = 'other-feature' + await getStatusOp(git, { worktreePath: tmpDir }) + + expect( + git.mock.calls + .filter( + ([args]) => + args[0] === 'rev-parse' && args.some((arg) => arg.startsWith('refs/remotes/origin/')) + ) + .map(([args]) => args.at(-1)) + ).toEqual(['refs/remotes/origin/feature', 'refs/remotes/origin/other-feature']) + }) + + it('does not cache a configured push target signal', async () => { + const git = vi.fn(async (args) => { + if (args.includes('status')) { + return { stdout: buildBranchStatusOutput('abc123', 'feature/fix'), stderr: '' } + } + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature/fix\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + throw new Error('fatal: no upstream configured for branch feature/fix') + } + if (args[0] === 'config' && args.includes('branch.feature/fix.pushRemote')) { + return { stdout: 'fork\n', stderr: '' } + } + if (args[0] === 'config' && args.includes('remote.pushDefault')) { + throw new Error('missing push default') + } + if (args[0] === 'config' && args.includes('branch.feature/fix.remote')) { + return { stdout: 'fork\n', stderr: '' } + } + if (args[0] === 'config' && args.includes('branch.feature/fix.merge')) { + return { stdout: 'refs/heads/feature/fix\n', stderr: '' } + } + if (args[0] === 'config' && args.includes('branch.feature/fix.base')) { + throw new Error('missing branch base') + } + if (args[0] === 'rev-parse' && args.some((arg) => arg.startsWith('refs/remotes/'))) { + throw new Error('missing remote branch') + } + throw new Error(`No upstream fixture for git ${args.join(' ')}`) + }) + + await getStatusOp(git, { worktreePath: tmpDir }) + await getStatusOp(git, { worktreePath: tmpDir }) + + expect( + git.mock.calls.filter(([args]) => args[0] === 'rev-parse' && args.includes('HEAD@{u}')) + ).toHaveLength(2) + }) }) diff --git a/src/relay/git-handler-status-ops.ts b/src/relay/git-handler-status-ops.ts index d0c8842f5..8619e6fd1 100644 --- a/src/relay/git-handler-status-ops.ts +++ b/src/relay/git-handler-status-ops.ts @@ -11,10 +11,8 @@ import { parseUnmergedEntry } from './git-handler-utils' import { parseStatusOutput } from './git-status-output-parser' import type { GitExec } from './git-handler-ops' import type { GitUpstreamStatus } from '../shared/types' -import { - getEffectiveGitUpstreamStatus, - splitRemoteBranchName -} from '../shared/git-effective-upstream' +import { splitRemoteBranchName } from '../shared/git-effective-upstream' +import { readOrProbeNoEffectiveUpstreamStatus } from './git-status-upstream-negative-cache' import { applyLineStats, collectUntrackedAdditions, @@ -133,11 +131,17 @@ export async function getStatusOp( if (!didHitLimit) { if (shouldProbeEffectiveUpstreamStatus(branch, upstreamStatus?.upstreamName)) { - try { - upstreamStatus = await getEffectiveGitUpstreamStatus((args) => git(args, worktreePath)) - } catch { - // Why: status polling should keep returning working-tree entries even - // if the richer upstream probe hits a transient SSH/git ref error. + const branchName = getShortBranchName(branch) + if (branchName) { + try { + upstreamStatus = await readOrProbeNoEffectiveUpstreamStatus( + { worktreePath, branchName, upstreamName: upstreamStatus?.upstreamName }, + (args) => git(args, worktreePath) + ) + } catch { + // Why: status polling should keep returning working-tree entries even + // if the richer upstream probe hits a transient SSH/git ref error. + } } } diff --git a/src/relay/git-status-upstream-negative-cache.ts b/src/relay/git-status-upstream-negative-cache.ts new file mode 100644 index 000000000..ec1764891 --- /dev/null +++ b/src/relay/git-status-upstream-negative-cache.ts @@ -0,0 +1,101 @@ +import { getEffectiveGitUpstreamStatus } from '../shared/git-effective-upstream' +import type { GitCommandRunner } from '../shared/git-effective-upstream' +import type { GitUpstreamStatus } from '../shared/types' + +const NO_EFFECTIVE_UPSTREAM_CACHE_TTL_MS = 30_000 + +type NoEffectiveUpstreamCacheIdentity = { + worktreePath: string + branchName: string + upstreamName?: string +} + +type NoEffectiveUpstreamCacheEntry = { + status: GitUpstreamStatus + expiresAt: number +} + +const noEffectiveUpstreamByIdentity = new Map() +const noEffectiveUpstreamInFlight = new Map>() + +function noEffectiveUpstreamCacheKey(identity: NoEffectiveUpstreamCacheIdentity): string { + return [identity.worktreePath, identity.branchName, identity.upstreamName ?? ''].join('\0') +} + +function readCachedNoEffectiveUpstreamStatus( + cacheKey: string, + nowMs = Date.now() +): GitUpstreamStatus | null { + const entry = noEffectiveUpstreamByIdentity.get(cacheKey) + if (!entry) { + return null + } + if (entry.expiresAt <= nowMs) { + noEffectiveUpstreamByIdentity.delete(cacheKey) + return null + } + return entry.status +} + +function cacheNoEffectiveUpstreamStatus( + cacheKey: string, + status: GitUpstreamStatus, + probedSameNameOriginRef: boolean, + nowMs = Date.now() +): void { + // Why: hasConfiguredPushTarget controls publish behavior; keep that signal + // fresh rather than serving a stale positive from status polling. + if (status.hasUpstream || status.hasConfiguredPushTarget) { + noEffectiveUpstreamByIdentity.delete(cacheKey) + return + } + // Why: only cache negatives after probing origin/; other resolution + // paths can fail without proving the same-name publish branch is absent. + if (!probedSameNameOriginRef) { + return + } + noEffectiveUpstreamByIdentity.set(cacheKey, { + status, + expiresAt: nowMs + NO_EFFECTIVE_UPSTREAM_CACHE_TTL_MS + }) +} + +export async function readOrProbeNoEffectiveUpstreamStatus( + identity: NoEffectiveUpstreamCacheIdentity, + runGit: GitCommandRunner +): Promise { + const cacheKey = noEffectiveUpstreamCacheKey(identity) + const cachedStatus = readCachedNoEffectiveUpstreamStatus(cacheKey) + if (cachedStatus) { + return cachedStatus + } + + const inFlight = noEffectiveUpstreamInFlight.get(cacheKey) + if (inFlight) { + return inFlight + } + + let probedSameNameOriginRef = false + const probe = getEffectiveGitUpstreamStatus((args) => { + if (args[0] === 'rev-parse' && args.includes(`refs/remotes/origin/${identity.branchName}`)) { + probedSameNameOriginRef = true + } + return runGit(args) + }).then((status) => { + cacheNoEffectiveUpstreamStatus(cacheKey, status, probedSameNameOriginRef) + return status + }) + noEffectiveUpstreamInFlight.set(cacheKey, probe) + try { + return await probe + } finally { + if (noEffectiveUpstreamInFlight.get(cacheKey) === probe) { + noEffectiveUpstreamInFlight.delete(cacheKey) + } + } +} + +export function clearNoEffectiveUpstreamStatusCache(): void { + noEffectiveUpstreamByIdentity.clear() + noEffectiveUpstreamInFlight.clear() +}