Skip to content

Every turn on a feature branch on Windows reads upstream divergence twice at turn end: 6 of 23 status git and ~310 ms repeated per turn #40430

Closed

Description

@juliusmarminge

What is slow

When a turn ends in a thread whose checkout is on a non-default branch with an upstream (every thread on a feature branch, and every worktree thread once it is pushed), RunFinalizationService.refresh updates git status. It reads the upstream divergence twice, about 300 ms apart. refreshLocalStatus runs statusDetailsRemote (6 git) so ahead/behind counts are published without waiting on the forge. refreshPullRequestStatus then calls remoteStatus, which runs the same 6 commands again before its 3-git pull request lookup. Every turn pays 6 extra git processes and about 300 ms of git on Windows. The next turn and any status read on the same checkout queue behind them.

Measured

  • Windows Server 2025, 4 vCPU, 16 GB, Defender real-time scanning on, Git 2.56.1.windows.1, commit 7d3677f.
  • A 32,168-file clone with a local bare remote, checked out on branch work with upstream origin/work. 113 replay threads seeded across two projects. No browser open during the turns.
  • 6 replay turns (thread send <id> go --wait) in one thread, with the server idle between turns: 40, 40, 40, 40, 41 and 49 git per turn (the 49 overlapped a settlement sweep). 39-40 are under RunFinalizationService.finalize: 16-17 checkpoint capture and 23 status refresh.
  • The status refresh, identical in all 6 runs (994 ms and 900 ms shown for two of them):
+0    RunFinalizationService.refresh 994ms git=23
  +0    VcsStatusBroadcaster.refreshLocalStatus 990ms git=12
          refreshLocalStatusCore -> localStatus               674ms git=6
  +676    GitWorkflowService.upstreamDivergence -> readStatusDetailsRemote 314ms git=6
            statusDetailsRemote.branch, readCurrentUpstreamRef, statusDetailsRemote.divergence,
            resolvePrimaryDefaultBranchName, computeAheadCountAgainstBase (stamp + rev-list)
  +994  VcsStatusBroadcaster.refreshPullRequestStatus 572ms git=11
          readRemoteStatus
  +995      GitWorkflowService.currentBranch               59ms git=1
  +1054     GitWorkflowService.remoteStatus -> readRemoteStatus 471ms git=9
  +1055       statusDetailsRemote -> readStatusDetailsRemote 318ms git=6   <- same 6 commands again
  +1373       lookupStatusPr                              152ms git=3
  +1525     GitWorkflowService.currentBranch               41ms git=1
  • With 4 turns finishing at once during seeding, the same refresh took 1.98 s + 1.31 s per turn, and the duplicated read took 713 ms.

How to measure it again

Harness (Windows, PowerShell; the next agent starts from a fresh machine)

  1. Check out the commit in C:/p/wt. Run vp i, then vp build in apps/web.
  2. Make two large repositories with a remote: git clone --bare --no-local <a t3code checkout> C:/p/repos/remote.git, then for p0 and p1: git clone C:/p/repos/remote.git C:/p/repos/pN, set user.name/user.email, git checkout -b work; git push -u origin work, and git branch feat-a HEAD~20; git push -u origin feat-a (same for feat-b, feat-c). Each has about 32,000 files.
  3. Before the first server start, write C:/p/home/userdata/settings.json: {"providerInstances":{"devReplay":{"displayName":"Replay (dev)","driver":"acpRegistry","config":{"source":"local","commandPath":"<output of node -p process.execPath>","commandArgs":["C:/p/wt/apps/server/scripts/dev-replay-agent.ts"]}}}}
  4. In apps/server, with T3CODE_DEV_SEED=0, run node src/bin.ts serve --base-dir C:/p/home --port 4800 --host 127.0.0.1 and keep it running (over SSH, start it with Invoke-CimMethod Win32_Process Create; it listens after about 50 s).
  5. node src/bin.ts project add C:/p/repos/p0 --base-dir C:/p/home (and p1).
  6. Seed threads: from inside the repository, node C:/p/wt/apps/server/src/bin.ts thread start --base-dir C:/p/home --provider devReplay --model command-output C:/p/repos/p0 go prints a thread id mcp:<uuid>. This run seeded 113 threads (73 in p0, 40 in p1). Wait until the server is idle before measuring. The page path is /ENVID/mcp:<uuid>; common.cjs fills in userdata/environment-id.
  7. Pair: node src/bin.ts pair --ttl 1h --base-dir C:/p/home prints a URL ending in pair#token=...; replace its host with 127.0.0.1:4800 and export it as PAIR. Export PW as the checkout's node_modules/.pnpm/playwright@*/node_modules/playwright directory.
  8. Delete C:/p/home/userdata/logs/server.trace.ndjson* before a run; afterwards copy them to a directory and run sum.cjs over it. Each git process is a runGitCommand or VcsProcess.spawn span.

common.cjs:

const fs = require('fs');
const { chromium } = require(process.env.PW);
const NL = String.fromCharCode(10);
exports.open = async (path) => {
  const browser = await chromium.launch();
  const page = await (await browser.newContext({ viewport: { width: 1600, height: 1000 } })).newPage();
  const sent = [];
  page.on('websocket', (ws) => ws.on('framesent', (f) => {
    try { for (const line of String(f.payload).split(NL)) { if (!line) continue; const j = JSON.parse(line); if (j._tag === 'Request') sent.push({ t: Date.now(), tag: j.tag, p: JSON.stringify(j.payload).slice(0, 160) }); } } catch {}
  }));
  await page.goto(process.env.PAIR);
  await page.waitForTimeout(4000);
  const env = fs.readFileSync('C:/p/home/userdata/environment-id', 'utf8').trim();
  await page.goto('http://127.0.0.1:4800' + path.replace('ENVID', env));
  return { browser, page, sent };
};
exports.record = (tag, rec) => { fs.mkdirSync('C:/p/perf/out', { recursive: true }); fs.appendFileSync('C:/p/perf/out/' + tag + '.jsonl', JSON.stringify(rec) + NL); };
exports.reqs = (sent, a, b) => { const c = {}; for (const s of sent) if (s.t >= a && s.t <= b) c[s.tag] = (c[s.tag] || 0) + 1; return c; };
exports.seq = (sent, a, b) => sent.filter((s) => s.t >= a && s.t <= b && s.tag !== 'server.reportClientActivity').map((s) => '+' + (s.t - a) + ' ' + s.tag + ' ' + s.p);

sum.cjs (node sum.cjs <traceDir> <out.jsonl>; CALLERS=1 lists the calling span):

const fs = require('fs'); const path = require('path');
const NL = String.fromCharCode(10);
const [dir, outFile, sf = 'start', ef = 'end'] = process.argv.slice(2);
const spans = [];
for (const f of fs.readdirSync(dir)) for (const l of fs.readFileSync(path.join(dir, f), 'utf8').split(NL)) { if (!l) continue; try { spans.push(JSON.parse(l)); } catch {} }
const byId = new Map(spans.map((s) => [s.spanId, s]));
const ms = (s) => Number(BigInt(s.startTimeUnixNano) / 1000000n);
const plumbing = ['VcsProcess', 'runGitCommand', 'GitVcsDriver.execute', 'GitVcsDriver.run', 'GitVcsDriver.gitCommand', 'gitCommand', 'ProcessRunner'];
const root = (s) => { while (s.parentSpanId && byId.has(s.parentSpanId)) s = byId.get(s.parentSpanId); return s; };
const caller = (s) => { let p = s; while (p.parentSpanId && byId.has(p.parentSpanId)) { p = byId.get(p.parentSpanId); if (!plumbing.some((x) => p.name.startsWith(x))) return p.name; } return '?'; };
const spawns = spans.filter((s) => s.name === 'VcsProcess.spawn' || s.name === 'runGitCommand');
for (const l of fs.readFileSync(outFile, 'utf8').split(NL)) {
  if (!l) continue; const r = JSON.parse(l); const a = r[sf], b = r[ef];
  const roots = new Map();
  for (const sp of spawns) { const t = ms(sp); if (t < a || t > b) continue; const rt = root(sp); const e = roots.get(rt.name) || { n: 0, ms: new Set(), callers: {} }; e.n++; e.ms.add(Math.round(rt.durationMs)); const c = caller(sp); e.callers[c] = (e.callers[c] || 0) + 1; roots.set(rt.name, e); }
  let total = 0; for (const e of roots.values()) total += e.n;
  console.log('run', r.run, r.target || '', 'total git=' + total);
  for (const [k, e] of roots) console.log('   ', k, 'git=' + e.n, 'ms=' + [...e.ms].join(','), process.env.CALLERS ? JSON.stringify(e.callers) : '');
}

turns.ps1 (powershell -File turns.ps1 mcp:<uuid> 6, run from a clean trace; writes the run windows to C:/p/perf/out/turn.jsonl):

param([string]$id, [int]$n = 6)
Set-Location C:\p\repos\p0
for ($i = 0; $i -lt $n; $i++) {
  $t0 = [DateTimeOffset]::Now.ToUnixTimeMilliseconds()
  node C:\p\wt\apps\server\src\bin.ts thread send --base-dir C:/p/home $id go --wait 2>&1 | Out-Null
  Start-Sleep 12
  $t1 = [DateTimeOffset]::Now.ToUnixTimeMilliseconds()
  New-Item -ItemType Directory -Force C:\p\perf\out | Out-Null
  "{""run"":$i,""start"":$t0,""end"":$t1}" | Add-Content C:\p\perf\out\turn.jsonl
}

Then node sum.cjs <traces> C:/p/perf/out/turn.jsonl for git per turn, and DEPTH=7 node tree.cjs RunFinalizationService.refresh <trace files> for the tree above (N= picks the k-th turn).

tree.cjs:

// node tree.cjs <rootName> <files...>: prints the first matching root's span tree with git counts
const fs = require('fs'); const NL = String.fromCharCode(10);
const [rootName, ...files] = process.argv.slice(2);
const spans = []; for (const f of files) for (const l of fs.readFileSync(f, 'utf8').split(NL)) { if (!l) continue; try { spans.push(JSON.parse(l)); } catch {} }
const kids = new Map(); for (const s of spans) { if (!kids.has(s.parentSpanId)) kids.set(s.parentSpanId, []); kids.get(s.parentSpanId).push(s); }
const ms = (s) => Number(BigInt(s.startTimeUnixNano) / 1000000n);
const isGit = (s) => s.name === 'runGitCommand' || s.name === 'VcsProcess.spawn';
const gitUnder = (s) => (kids.get(s.spanId) || []).reduce((a, k) => a + (isGit(k) ? 1 : 0) + gitUnder(k), 0);
const plumb = /^(VcsProcess|runGitCommand|processRunner|GitVcsDriver\.gitCommand|sqlite|sql\.|BEGIN|COMMIT|SAVEPOINT|RELEASE)/;
const pick = spans.filter((s) => s.name === rootName && gitUnder(s) > 0)[+(process.env.N || 0)];
if (!pick) { console.log('none'); process.exit(); }
const t0 = ms(pick);
const walk = (s, d) => { const g = gitUnder(s); if (d > +(process.env.DEPTH || 6)) return; if (!plumb.test(s.name) || d === 0) console.log(' '.repeat(d * 2) + '+' + (ms(s) - t0) + ' ' + s.name + ' ' + Math.round(s.durationMs) + 'ms git=' + g); for (const k of (kids.get(s.spanId) || []).sort((a, b) => ms(a) - ms(b))) if (gitUnder(k) > 0 || isGit(k)) { if (!plumb.test(k.name)) walk(k, d + 1); } };
walk(pick, 0);

Where the time goes

  • apps/server/src/orchestration-v2/RunFinalizationService.ts, refresh (line 179): calls vcsStatus.refreshLocalStatus(cwd), then, for a non-default branch, vcsStatus.refreshPullRequestStatus(cwd).
  • apps/server/src/vcs/VcsStatusBroadcaster.ts, refreshLocalStatus (line 555): when the cached remote has an upstream, it calls workflow.upstreamDivergence(cwd), which is statusDetailsRemote (6 git). It publishes ahead/behind from that.
  • VcsStatusBroadcaster.refreshPullRequestStatus (line 771) → readRemoteStatus (line 585) → workflow.remoteStatus. It runs statusDetailsRemote again (6 git) with refreshUpstream: false, so no fetch happens between the two reads. Both see the same refs.

Why it is avoidable

Both reads run back to back on the same checkout with no fetch between them and return the same branch, upstream, divergence, default branch and ahead count. The pull request lookup needs only the branch and upstream the first read already has. The early read exists so the forge lookup does not delay ahead/behind (the comment above it). Running the local half twice is not needed for that.

What a fix has to show

The same 6 replay turns on a branch with an upstream, on Windows:

  • Expected: RunFinalizationService.refresh runs 17 git instead of 23 (at most one statusDetailsRemote per turn end), so 33-34 git per turn instead of 39-40, and about 300 ms less git per turn on this machine.
  • What stays: the local status read (6), one divergence read (6), the pull request lookup (3) and readRemoteStatus's two currentBranch reads (2), which guard against a branch switch during the forge lookup. The checkpoint capture (16-17) is out of scope.
  • Not regressed: ahead/behind still reach the client before the pull request lookup finishes. A branch switched during the lookup still publishes the new branch's status.

Found by the automated Windows performance sweep on 7d3677f.


Found by the automated Windows performance sweep on 7d3677f.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions