Re: [PATCH 2/2] commit: lock index before reading
- From
Jeff King <peff@peff.net>
- Date
- Oct 14, 2026, 10:04 UTC
- Message-ID
- <20261014100432.GB1344504@coredump.intra.peff.net>
- In-Reply-To
- <20261013172315.2997446-3-quark.zju@gmail.com>
On Tue, Oct 13, 2026 at 10:23:15AM -0700, Jun Wu wrote:
Show 9 quoted lines
> Take the index lock before reading the index, in one place, instead > of separately in each `if` branch. > > `commit` now respects the `core.indexLockTimeout` config. > > History suggests no particular reason for reading before locking: > - f5bbc3225c (Port git commit to C., 2007-11-08): lock before reading > - 2888605c64 (builtin-commit: fix partial-commit support, 2007-11-18): > seems to accidentally move reading to before locking
Hmm. We may do a lot more work under lock than we used to, running stat() on the whole repo.
But I think there's a deeper issue here. We're reading the index, _then_ taking the lock, but not necessarily discarding what we read earlier. So it feels like two processes could race here, with git-commit discarding some update by another process (like git-add).
If we instrument git-commit like this:
diff --git a/builtin/commit.c b/builtin/commit.c index 840b6b4083..2a78cb473a 100644 --- a/builtin/commit.c +++ b/builtin/commit.c @@ -392,6 +392,8 @@ static const char *prepare_index(const char **argv, const char *prefix, if (repo_read_index_preload(the_repository, &pathspec, 0) < 0) die(_("index file corrupt")); + sleep(5); + if (interactive) { char *old_index_env = NULL, *old_repo_index_file; repo_hold_locked_index(the_repository, &index_lock, that widens the race window. And then something like this: echo new content >old-file git commit -am foo & sleep 1 ;# commit is sleeping in race window git add new-file will clobber the index change from git-add. And that is true with today's code, not using any timeouts. Adding a timeout doesn't really change anything, though if you _do_ see lock contention it is a good sign that you are about to hit the race and clobber something. ;) So it is widening the window. But the correctness problem is already there. I do think your patch fixes the problem. But we probably want to discuss that in the commit message as a motivation (and likewise, discuss the fact that we may be holding the lock for longer). There's probably some kind of hybrid world where we optimistically read without the lock, then take the lock, and then check (cheaply-ish) that the index didn't change since what we read. But I don't think we do that in this code path. -Peff