Skip to content

perf(git): cache the status listing and share one scan between requests - #1322

Closed
brynne8 wants to merge 1 commit into
agegr:mainfrom
brynne8:perf/git-status-cache
Closed

brynne8 wants to merge 1 commit into
agegr:mainfrom
brynne8:perf/git-status-cache

Conversation

@brynne8

@brynne8 brynne8 commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

What it does

GET /api/git/status runs a full working-tree scan on every request (getGitStatus() in lib/git-changes.ts, which reads every untracked file one by one to count its lines). Nothing was shared between a sidebar reload and the next, or between two tabs on the same project — and the sidebar refetches the listing on every reload trigger, at most once a second while a run's tools finish.

This puts a short per-cwd cache in front of that scan, following lib/models-cache.ts exactly:

  • lib/git-status-cache.ts: a 2 s per-cwd TTL, plus an in-flight scan shared by concurrent requests for the same cwd.
  • An expired entry is dropped before the request scans, never served: the changed-file badges are what the focus reload (File list hot refresh #1144) exists to refresh, so a listing older than the TTL is not an answer.
  • The key is the cwd exactly as the caller spells it (the answer's paths are rebased onto it), so two spellings are two entries and one project is never served another's.
  • The route's allow-list checks still run per request, so a revoked root is never served from an entry.
  • An upload invalidates eagerly (/api/files ?type=upload), so the explorer's refetch after one is not the listing cached before the write.

The response shape is unchanged, and the first request still scans.

Why it matters

A sidebar reload, a second tab, and the periodic tool-end refetch all hit the same project within a couple of seconds. On a repository with a few hundred untracked files the scan is the dominant cost of the route, and it was paid in full every time — in parallel, per request. Caching the listing collapses a burst to one scan.

Measurements

Measured by timing the scan directly, because the route handler is a thin NextResponse.json(await …) wrapper around it and the allow-list checks are unchanged. A synthetic repository is built once, then both forms are timed in the same process against it:

  • origin/main route = getGitStatus(cwd) on every request (no cache)
  • this branch route = loadGitStatusWithCache(cwd, () => getGitStatus(cwd))

Repo shape: 300 tracked files, 100 of them modified, 400 untracked files of 300 lines each.

Reproduction (run from the repo root):

// gsc-bench.mjs
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createJiti } from "jiti";

const repo = process.cwd();
const jiti = createJiti(import.meta.url, { alias: { "@": repo }, interopDefault: true, moduleCache: false });
const { getGitStatus } = await jiti.import(path.join(repo, "lib/git-changes.ts"));
const { loadGitStatusWithCache, invalidateGitStatusCache } = await jiti.import(path.join(repo, "lib/git-status-cache.ts"));

const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "gsc-bench-")));
execFileSync("git", ["-C", root, "init", "--quiet"]);
execFileSync("git", ["-C", root, "config", "user.email", "[email protected]"]);
execFileSync("git", ["-C", root, "config", "user.name", "Bench"]);
const body = (n) => Array.from({ length: 300 }, (_, i) => `line ${i} of file ${n}`).join("\n") + "\n";
for (let i = 0; i < 300; i += 1) fs.writeFileSync(path.join(root, `tracked-${i}.txt`), body(i));
execFileSync("git", ["-C", root, "add", "."]);
execFileSync("git", ["-C", root, "commit", "--quiet", "-m", "fixture"]);
for (let i = 0; i < 100; i += 1) fs.writeFileSync(path.join(root, `tracked-${i}.txt`), body(i) + "changed\n");
for (let i = 0; i < 400; i += 1) fs.writeFileSync(path.join(root, `untracked-${i}.txt`), body(i));

const now = () => Number(process.hrtime.bigint()) / 1e6;
await getGitStatus(root); // warm page cache
const base5 = [];
for (let i = 0; i < 5; i += 1) { const t = now(); await getGitStatus(root); base5.push((now() - t).toFixed(1)); }
invalidateGitStatusCache();
const branch5 = [];
for (let i = 0; i < 5; i += 1) { const t = now(); await loadGitStatusWithCache(root, () => getGitStatus(root)); branch5.push((now() - t).toFixed(1)); }
const tb = now(); await Promise.all(Array.from({ length: 8 }, () => getGitStatus(root))); const baseConc = (now() - tb).toFixed(1);
invalidateGitStatusCache();
const tc = now(); await Promise.all(Array.from({ length: 8 }, () => loadGitStatusWithCache(root, () => getGitStatus(root)))); const branchConc = (now() - tc).toFixed(1);
console.log(`main  5 sequential: ${base5.join(", ")} ms`);
console.log(`branch 5 sequential: ${branch5.join(", ")} ms`);
console.log(`main  8 concurrent: ${baseConc} ms`);
console.log(`branch 8 concurrent: ${branchConc} ms`);
fs.rmSync(root, { recursive: true, force: true });
process.exit(0);
$ bun gsc-bench.mjs
main   5 sequential requests: 137.2, 96.2, 162.1, 100.7, 123.5 ms  (median 123.5 ms)
branch 5 sequential requests: 118.6,  0.0,   0.0,   0.0,   0.0 ms  (median 0.0 ms)
main   8 concurrent requests: 659.7 ms
branch 8 concurrent requests: 115.0 ms

A warm request inside the TTL is a cache hit (~0 ms); eight concurrent requests for one cwd collapse from ~660 ms to one real scan (~115 ms), a ~5.7× reduction. The first request of a burst still pays the full scan; the win is everything behind it.

Scope

One change split out of a Bun-running fork (brynne8/pi-web-bun) into a single-purpose branch on today's main; one feature per PR. The fork's file-row "Revert" and its lib/git-revert.ts are not part of this change and are not present upstream, so the revert invalidation was dropped; only the upload invalidation is ported.

Testing

$ export PATH="$HOME/.nvm/versions/node/v26.7.0/bin:$PATH"   # real Node on PATH
$ npm test
  • baseline origin/main: tests 2778, pass 2777, fail 0, skipped 1
  • this branch: tests 2785, pass 2784, fail 0, skipped 1 — the +7 are the new tests, all passing.

bun test on the touched files:

$ bun test lib/git-status-cache.test.mjs app/api/git/status/route.test.mjs
7 pass, 0 fail

bun x tsc --noEmit clean, bun run lint clean.

At least one new test fails on origin/main and passes here. With lib/git-status-cache.ts present but the route left unwired on origin/main, app/api/git/status/route.test.mjs fails behaviourally (reuses one scan inside the TTL…: the file added inside the TTL still shows up, because the base route rescans on every request); the same file passes on this branch. lib/git-status-cache.test.mjs pins the TTL, the shared in-flight scan, the expired-entry-not-served rule, a scan that finishes after invalidation, and a failed scan retrying.

Note: on origin/main, a full-suite bun test is not green for either the base or this branch — the same unrelated files fail under Bun on both (verified, e.g. hooks/useAudio.test.mjs 0 pass/13 fail and lib/session-list-scanner.test.mjs 8 pass/6 fail on origin/main and on this branch). Those are upstream-main-under-Bun issues outside this change; upstream's own runner (npm test) is fully green as above.

Provenance

Source commit: db8af8a in brynne8/pi-web-bun — "perf(git): cache the status listing and share one scan between requests".

GET /api/git/status ran a full working-tree scan on every request, reading
every untracked file to count its lines, with nothing shared between a
sidebar reload and the next, or between two tabs on one project.

- lib/git-status-cache.ts: a 2 s per-cwd TTL in front of the scan, and an
  in-flight scan shared by concurrent requests for the same cwd, following
  lib/models-cache.ts.
- An expired entry is dropped before the request scans rather than served:
  the focus reload (agegr#1144) is what makes an editor's edit visible, so a
  listing older than the TTL is not an answer.
- The key is the cwd as spelled (the paths are rebased onto it), and the
  route's allow-list checks still run per request, so a revoked root is
  never served from an entry.
- An upload invalidates eagerly, so the explorer's refetch after one is not
  the listing cached before the write.

The response shape is unchanged; the first request still scans.

Measured on a synthetic repo (300 tracked files, 100 modified, 400 untracked
files of 300 lines each), timing the scan directly since the route is a thin
JSON wrapper around it:

  origin/main  5 sequential requests: 137.2, 96.2, 162.1, 100.7, 123.5 ms
  branch       5 sequential requests: 118.6,   0.0,   0.0,   0.0,   0.0 ms
  origin/main  8 concurrent requests: 659.7 ms
  branch       8 concurrent requests: 115.0 ms
@brynne8 brynne8 closed this Oct 18, 2026
@brynne8 brynne8 reopened this Oct 18, 2026
@brynne8

brynne8 commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

CI note: the first e2e run (39083346106) timed out on the upstream-flaky sidebar wait at e2e/run.mjs:496 (waiting for getByRole('button', { name: 'Show sidebar', exact: true }), 30s) — the 'returning from the mobile breakpoint restores the desktop sidebar preference' step, which this change never touches.

I could not use gh run rerun (rerunning requires admin on this repository), so I reopened the PR to trigger a fresh run: 39083659942 — checks pass (3m16s), e2e pass (3m38s), with no code change. The red was that one-off flake.

@agegr

agegr commented Oct 19, 2026

Copy link
Copy Markdown
Owner

Thanks @brynne8 for the careful write-up and the benchmark. I measured how this behaves in the app before deciding, and I'm going to close it.

  • The gain is small in practice. A tab sends one /api/git/status request per reload trigger (a tool finishing, at most once a second; a run ending; focus; an upload; refresh). Nothing in the app sends the 8-way parallel burst from the benchmark. On the pi-web repo (~2k tracked files, up to 430 changed files) a full scan takes 42–56 ms, so a cache hit saves about 50 ms now and then.
  • The cache makes the badges wrong after the reloads meant to refresh them. The only requests that land within 2 s of each other come during a run, exactly while files are changing. Replaying the app's reload timings against the route: tool A writes, refresh at 1 s; tool B writes at 1.6 s; the run-end refresh at 2.0 s and B's own refresh at 2.7 s both came back without B's file. Nothing reloads after that, so the badges stay wrong after the run finishes. A git commit in the terminal followed by focus within 2 s showed the same stale listing. On main every one of those answers is correct.
  • The shared in-flight scan has the same problem: a request triggered after a write can join a scan that started before it, and agent tools and terminal git commands never invalidate the entry.

Correct badges matter more here than ~50 ms. If you've seen the scan be slow on a real large repo, I'd gladly look at a change that makes getGitStatus() itself cheaper (for example how untracked files' lines are counted), with timings from that repo.

@agegr agegr closed this Oct 19, 2026
agegr pushed a commit that referenced this pull request Oct 20, 2026
Returning from the mobile breakpoint restores the desktop sidebar preference in an
effect, so the toggle can swap from "Show sidebar" to "Hide sidebar" between the
`isVisible()` check and the click. The click then waits its full 30s for a button
that will not come back, and the suite dies with

  locator.click: Timeout 30000ms exceeded. waiting for
  getByRole('button', { name: 'Show sidebar', exact: true }) at e2e/run.mjs:496:60

Seen on several unrelated PRs (#1322, #1324 ourselves, #1308 from another
contributor).

The click now retries against a short deadline and only its own timeout is
ignored; the wait for "Hide sidebar" that follows still fails if the sidebar never
opens, so a real regression is not hidden. The fork's earlier 947c7fe reload
fallback does not cover this signature: it fires only when neither toggle appears
within its 10s bound.
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 6, 2026
…gr#1326)

Returning from the mobile breakpoint restores the desktop sidebar preference in an
effect, so the toggle can swap from "Show sidebar" to "Hide sidebar" between the
`isVisible()` check and the click. The click then waits its full 30s for a button
that will not come back, and the suite dies with

  locator.click: Timeout 30000ms exceeded. waiting for
  getByRole('button', { name: 'Show sidebar', exact: true }) at e2e/run.mjs:496:60

Seen on several unrelated PRs (agegr#1322, agegr#1324 ourselves, agegr#1308 from another
contributor).

The click now retries against a short deadline and only its own timeout is
ignored; the wait for "Hide sidebar" that follows still fails if the sidebar never
opens, so a real regression is not hidden. The fork's earlier 947c7fe reload
fallback does not cover this signature: it fires only when neither toggle appears
within its 10s bound.
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 8, 2026
…gr#1326)

Returning from the mobile breakpoint restores the desktop sidebar preference in an
effect, so the toggle can swap from "Show sidebar" to "Hide sidebar" between the
`isVisible()` check and the click. The click then waits its full 30s for a button
that will not come back, and the suite dies with

  locator.click: Timeout 30000ms exceeded. waiting for
  getByRole('button', { name: 'Show sidebar', exact: true }) at e2e/run.mjs:496:60

Seen on several unrelated PRs (agegr#1322, agegr#1324 ourselves, agegr#1308 from another
contributor).

The click now retries against a short deadline and only its own timeout is
ignored; the wait for "Hide sidebar" that follows still fails if the sidebar never
opens, so a real regression is not hidden. The fork's earlier 947c7fe reload
fallback does not cover this signature: it fires only when neither toggle appears
within its 10s bound.
agegr added a commit that referenced this pull request Nov 12, 2026
…#1609)

* fix(files): count untracked lines without blocking the server (#1584)

/api/git/status read every untracked file with lstatSync/readFileSync in
one synchronous pass. With 46k untracked files on Windows that held the
server's event loop, and every chat stream and request with it, for 12 s.

Untracked files are now read with async fs, 8 at a time, in 64 KiB chunks
up to the size lstat reported, and the status entries are mapped in turns
of 1000. Counts and response shape are unchanged: one line per newline
byte plus an unterminated last line; empty, NUL-holding, over 256 KiB and
non-regular files count 0. No cache, no shared scan: every request still
reads afresh (#1322, #1350).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cli): count a busy server as running in status and stop (#1584)

pi-web status, stop, open and update list a record only when its URL
answers within 2 s. A server whose event loop a long request held took the
connection but answered nothing in time, so status printed "No pi-web
server is running." and stop did nothing.

A closed port refuses at once, so a probe that times out now counts as a
running server; a refused or failed connection still does not. The pid
was already found alive and ours before the probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cli): a timed-out probe counts only when a TCP connection opens (#1584)

A fetch timeout also comes from a slow refusal (Windows retries a
refused loopback connect for about 2 s), an address that drops packets
or a stuck name lookup. Counting those as running could let `stop`
kill a recycled pid's process tree. After a timeout, connect to the
same address: only an accepted connection means a busy server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(files): stop a git status scan its request left, read 4 files at a time (#1584)

The explorer aborts a replaced status request, and the route passes the
request's signal, so a long scan whose answer nobody waits for stops
instead of piling up behind each tool-end refresh. Four reads at a time
match libuv's default thread pool; more only queued ahead of the server's
other fs work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Hwwwww-dev pushed a commit to Hwwwww-dev/pi-web that referenced this pull request Nov 19, 2026
…1584) (agegr#1609)

* fix(files): count untracked lines without blocking the server (agegr#1584)

/api/git/status read every untracked file with lstatSync/readFileSync in
one synchronous pass. With 46k untracked files on Windows that held the
server's event loop, and every chat stream and request with it, for 12 s.

Untracked files are now read with async fs, 8 at a time, in 64 KiB chunks
up to the size lstat reported, and the status entries are mapped in turns
of 1000. Counts and response shape are unchanged: one line per newline
byte plus an unterminated last line; empty, NUL-holding, over 256 KiB and
non-regular files count 0. No cache, no shared scan: every request still
reads afresh (agegr#1322, agegr#1350).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cli): count a busy server as running in status and stop (agegr#1584)

pi-web status, stop, open and update list a record only when its URL
answers within 2 s. A server whose event loop a long request held took the
connection but answered nothing in time, so status printed "No pi-web
server is running." and stop did nothing.

A closed port refuses at once, so a probe that times out now counts as a
running server; a refused or failed connection still does not. The pid
was already found alive and ours before the probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cli): a timed-out probe counts only when a TCP connection opens (agegr#1584)

A fetch timeout also comes from a slow refusal (Windows retries a
refused loopback connect for about 2 s), an address that drops packets
or a stuck name lookup. Counting those as running could let `stop`
kill a recycled pid's process tree. After a timeout, connect to the
same address: only an accepted connection means a busy server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(files): stop a git status scan its request left, read 4 files at a time (agegr#1584)

The explorer aborts a replaced status request, and the route passes the
request's signal, so a long scan whose answer nobody waits for stops
instead of piling up behind each tool-end refresh. Four reads at a time
match libuv's default thread pool; more only queued ahead of the server's
other fs work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 2e8d3b1)
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 24, 2026
…1584) (agegr#1609)

* fix(files): count untracked lines without blocking the server (agegr#1584)

/api/git/status read every untracked file with lstatSync/readFileSync in
one synchronous pass. With 46k untracked files on Windows that held the
server's event loop, and every chat stream and request with it, for 12 s.

Untracked files are now read with async fs, 8 at a time, in 64 KiB chunks
up to the size lstat reported, and the status entries are mapped in turns
of 1000. Counts and response shape are unchanged: one line per newline
byte plus an unterminated last line; empty, NUL-holding, over 256 KiB and
non-regular files count 0. No cache, no shared scan: every request still
reads afresh (agegr#1322, agegr#1350).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cli): count a busy server as running in status and stop (agegr#1584)

pi-web status, stop, open and update list a record only when its URL
answers within 2 s. A server whose event loop a long request held took the
connection but answered nothing in time, so status printed "No pi-web
server is running." and stop did nothing.

A closed port refuses at once, so a probe that times out now counts as a
running server; a refused or failed connection still does not. The pid
was already found alive and ours before the probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cli): a timed-out probe counts only when a TCP connection opens (agegr#1584)

A fetch timeout also comes from a slow refusal (Windows retries a
refused loopback connect for about 2 s), an address that drops packets
or a stuck name lookup. Counting those as running could let `stop`
kill a recycled pid's process tree. After a timeout, connect to the
same address: only an accepted connection means a busy server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(files): stop a git status scan its request left, read 4 files at a time (agegr#1584)

The explorer aborts a replaced status request, and the route passes the
request's signal, so a long scan whose answer nobody waits for stops
instead of piling up behind each tool-end refresh. Four reads at a time
match libuv's default thread pool; more only queued ahead of the server's
other fs work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants