Files
orca/src/main/git/wsl-git-read-environment.ts
T
Neil 96565fe370 perf(source-control): stop re-running every git read on each file selection (#15036) (#16600)
* perf(source-control): stop blocking main on four sync git-dir probes per status poll

detectConflictOperation ran four existsSync calls against the git dir on every
status poll. On a `\\wsl.localhost\...` worktree each one is a 9p round trip, and
being synchronous they landed on the Electron main thread back to back.

Replace them with concurrent fs/promises access probes: same "any failure reads
as absent" semantics existsSync had, one wave instead of four serialized blocking
calls. The outer try/catch went with them -- neither resolveGitDir nor the probes
can throw now, so it was unreachable.

Part of #15036 (source-control latency).

* perf(wsl): let git reads take the shell-free route from a cwd-derived distro

shouldAttemptWslDirectGit required options.wslDistro, so a `\\wsl.localhost\...`
worktree without a resolved WSL project runtime never qualified -- even though the
distro is right there in the cwd and wslDistroForCommand already knew how to read
it. Every `git show` behind a diff therefore ran through the user's login shell,
executing their rc once per blob read.

Three changes:

- Derive the distro from the cwd when no override was supplied. This is the fix;
  the routing decision now depends on where the repo actually lives.
- Wait, bounded, for a cold read-environment probe instead of resolving without it.
  The probe is one wsl.exe call shared per distro, so the wait is paid at most once,
  and past WSL_GIT_READ_ENVIRONMENT_WAIT_MS the shell route runs exactly as before.
  It returns null rather than a settled promise when there is nothing to wait for,
  so a non-WSL git call is not pushed into a later microtask.
- Opt the blob reads into preferWslDirectGit via gitReadOptionsForWorktree (renamed
  from gitStatusReadOptionsForWorktree; it was never status-specific). Belt-and-
  braces only: `show`, `config --get-regexp`, `ls-files` and `rev-parse` were all
  already matched by isWslDirectGitReadCommand, so this changes no routing today --
  it just stops the diff path depending on a heuristic it knows the answer to.

git-blob-read also gains a `failed` flag distinguishing "git ran and reported the
path absent" (exit 128) from "the read never got an answer"; nothing consumes it
yet, the settled diff cache does.

Part of #15036 (source-control latency).

* perf(source-control): give diff reads a settled cache keyed on stamped git state

gitDiffReadDedupe coalesces only while a read is in flight, so every file
selection re-ran the whole read: a `git config --file .gitmodules` spawn, one or
two `git show` spawns, and a working-tree stat+read. On a WSL/UNC worktree each
git spawn is a wsl.exe invocation, which is the ">3s Loading diff..." in #15036.

Correctness first -- a stale diff is worse than a slow one. The cache never
expires on a clock and there is no TTL to tune. Instead:

- worktree-diff-stamp.ts takes a subprocess-free stamp of exactly the inputs a
  file diff is built from: HEAD (by resolved tip *content*, so a commit is
  visible even though HEAD's own bytes never move), `.git/index` (mtime+size),
  `.gitmodules` (submodule routing), and the working-tree file. A linked
  worktree's commondir and the packed-refs/reftable fallback are handled; an
  unborn branch is caught by recording "no loose ref" rather than only the
  packed stamps.
- The stamp is captured BEFORE the read and stored with the result. Anything
  that moves during or after the read leaves the stored stamp behind, so the
  next lookup misses. That, not a freshness window, is why a stale diff cannot
  be served.
- A store is refused unless the stamp was taken a full mtime bucket (2s, FAT's
  granularity) after its newest component. Below that, a second write inside the
  same bucket would be invisible -- git's own racy-index rule.
- `null` stamp means "cannot prove" and never caches: a folder workspace, a repo
  whose layout cannot be read, or a filesystem reporting no usable mtime.
- Submodule routes and reads that failed rather than proved absence are not
  reusable. A wsl.exe hiccup produces the same empty left side a new file does,
  and pinning that would persist a wrong diff.
- invalidateGitReadCaches clears it and bumps a generation, so a read that
  started pre-mutation cannot store its result post-mutation.

`ino` is deliberately optional in the working-tree component: Windows reports 0
for it on the redirector behind `\\wsl.localhost`, and requiring an unstable 0 to
match would make the cache silently never hit on the exact host it exists for.
Cache counters are exposed for the same reason -- a miss storm and a cold start
otherwise look identical.

Also drops gitDiffReadDedupe.clear() from getStatus. A status poll is a read; all
it did was destroy a live coalescing entry so a concurrent identical request
started duplicate git work. Mutations still invalidate through the shared point.

Memory is bounded by retained characters, not entry count -- one diff result can
legitimately hold megabytes.

Fixes the source-control half of #15036.

* perf(source-control): reuse BoundedMap and stop the WSL probe wait from outliving its answer

Review follow-ups on the settled-diff-cache work:

- SettledDiffCache now sits on the shared BoundedMap instead of hand-rolling the
  same Map + character ledger + evict-oldest loop.
- pendingWslDirectGitReadEnvironment returns null once the probe has settled
  either way, so a distro whose direct route was disabled no longer pays for a
  1.5s timer and two microtask hops on every git read.
- That wait now honours the read's abort signal and goes through withTimeout, so
  an aborted read is not held for the full bound and a probe rejection can never
  surface as a read failure.
- The settled-cache generation fence is taken before the stamp read, so a
  mutation that lands entirely inside the stamp's stats can no longer store an
  entry whose stamp is torn across it.
- The cache counters are folded into the main-thread churn probe report, which is
  what tells a permanently-cold cache apart from a cold start in the field.

* fix(source-control): tell WSL clock skew apart from a genuinely fresh write

The racy-write margin compares two clocks: capturedAtMs is this host's, while
the component mtimes come from whatever wrote the files. On a \\wsl.localhost
worktree the guest sets them, so a guest running ahead pushes every
recently-touched file past the margin and the cache refuses to store — for as
long as the skew lasts, on exactly the platform this cache exists for.

Nothing was wrong with the refusal; it was invisible. racyWrites alone cannot
distinguish "the repo was just edited" from "the clocks disagree and this will
never resolve on its own", so a permanently cold cache looked like a cold start.

isDiffStampClockSkewed flags the one thing no local write can produce — an mtime
in this host's future — and the cache counts those separately as
clockSkewedWrites. A nonzero count is the signal that the cache is off for a
reason idling will not fix.

Found by review of #16600; behavior is unchanged, only observability.
2026-08-26 15:44:11 -07:00

153 lines
5.4 KiB
TypeScript

import { execFile } from 'node:child_process'
import {
buildWslCapturedLoginShellCommand,
buildWslExecArgs
} from '../../shared/wsl-login-shell-command'
export type WslGitReadEnvironment = { gitPath: string; home: string; path: string }
const PROBE_TIMEOUT_MS = 10_000
/**
* How long a read may wait for a cold probe before taking the login shell.
* Short enough that a wedged distro cannot stall the panel, long enough that a
* healthy one resolves and every later read runs shell-free.
*/
export const WSL_GIT_READ_ENVIRONMENT_WAIT_MS = 1_500
const PROBE_MAX_BUFFER = 64 * 1024
const TRANSIENT_PROBE_RETRY_MS = 30_000
const environmentByDistro = new Map<string, Promise<WslGitReadEnvironment | null>>()
// Why the null entries matter: a settled "no direct route" answer is what lets a read skip the
// bounded probe wait entirely instead of racing an already-decided promise on every call.
const settledEnvironmentByDistro = new Map<string, WslGitReadEnvironment | null>()
const transientRetryAfterByDistro = new Map<string, number>()
type ProbeOutcome =
| { kind: 'resolved'; environment: WslGitReadEnvironment }
| { kind: 'rejected' }
| { kind: 'transient' }
function parseProbe(payload: string | null): WslGitReadEnvironment | null {
if (payload === null) {
return null
}
const fields = payload.split('\0')
const path = fields[0] ?? ''
const gitPath = fields[1] ?? ''
const home = fields[2] ?? ''
if (
!path.includes('/') ||
path.length > 32_768 ||
!gitPath.startsWith('/') ||
gitPath.includes('\n') ||
gitPath.includes('\r') ||
!home.startsWith('/') ||
home.includes('\n') ||
home.includes('\r')
) {
return null
}
return { gitPath, home, path }
}
function probeWslGitReadEnvironment(distro: string): Promise<ProbeOutcome> {
const probeCommand = [
'_orca_git_path=$(command -v git 2>/dev/null || true)',
'case "$_orca_git_path" in /*) [ -x "$_orca_git_path" ] || exit 127 ;; *) exit 127 ;; esac',
'if [ -n "${XDG_CONFIG_HOME:-}" ] || [ -n "${LD_LIBRARY_PATH:-}" ] || env | grep -q \'^GIT_\'; then exit 78; fi',
`printf '%s\\0%s\\0%s' "$PATH" "$_orca_git_path" "$HOME"`
].join('\n')
const captured = buildWslCapturedLoginShellCommand(probeCommand)
return new Promise((resolve) => {
execFile(
'wsl.exe',
buildWslExecArgs(distro, ['sh', '-lc', captured.command]),
{
encoding: 'utf8',
maxBuffer: PROBE_MAX_BUFFER,
timeout: PROBE_TIMEOUT_MS,
windowsHide: true
},
(error, stdout) => {
if (error) {
const code = (error as { code?: unknown }).code
resolve(code === 78 || code === 127 ? { kind: 'rejected' } : { kind: 'transient' })
return
}
const environment = parseProbe(captured.readStdout(String(stdout)))
resolve(environment ? { kind: 'resolved', environment } : { kind: 'rejected' })
}
)
})
}
export function getWslGitReadEnvironment(distro: string): Promise<WslGitReadEnvironment | null> {
const retryAfter = transientRetryAfterByDistro.get(distro)
if (retryAfter !== undefined && Date.now() >= retryAfter) {
environmentByDistro.delete(distro)
settledEnvironmentByDistro.delete(distro)
transientRetryAfterByDistro.delete(distro)
}
let environment = environmentByDistro.get(distro)
if (!environment) {
environment = probeWslGitReadEnvironment(distro).then((outcome) => {
if (environmentByDistro.get(distro) !== environment) {
return outcome.kind === 'resolved' ? outcome.environment : null
}
if (outcome.kind === 'resolved') {
settledEnvironmentByDistro.set(distro, outcome.environment)
transientRetryAfterByDistro.delete(distro)
return outcome.environment
}
settledEnvironmentByDistro.set(distro, null)
if (outcome.kind === 'transient') {
transientRetryAfterByDistro.set(distro, Date.now() + TRANSIENT_PROBE_RETRY_MS)
}
return null
})
environmentByDistro.set(distro, environment)
}
return environment
}
/**
* What the shared probe settled to: the environment, `null` for a distro with no
* usable direct route, `undefined` while nothing has been decided yet.
*/
export function peekWslGitReadEnvironment(
distro: string
): WslGitReadEnvironment | null | undefined {
return settledEnvironmentByDistro.get(distro)
}
/** True once the probe has decided either way, so a read has nothing left to wait for. */
export function isWslGitReadEnvironmentSettled(distro: string): boolean {
return settledEnvironmentByDistro.has(distro)
}
export function invalidateWslGitReadEnvironment(distro: string): void {
environmentByDistro.delete(distro)
settledEnvironmentByDistro.delete(distro)
transientRetryAfterByDistro.delete(distro)
}
export function disableWslGitReadEnvironment(distro: string): void {
environmentByDistro.set(distro, Promise.resolve(null))
settledEnvironmentByDistro.set(distro, null)
transientRetryAfterByDistro.delete(distro)
}
export function resetWslGitReadEnvironmentForTests(): void {
environmentByDistro.clear()
settledEnvironmentByDistro.clear()
transientRetryAfterByDistro.clear()
}
export function seedWslGitReadEnvironmentForTests(
distro: string,
environment: WslGitReadEnvironment
): void {
environmentByDistro.set(distro, Promise.resolve(environment))
settledEnvironmentByDistro.set(distro, environment)
transientRetryAfterByDistro.delete(distro)
}