Skip to content

git: avoid racy temp-index stats for untracked files - #3014

Merged
max-sixty merged 1 commit into
max-sixty:mainfrom
Xeonacid:fix-working-tree-untracked-racy-index
Jun 8, 2026
Merged

max-sixty merged 1 commit into
max-sixty:mainfrom
Xeonacid:fix-working-tree-untracked-racy-index

Conversation

@Xeonacid

@Xeonacid Xeonacid commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

working_tree_diff_stats_with_untracked() used a copied index to make untracked files visible to git diff: first git add --intent-to-add ., then git diff --shortstat HEAD against that temporary index. That means the copied index also has to rediscover tracked working-tree modifications.

On a slow riscv64 machine, the test passes by itself and the full lib test suite passes with --test-threads=1, but the default concurrent lib test run reliably exposes a failure. Diagnostic output from the failing test showed tracked.txt already contained the new contents, while git status and git diff through the temporary index reported only untracked.txt. The tracked rewrite was same-size, so the copied index could treat it as racily clean under this slow riscv64 machine.

Do not use the temporary index to rediscover tracked changes. Keep the existing git diff --shortstat HEAD path for tracked, staged, and unstaged changes, then list untracked files with git ls-files --others --exclude-standard -z, stage only those paths into the temporary index, and sum their cached numstat output. The real index remains untouched, while the racy-index window is avoided.

working_tree_diff_stats_with_untracked() used a copied index to make untracked files visible to git diff: first git add --intent-to-add ., then git diff --shortstat HEAD against that temporary index. That means the copied index also has to rediscover tracked working-tree modifications.

In a riscv64 qemu-user chroot, the test passes by itself and the full lib test suite passes with --test-threads=1, but the default concurrent lib test run reliably exposes a failure. Diagnostic output from the failing test showed tracked.txt already contained the new contents, while git status and git diff through the temporary index reported only untracked.txt. The tracked rewrite was same-size, so the copied index could treat it as racily clean under this slower, heavily concurrent qemu-user workload.

Do not use the temporary index to rediscover tracked changes. Keep the existing git diff --shortstat HEAD path for tracked, staged, and unstaged changes, then list untracked files with git ls-files --others --exclude-standard -z, stage only those paths into the temporary index, and sum their cached numstat output. The real index remains untouched, while the qemu-user-only racy-index window is avoided.
@max-sixty

Copy link
Copy Markdown
Owner

On a slow riscv64 machine, the test passes by itself and the full lib test suite passes with --test-threads=1, but the default concurrent lib test run reliably exposes a failure. Diagnostic output from the failing test showed tracked.txt already contained the new contents, while git status and git diff through the temporary index reported only untracked.txt. The tracked rewrite was same-size, so the copied index could treat it as racily clean under this slow riscv64 machine.

do we know where this race comes from?

@worktrunk-bot please can you explain it to me?

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

This comes from Git's racy-index heuristic interacting with the copied temp index. The short version: the old code asked a freshly-written temp index to rediscover tracked modifications, and that rediscovery relies on a stat comparison that Git deliberately treats as untrustworthy in a narrow timing window — a window the copy re-opens.

Git's stat cache and the racy rule

To make git status/git diff fast, Git doesn't re-hash every tracked file. For each entry the index caches the file's lstat data (mtime, ctime, size, inode, …). On the next read Git lstat()s the working file and, if the stat matches the cached stat, assumes the content is unchanged and skips re-hashing.

That optimization has a hole: a file can be modified, the index written, and the file modified again, all within one filesystem timestamp tick. The second modification would leave the mtime unchanged, so the stale stat would still "match." Git guards against this with the racy rule:

  • It records the index file's own mtime as istate->timestamp when the index is read.
  • Any entry whose cached mtime >= istate->timestamp is racily clean — Git refuses to trust the stat and re-reads the content to be sure.
  • At write time, smudge_racily_clean_entries() zeroes the cached size of such entries, so a future read is forced to re-compare regardless.

The reference point for all of this is the index file's own timestamp.

Why the temp-index path was vulnerable

The old working_tree_diff_stats_with_untracked() did, against a byte-copy of the real index:

git add --intent-to-add .        # re-stats every path, then WRITES the temp index
git diff --shortstat HEAD        # trusts that fresh stat cache

The git add step re-writes the temp index "now", which resets istate->timestamp to the present and re-stats every tracked file into it. For a tracked file modified moments earlier:

  • mtime matches the just-written cache (it was re-stat'd during add), and
  • size matches — the test's rewrite was deliberately same-size, so size, Git's cheap discriminator, can't catch it, and
  • the entry falls outside the smudge protection (its mtime isn't >= the brand-new write timestamp in the way that would trigger smudging).

So git diff trusts the stat, skips re-hashing tracked.txt, and reports it as clean — exactly the diagnostic observed (tracked.txt already had the new contents, but only untracked.txt showed up).

The real index never has this problem here because the change goes through git diff HEAD against an index whose racy/smudge bookkeeping was established at commit time and not disturbed.

Why only slow riscv64-under-qemu

On a normal machine two things hide the bug:

  1. Fine-grained mtime (nanosecond st_mtim) means the rewrite and the temp-index write almost never land in the same tick, so the stat mismatches and the change is caught.
  2. Even at second granularity you need the rewrite to be same-size and fall in the unlucky tick.

qemu-user emulating riscv64 reports coarse/second-granularity timestamps (and can zero the nsec field that the racy comparison leans on), and the heavily-concurrent default test run slows wall-clock progress enough that the rewrite and the temp-index write frequently share a tick. That's why it's reliable there, passes in isolation, and passes with --test-threads=1.

Why the fix avoids it

After the change the temp index is only ever used for untracked paths that we explicitly ls-files --others, stage, and diff by path. Tracked changes come from git diff HEAD against the real index, where Git's racy/smudge protections are intact. Untracked entries can't produce a racy false-negative here because they have no pre-existing cached stat to be wrongly trusted — we stage exactly those paths and sum their --cached --numstat output. The real index is never touched and the racy-index window is never opened.

— 🤖 worktrunk-bot

@max-sixty

Copy link
Copy Markdown
Owner

thanks!

if we copied the index and maintained its timestamp, would that work?

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Short answer: no, not as described — because the vulnerable write happens inside git add, after the copy.

Why preserving the copy's timestamp doesn't survive

The racy reference point is the index file's own mtime (istate->timestamp), read when git opens the index. The old path was:

cp real_index temp_index      # whatever timestamp we give the copy
git add --intent-to-add .      # RE-STATS every tracked file, then RE-WRITES temp_index
git diff --shortstat HEAD      # reads istate->timestamp = the add's write time

The git add step rewrites temp_index with a fresh "now" timestamp and re-stats tracked.txt into it at its current mtime. So whatever timestamp we preserved on the copy is gone by the time git diff reads the index — the diff sees the add's write time, not ours. std::fs::copy doesn't even carry mtime across on Linux, but it wouldn't matter if it did.

The direction that would work — and why we didn't do it

You can force the catch by going the opposite way: after the add, backdate the temp index file's mtime to before the working-tree edits. Then every entry has cached_mtime >= istate->timestamp, so all of them are racily clean and git re-hashes them — tracked.txt gets caught.

But that's:

  1. Backdating, not maintaining — and only correct if the chosen timestamp is genuinely older than every working-tree modification, which we'd have to reason about per call.
  2. Slow — it forces a re-hash of the entire tree, defeating the stat cache that the temp-index trick exists to exploit in the first place.
  3. Fragile — it deliberately steers into the racy heuristic (zeroed nsec, coarse-granularity clocks, the whole reason qemu-user broke) rather than away from it. We'd be depending on undocumented behavior to be reliably wrong-in-our-favor.

So the merged fix instead just never asks the temp index to judge tracked files: tracked/staged/unstaged come from git diff HEAD against the real index (racy/smudge bookkeeping intact), and the temp index only ever stages the explicit untracked paths — which have no pre-existing cached stat to be wrongly trusted.

— 🤖 worktrunk-bot

@Xeonacid

Xeonacid commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the great review and explanation, max-sixty and bot!

Why only slow riscv64-under-qemu

Nit: The bug occurs not only under qemu, but also on real riscv64 hardware which are mostly slow.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

You're right, and thanks for the correction — I'll own that "qemu-user-only" framing was wrong.

The racy-index trap isn't an emulation artifact at all; it's purely about timestamp granularity. Git's racy rule leans on st_mtim, and the false-negative window opens whenever a same-size rewrite and the temp-index write can land in the same observable tick. That happens any time the effective mtime resolution is coarse (second-granularity, or a zeroed nsec field) and wall-clock progress between the two writes is slow enough to fit inside one tick — which describes real, slow riscv64 hardware just as well as a qemu-user chroot. The emulation only made it easy to hit; it was never a precondition.

So the accurate framing is "coarse-timestamp + slow + same-size rewrite," not "qemu." The fix is unaffected either way, since it stops asking the temp index to judge tracked files at all.

One heads-up: the same "qemu-user-only" wording is in the commit message body (while the qemu-user-only racy-index window is avoided). Since it's your commit and the PR is still open, you may want to reword it there too — I'll leave that to you rather than touch your commit.

— 🤖 worktrunk-bot

@max-sixty
max-sixty merged commit ba6a3c2 into max-sixty:main Jun 8, 2026
34 of 35 checks passed
@max-sixty

Copy link
Copy Markdown
Owner

@Xeonacid thank you very much for the thoughtful and technically deep change!

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.

3 participants