Skip to content

Archiving a thread fetches the whole archived thread list twice: 2 identical snapshots per archive (about 1.9 KB per archived thread each) #40432

Open

Description

@juliusmarminge

What is slow

Archiving a thread from the sidebar makes the client fetch the full archived thread list (orchestration.getArchivedShellSnapshot) twice, about 100 ms apart, with identical answers. The response carries every archived thread's shell, about 1.9 KB each, so the duplicate grows with the archive. At 8-10 archived threads it is 16-20 KB and 40-90 ms of server work per copy. #32805 measured 6-18 s for one snapshot on large archives, and this doubles that per archive. The list is loaded whenever a thread page is open (the thread relationships control mounts it), so a user who archives from the sidebar always pays it. Remote clients pay it over the relay.

Measured

  • Windows Server 2025, 4 vCPU, 16 GB, Defender real-time scanning on, commit 7d3677f.
  • 113 replay threads in two projects, headless Chromium on a thread page. Each archive is right-click a sidebar row, then Archive.
  • 7 archives, counting the page's WebSocket requests with common.cjs reqs: every one sent orchestration.dispatchCommand 1, orchestration.getArchivedShellSnapshot 2, getOlderSettledThreads 1. The row disappeared in 201-535 ms (median 218 ms).
  • Request order (run 5):
+57  orchestration.dispatchCommand {"type":"thread.archive",...}
+99  orchestration.getArchivedShellSnapshot {}
+199 orchestration.getArchivedShellSnapshot {}
  • Response frames (arch2.cjs, 3 more archives): two identical snapshot responses per archive, 16,269 + 16,269 bytes, then 18,186 + 18,186, then 20,103 + 20,103. That is 1,917 bytes per archived thread, sent twice.
  • Server trace: every archive has two orchestration.getArchivedShellSnapshot spans, 12-88 ms each at 8-14 archived threads.

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) : '');
}

arch2.cjs (node arch2.cjs /ENVID/<thread id>; archives the 4th sidebar row 3 times and prints every received frame over 2 KB):

// archive 3 threads, log every received frame over 2 KB with its offset
const { open } = require('./common.cjs');
(async () => {
  const { browser, page } = await open(process.argv[2]);
  const recv = [];
  page.on('websocket', (ws) => ws.on('framereceived', (f) => { const s = String(f.payload); recv.push({ t: Date.now(), n: s.length, head: s.slice(0, 90) }); }));
  await page.locator('[data-thread-item]').first().waitFor({ timeout: 60000 });
  await page.waitForTimeout(8000);
  for (let i = 0; i < 3; i++) {
    const row = page.locator('[data-thread-item]').nth(3); const key = await row.getAttribute('data-thread-item');
    await row.click({ button: 'right' }); const item = page.getByRole('menuitem', { name: /^Archive/ }).first(); await item.waitFor();
    const t0 = Date.now(); await item.click();
    await page.locator(`[data-thread-item="${key}"]`).first().waitFor({ state: 'detached' }); await page.waitForTimeout(3000);
    for (const r of recv.filter((r) => r.t >= t0 && r.n > 2048)) console.log('run', i, '+' + (r.t - t0), r.n, r.head);
  }
  await browser.close();
})();

Each archive prints two frames of the same size that start with "value":{"schemaVersion":2,"snapshot.... Each pair is about 1.9 KB larger than the one before.

Where the time goes

  • apps/web/src/hooks/useThreadActions.ts, archiveThread (line 444): after the dispatch succeeds, it calls refreshArchivedThreadsForEnvironment(environmentId) (apps/web/src/lib/archivedThreadsState.ts), which runs appAtomRegistry.refresh on the snapshot atom. That is the first fetch, about 40 ms after dispatch.
  • packages/client-runtime/src/state/orchestration.ts, archivedShellSnapshot (line 240): its refreshTrigger watches the shell's removedAt, which changes when the shell reports the archived thread as removed (fix(client): refresh open archive when threads are archived elsewhere #36909 added it for archives made elsewhere). That is the second fetch, about 100 ms later.
  • The same explicit call follows unarchive (line 398) and the two delete paths (lines 506 and 638). Each of those also changes removedAt when it touches an archived or listed thread. Only archive was measured here.

Why it is avoidable

The shell event that the refreshTrigger follows already covers the archive this client made. The explicit refresh in the action fetches the same list once more about 100 ms earlier. One snapshot per archive gives the same final list.

What a fix has to show

The same archives from the sidebar, on Windows:


Found by the automated Windows performance sweep on 7d3677f.


Found by the automated Windows performance sweep on 7d3677f.

Activity

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