Ray's Knowledge Base
Unlock

git2::Diff is not Sync; concurrent Patch::from_diff on a shared diff corrupts output nondeterministically

PitfallVerified 5 Oct 2026Holds git2: 0.21, project: rgit
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

rgit diff -p prints nothing (exit 0) on a repo with many changed files, but only sometimes; output md5 differs run to run. Appeared after wrapping &git2::Diff in a raw-pointer struct with unsafe Send/Sync to fan out Patch::from_diff over rayon.

Cause#

git2 declares only unsafe impl Send for Diff, not Sync. libgit2's git_patch_from_diff mutates diff-internal state when lazily materializing file content, so concurrent patch creation over one shared git_diff races.

Fix#

Parallelize with per-thread handles instead: each rayon worker calls Repository::open(gitdir) and rebuilds the same diff on its own handle, then extracts only its chunk of delta indices (pattern in git_repo.rs extract_with_renames_par; precedent: Repository::open(&gitdir) per thread in the update loop). Never share one Diff across threads.

Evidence#

2000-file repo: rgit diff -p | md5 gave five identical hashes matching git diff only after the fix; before, runs intermittently produced empty output. Repro and timings: extraction of 2000 file patches ~200 ms sequential, ~140 ms with per-thread rebuild (libgit2 contention caps scaling near 4 threads).

Also found by searching

  • concurrent Patch::from_diff corrupts output
  • git2 Diff not Sync rayon race
  • parallel libgit2 diff extraction empty output
  • rgit diff prints nothing sometimes