Skip to content

perf(git): count an untracked file's lines once while it is unchanged - #1350

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

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

Conversation

@brynne8

@brynne8 brynne8 commented Oct 20, 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 asks Git for the listing, and then reads every untracked file one by one, only to count its lines.

This makes that count cheap to keep. A file's line count is remembered for that file only, and only for as long as the file is provably the same one it was:

  • the remembered entry carries the file's size, modification time, change time and inode; a hit requires all four to match,
  • a file is only remembered once it has been quiet for at least two seconds, so a change to it after that point carries a later change time and is always seen,
  • the lines are counted from the bytes (\n), not from a decoded string.

Two things are deliberately not here: the listing is not cached — Git is asked on every request, exactly as before — and there is no expiry window on an answer. Every request produces the same listing, the same line counts and the same additions/deletions as before; the only thing this avoids is re-reading a file whose bytes cannot have changed.

The count is also taken from the bytes rather than from toString("utf8") + split("\n"): it does not build a string and an array of lines for every file, and its cost does not depend on how the lines are shaped. The native split is about twice as fast on a file of ordinary lines, and about eight times slower on a file of very short ones — the fourth row below.

Why it matters

When the previous pull request was closed, the maintainer left an invitation:

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.

This is that change. It answers the question that was asked — how the lines of an untracked file are counted — and it does it without touching the listing, so none of the staleness that closed #1322 can happen here.

The semantics are pinned by the file's own metadata rather than by a timer:

  • a rewritten file gets a new change time, which no program can set back, so it is counted again;
  • a file changed within the last two seconds is never remembered at all, so a coarse-timestamp filesystem (one second, or two) cannot hide a change behind a stale count;
  • the size, the modification time and the inode have to match as well, so a file that was replaced, truncated or swapped is counted again.

Measurements

Timed on the same machine, on the same repositories, in one process: origin/main's getGitStatus() and this branch's, against each other, 21 calls each, median reported.

repository before (cold) before (median) after (cold) after (median)
300 tracked / 100 changed / 400 untracked, 32 KB each 55.6 ms 41.6 ms 47.3 ms 32.5 ms
300 tracked / 100 changed / 400 untracked, 4 KB each 35.7 ms 30.5 ms 31.1 ms 25.5 ms
1200 tracked / 300 changed / 200 untracked, 32 KB each 120.0 ms 68.4 ms 74.5 ms 63.9 ms
300 tracked / 100 changed / 400 untracked, 32 KB each, 16k short lines per file 113.7 ms 99.1 ms 50.6 ms 32.6 ms
a checkout of this repository, clean 21.7 ms 18.5 ms 18.9 ms 18.8 ms
a checkout of this repository with 400 untracked files in it 79.6 ms 29.8 ms 38.9 ms 20.5 ms

Git's own listing dominates the total (30 ms of the 41 ms in the first row, 63 ms of the 68 ms in the third), so the request is 22 %, 16 % and 7 % faster in the first three rows, 67 % faster on the short-lines repository and 31 % faster on a real checkout with untracked files in it. The part that reads the files is 5–30× cheaper (10.8 ms → 1.7 ms in the first row, 68.5 ms → 2.0 ms in the fourth). A clean checkout has no untracked files to read, and is unchanged, as it should be.

Both branches return the same additions, deletions and file list on every repository above — that is checked as part of the measurement, not just asserted.

"Cold" is the first call on that repository. The process is warmed up on a scratch repository first, so the number is the cost of the scan and not of the first Git call in the process.

Reproduction (run from the repo root, with origin/main's lib/ copied to /tmp/before/):

// 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 jiti = createJiti(import.meta.url, { moduleCache: false });
const before = await jiti.import("/tmp/before/git-changes.ts");
const after = await jiti.import(path.join(process.cwd(), "lib/git-changes.ts"));

const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "gsc-bench-")));
const git = (...args) => execFileSync("git", ["-C", root, ...args], { stdio: "ignore" });
git("init", "--quiet");
git("config", "user.email", "[email protected]");
git("config", "user.name", "Bench");
const source = "const answer = 42; // a line of ordinary source code\n";
const body = () => {
  let out = "";
  while (out.length < 32 * 1024) out += source;
  return out.slice(0, 32 * 1024);
};
for (let i = 0; i < 300; i += 1) fs.writeFileSync(path.join(root, `tracked-${i}.txt`), body());
git("add", ".");
git("commit", "--quiet", "-m", "fixture");
for (let i = 0; i < 100; i += 1) fs.writeFileSync(path.join(root, `tracked-${i}.txt`), body() + "changed\n");
for (let i = 0; i < 400; i += 1) fs.writeFileSync(path.join(root, `untracked-${i}.txt`), body());

// A file is only remembered once it has been quiet for a while.
await new Promise((resolve) => setTimeout(resolve, 2200));

const now = () => Number(process.hrtime.bigint()) / 1e6;
const median = (xs) => [...xs].sort((a, b) => a - b)[xs.length >> 1];
for (const [name, impl] of [["before", before], ["after", after]]) {
  const times = [];
  let result = null;
  for (let i = 0; i < 21; i += 1) {
    const t = now();
    result = await impl.getGitStatus(root);
    times.push(+(now() - t).toFixed(1));
  }
  console.log(`${name}: cold ${times[0]} ms, median ${median(times)} ms, additions ${result.additions}`);
}
fs.rmSync(root, { recursive: true, force: true });
process.exit(0);
$ node gsc-bench.mjs
before: cold 96.9 ms, median 43.7 ms, additions 247700
after:  cold 49.5 ms, median 33.4 ms, additions 247700

The script's "cold" is the very first call in the process, Git's own first call included, which is why it is higher than the table's.

Scope

One change, two files: lib/git-changes.ts and lib/git-changes.test.mjs. Nothing else in the repository is touched, and no other optimisation is folded in.

To be explicit, because it is what the previous attempt was closed for:

  • this does not cache the listing. git status --porcelain still runs on every request, and the file list, its statuses and the tracked additions/deletions come from Git every time;
  • this does not introduce an expiry window. There is no TTL on an answer, and no request can be served a listing that is older than the last one Git gave;
  • the only thing remembered is one file's line count, and only while that file's own size, modification time, change time and inode say it cannot have changed.

Testing

$ export PATH="$HOME/.nvm/versions/node/v26.7.0/bin:$PATH"   # real Node on PATH
$ node --version
v26.7.0
$ npm test
  • baseline origin/main: tests 2799, pass 2798, fail 0, skipped 1
  • this branch: tests 2802, pass 2801, fail 0, skipped 1 — the +3 are the new tests, all passing.

npx tsc --noEmit clean, npx eslint . clean.

The three new tests in lib/git-changes.test.mjs pin the semantics that matter:

  • a changed file is counted again — the count follows the file, not the answer that came before it;
  • a file whose modification time is put back is counted again all the same — the bytes are the same length and the name the same, so only the file's own change time gives it away, and a program cannot set that back. This test fails if the change time is left out of the key;
  • an empty, a binary and an oversized file hold no lines, as before.

Provenance

One feature per pull request, split out of a Bun-running fork (brynne8/pi-web-bun) into a single-purpose branch on today's main. The fork's own git status cache is not part of this change and is not present here — this branch is only the line counting.

`GET /api/git/status` reads every untracked file on every request, only to
count its lines. This keeps that count per file for as long as the file is
provably the same one it was: size, modification time, change time and
inode must all match, and the file must have been quiet for at least two
seconds, so a change to it after that point carries a later change time and
is seen. The lines themselves are counted from the bytes rather than from a
decoded string.

This is not a cache of the scan. The listing is still read from Git on every
request, and every request still produces the same answer as before: the
same files, the same line counts, the same additions and deletions. It only
avoids re-reading a file whose bytes cannot have changed.

Why: the maintainer of this repository closed an earlier pull request that
put a two-second cache in front of the whole scan, because the sidebar's
reload triggers land inside that window while files are changing, and a
stale badge is worse than a slow scan. In closing it they wrote:

  "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."

This is that change, with timings.

Measured on the same machine, on the same repositories, in one process, with
origin/main's getGitStatus() and this one timed against each other (21
calls each, median):

  300 tracked / 100 changed / 400 untracked, 32 KB each
    before 55.6 ms cold, 41.6 ms median   after 47.3 ms cold, 32.5 ms median
  300 tracked / 100 changed / 400 untracked, 4 KB each
    before 35.7 ms cold, 30.5 ms median   after 31.1 ms cold, 25.5 ms median
  1200 tracked / 300 changed / 200 untracked, 32 KB each
    before 120.0 ms cold, 68.4 ms median  after 74.5 ms cold, 63.9 ms median
  a checkout of this repository, clean
    before 21.7 ms cold, 18.5 ms median   after 18.9 ms cold, 18.8 ms median
  a checkout of this repository with 400 untracked files in it
    before 79.6 ms cold, 29.8 ms median   after 38.9 ms cold, 20.5 ms median

Git's own listing dominates the total, so the request itself is 7-67% faster
where there are untracked files to read, and the part that reads them is 5-30x
cheaper. A clean checkout has no untracked files to read and is unchanged, as
it should be.

Tested with Node 26.7.0: `npm test` (2802 tests, 0 failures, 1 skipped),
`npx tsc --noEmit` and `npx eslint .` clean. The new tests in
`lib/git-changes.test.mjs` pin that a changed file is counted again, that a
file whose modification time is put back is counted again all the same, and
that an empty, binary or oversized file holds no lines.
@agegr

agegr commented Oct 20, 2026

Copy link
Copy Markdown
Owner

Thanks @brynne8 for following up on #1322, and for keeping the listing uncached this time. I asked for timings from a real repo where the scan is slow, so I measured that before deciding, and I'm going to close this one.

I loaded main's getGitStatus() and this branch's in one process, alternated them, and took the median of 31 calls each. Every repo was a copy-on-write copy, so the originals were untouched.

repo untracked files main this PR
pi-web, as checked out 0 31.4 ms 31.7 ms
the busiest real repo on the machine 118 (1 MB) 31.4 ms 28.3 ms
a 6.9k-file repo 1 78.4 ms 78.8 ms
pi-web + 20 new files (a typical agent run) 20 33.4 ms 32.8 ms
pi-web + 400 untracked (the PR's shape) 400 51.8 ms 40.5 ms
node_modules not ignored, 5k files 5,000 221 ms 234 ms
node_modules not ignored, 20k files 19,999 858 ms 997 ms
  • On real repos the saving is 0–3 ms on a background request that refreshes badges, at most once a second. Most of the per-file cost is opening and reading the file (about 25 µs per file), and a cache hit still pays the lstat.
  • Where counting really dominates, it's slower. With more than 2,048 untracked files, every scan walks more files than the map holds, in the same order. The cache then never hits (4,994 of 5,000 files were re-read on every scan) and only adds the bigint lstat and the map work.
  • It can serve a stale count. On a FAT32 volume, ctime is just mtime. cp -p of a same-size file with different contents over an untracked file kept size, mtime, "ctime" and inode, so the branch answered +4 where main answered +3. It stayed wrong on every scan until the file changed again. ("A program cannot set ctime back" holds on APFS/ext4/NTFS, not on FAT/exFAT.) Git misses the same edit on a tracked file there, so the rule is as good as git's own, but main is right for untracked files today. On NFS, the cache hit also skips the open that makes the client revalidate cached attributes.
  • On the counting itself: the byte loop isn't slower than split here (it ties at 4–16 KB and is 1.5–3× faster above that). A count-only change, with no cache, saves 0–1.2 ms on these repos, though, so it isn't worth a change on its own either.

So the trade is the same as in #1322: a process-wide cache with an edge case where the +N goes wrong, for a few milliseconds nobody sees. Thanks again for the careful, single-purpose PRs. #1349 is the kind that goes straight in.

@agegr agegr closed this Oct 20, 2026
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