Skip to content

Keep a change visible when unstaging after reset --soft (sparse index) - #2200

Draft
Tyrie Vella (tyrielv) wants to merge 6 commits into
tyrielv/sparse-index/widen-on-modifyfrom
tyrielv/sparse-index/unstage-after-soft-reset
Draft

Tyrie Vella (tyrielv) wants to merge 6 commits into
tyrielv/sparse-index/widen-on-modifyfrom
tyrielv/sparse-index/unstage-after-soft-reset

Conversation

@tyrielv

@tyrielv Tyrie Vella (tyrielv) commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Note

This PR is part of a stack of PRs into vnext. It builds on #2197, and its base branch is the branch of #2197, so the diff shows only this layer.

Important

Test with the git changes. This stack needs the git-side changes in microsoft/git#1027, #1025, #1028, #1024, and #1026. VFS for Git CI uses a released git without them, so CI skips the AutoSparseIndex functional tests (NUnit reports them as ignored). To run the tests locally, install the unsigned preview git from sparse-index-preview-1. Its release notes give the install, test, and removal steps.

Latest preview validation: run 44381940180 on 830a7882: 50 passed, 0 failed, 0 ignored; 1 other test failed (WorktreeTests.ConcurrentWorktreeAddCommitRemove, x64).

Problem and Context

With gvfs.auto-sparse-index on, the index stores each directory outside the sparse-checkout cone as one sparse-directory entry. git reset --soft HEAD~1 can then stage a file inside such an entry. Git changes only the tree id of the entry, and it writes nothing to the working tree. No file system callback fires, so the mount does not add the file to the modified paths, and the cone does not include it.

A later unstage of that file failed or hid the change. Measured on a repository with about 2.2 million index entries, for a file outside the cone that HEAD changed relative to HEAD~1:

  • git restore --staged -- <path> failed with pathspec '<path>' did not match any file(s) known to git, because the file has no index entry.
  • git restore --staged . unstaged the file and kept its content. But the file stayed inside the sparse-directory entry with skip-worktree set, so git status and git diff did not show the change. git commit -a left it out, and a later checkout could overwrite it without a warning.
  • git reset expanded the whole index.

GVFS already prepares an unstage for a full index: the pre-command hook sends PrepareForUnstage, and the mount runs git diff --cached --name-status -z <pathspec> and adds the staged files to the modified paths. The mount reported addedToModifiedPaths: 0 for the first case. The cause is in Git: git diff --cached does not match a pathspec with a path inside a sparse-directory entry. For example, git diff --cached -- dir/sub/file.h prints nothing, while git diff --cached -- dir and git diff --cached without a pathspec report the file. The hook sent PrepareForUnstage before the widen, so the query ran while the file was still hidden. git restore has the same pathspec limit, which gives the error above.

Changes

  • The pre-command hook now sends the widen before PrepareForUnstage (new PreCommandConeRequests). The widen gives each named path an index entry, so git diff --cached finds the staged file, and git restore matches the path.
  • FileSystemCallbacks.TryAddStagedFileToModifiedPaths reports each staged file that the mount adds to the modified paths to the working-tree change observer of Widen the sparse-index cone for working-tree changes #2197. If the applied cone does not include the file, the observer makes a cone change pending. After PrepareForUnstage, the hook checks the pending file again and sends ConeApply. The apply covers the forms that name no path that the widen can use, such as git restore --staged . and git reset. The command holds the GVFS lock, so the apply can write the index before Git runs. The observer documentation now names this second source of changes.
  • For an unstage command, the hook now stops the command when the widen times out or the apply does not succeed. Before, every cone request failure let Git run, because it only made Git slower. For an unstage, Git would then remove the staged difference while the file stays hidden. The message names the failed request and tells the user to run the command again.
  • The hook treats a mixed git reset as an unstage operation when GVFS manages a sparse-index cone (cone-mode cone file and gvfs.auto-sparse-index). --soft, --hard, --merge, --keep, and --patch are not unstage operations. A reset whose pathspecs the hook cannot read (--pathspec-from-file=-) runs without the preparation, as before. With a full index, Git prepares the files of a mixed reset itself, so the hook sends nothing new. For git reset, the argument before -- is the tree-ish. Without --, only HEAD is taken as the tree-ish.
  • ConeManagementHook.IsSparseIndexConeManaged is the one gate for the widen, the narrow, and the reset preparation.
  • PrepareForUnstage writes the staged content of an added file only when the file was not a modified path yet. Before, it wrote every added file with git checkout-index --force. That overwrote unstaged edits to a file that the user created, staged, and edited again. This affected git restore --staged with a full index too.
  • The PrepareForUnstage failure message now says "Retry the unstage command" instead of "Retry the restore --staged command", because git reset can show it too. The --source/-s option skip of the unstage parser now applies only to git restore (git reset has no such option).
  • Add unit tests for PreCommandConeRequests. The tests check that an unstage command widens before it prepares, that the hook applies a change that the preparation made pending (after an applied widen and after a widen that named no path), and that it applies a change that was pending before a widen that did not apply. Other tests check that an unstage stops when the widen times out or the apply fails, that it runs when the apply has nothing to do, and that other commands keep the earlier order and never stop.
  • Add unit tests for UnstageCommandParser.ShouldPrepareForUnstage and the git reset forms of the parser, and for ConeManagementHook.IsSparseIndexConeManaged.
  • Add a unit test that TryAddStagedFileToModifiedPaths adds the path to the modified paths, reports it to the observer, and reports it again when it already is a modified path.
  • Add functional tests (AutoSparseIndexUnstageTests) that check out a commit that changes a file outside the cone, without a write to that file. Each test asserts that the cone does not include the file's directory, runs git reset --soft HEAD~1, and then runs one of git restore --staged -- <path>, git restore --staged ., git reset -- <path>, and git reset. The tests assert that the command succeeds without ensure_full_index, that git status shows M <path>, that git ls-files -v shows H, that the file keeps the committed content, and that the index on disk stays sparse (the entry count in the index header is smaller than the number of files in HEAD). IndexHeaderEntryCount moves from AutoSparseIndexConeTests to AutoSparseIndexTestsBase for this. Each test resets the enlistment in a finally block. git restore --staged . and git reset rely on the apply, and the apply keeps a staged file that has no placeholder in the cone only because Git changes only the index when the cone changes. The mount turns cone management on only for a Git that advertises feature: vfs-sparse-index, which includes that behaviour.
  • Add functional tests that create, stage, and edit a new file, then unstage it with git restore --staged and git reset. The tests assert that the file keeps the unstaged edit.

Functional-test fixtures

  • GVFS.FunctionalTests.Tests.EnlistmentPerFixture.AutoSparseIndexUnstageTests (new)
  • GVFS.FunctionalTests.Tests.EnlistmentPerFixture.AutoSparseIndexConeTests (changed: it uses IndexHeaderEntryCount from AutoSparseIndexTestsBase; no behaviour change)

Known gaps and deliberate decisions

  • git reset <path> and git reset <commit> without --. The widen parser of Hooks: parse git command lines and request sparse-index cone widening #2192 reads the first argument as a commit, and the unstage parser reads it as a path, because the hook cannot tell them apart. The widen then does not include the path, the preparation finds nothing, and Git expands the index for these forms. git reset -- <path> and git reset HEAD <path> work.
  • Pathspecs that the hook cannot resolve. A glob in a directory segment, a magic pathspec, or --pathspec-from-file gives the widen no path. For a file inside a sparse-directory entry, git restore --staged then still fails to match it. A fix in Git (match a sparse-directory entry with a pathspec that names a path inside it) would remove this limit.
  • The preparation reports staged files through the working-tree change observer. The mount could instead apply the cone inside PrepareForUnstage. That needs the Git process id in the request and a second apply path. The observer keeps one apply path, with its lock check, timeout, and retry of a pending change.
  • A pending file that the mount cannot create. If the observer cannot create .gvfs\ConeChangePending, the mount logs a telemetry warning, the preparation still succeeds, and the hook does not apply. A working-tree change has the same limit in Widen the sparse-index cone for working-tree changes #2197.
  • PrepareForUnstage has no deadline. The hook waits for the reply, and the mount's git diff --cached has no timeout unless gvfs.git-status-stream-timeout-seconds is set. This is the same for git restore --staged before this change. A mixed reset now waits for it when GVFS manages a sparse-index cone.
  • Other commands that stage without a file system write, such as git checkout <commit> -- <path>, git cherry-pick -n, and git read-tree, can hide a file in the same way. This change covers the unstage after git reset --soft only.

@tyrielv
Tyrie Vella (tyrielv) force-pushed the tyrielv/sparse-index/unstage-after-soft-reset branch from 3613ce4 to c97baa2 Compare November 17, 2026 18:02
With a sparse index (git index.sparse), git stores each folder outside
the sparse-checkout cone as one sparse-directory entry. The entry has
mode 040000, a path that ends in '/', and the id of the folder tree.
The projection must still contain every file, because the user sees
the full working directory.

Add the gvfs.auto-sparse-index setting (default false). When it is
false, the projection rejects a sparse index, as before. When it is
true, the projection reads the tree behind each sparse-directory entry
through libgit2, and adds every file under it. The result is the same
projection that the full index gives:

- The walk reads the trees depth first, in tree order, which is the
  same as index order. Folder names that differ only in case merge as
  they do for a full index, and the first name wins.
- A folder is added only when a file under it is added, because a full
  index has no entry for an empty tree.
- A file is not added if the file, or a folder above it, is in the
  modified paths. For a full index, git clears the skip-worktree bit
  of these entries, so the projection does not contain them.
- A missing tree is downloaded once. The download stops when the mount
  stops. If a tree is still missing, is not a tree, or cannot be read,
  or if a tree has an entry that git cannot add to an index (for
  example '..', '.git', or a path longer than 4095 bytes), the build
  fails with SparseIndexExpansionException. The mount shows its
  message, which tells the user what to do next, without a stack.

Keep the other index consumers correct for a sparse index:

- The placeholder scan treats a placeholder under a sparse-directory
  entry as an index entry with the skip-worktree bit only if the file
  is in the tree of the entry. Otherwise, as for a full index, the
  file moves to the modified paths and stays on disk. If the tree
  cannot be read, the scan treats the file as not in the index. If the
  sparse-directory entry has no skip-worktree bit, the scan adds the
  folder to the modified paths.
- The hydration summary of a mounted enlistment gets the file count
  from the projection, because the index header counts a collapsed
  folder as one entry.
- 'gvfs repair' validates a sparse-directory entry, but does not read
  the trees, and does not replace a valid sparse index.
- GVFS.PerfProfiling accepts a sparse index when the setting is true.

Fix LazyUTF8String.BytePool.MakeFreeSpace, which expanded the pool
only once. A name longer than one expansion was copied past the end of
the pool. A sparse index has few entries, so its pools start small.

Add LibGit2Repo.EnumerateTree, which reads a tree with
git_object_lookup and reports a missing tree, a non-tree object, and an
unreadable tree as different results. Add GitRepo.TryEnumerateTree,
GitRepo.GetConfigBoolOrDefault, a cancellable
GVFSGitObjects.TryDownloadAndSaveObject overload, and the
RequestSource.ProjectionBuild value. The projection build telemetry
records the expansion counts, also when the build fails.

Add unit tests that build the projection from a full index and from
sparse indexes of the same trees, and compare every folder, file, SHA,
folder inclusion, and file mode. Other unit tests check the
modified-paths rule, the placeholder scan, the failure paths, small
string pools, and the hydration file count. Add functional tests that
read real trees through libgit2, and that mount an enlistment with a
sparse index.

Assisted-by: Claude Opus 5.5
Signed-off-by: Tyrie Vella <[email protected]>
Add a library in GVFS.Common.Sparse that computes the sparse-checkout
cone that GVFS needs for a sparse index, and writes it to
info/sparse-checkout. Nothing calls the library yet. A later change
uses it from the mount process.

- ConeBuilder maps modified paths to cone patterns. A modified file
  adds parent-only patterns for its directory and each ancestor, so it
  does not pull a whole subtree into the index. A modified folder adds
  one recursive pattern. GVFS does not use "git sparse-checkout set",
  because "set" makes every input directory recursive.
- ConePatternSet holds the cone and its case rule. It rejects a
  directory that is in the cone twice under that rule, and a directory
  that git cannot read back from a cone file. When core.ignoreCase is
  true, git treats "Src" and "src" as a repeated pattern and turns off
  cone matching. So the builder merges directories that differ only in
  ASCII case when core.ignoreCase is true.
- ConeFileWriter writes the file in git's cone format through a
  temporary file and a rename. It keeps a backup for rollback. It
  writes nothing when the bytes do not change. It fails, and does not
  write, when it cannot read the existing file. A git process that
  reads the file keeps it open without delete sharing, so the rename
  can fail with ERROR_ACCESS_DENIED or ERROR_SHARING_VIOLATION. The
  writer then tries the replace again with git's mingw_rename delays,
  within a total wait that the caller sets (100 ms by default).
- ConePathMatcher decides whether a path is in the cone with git's
  cone rules, including git's ASCII-only case folding.
- SparseCheckoutPathResolver finds the per-worktree sparse-checkout
  file.

MockFileSystem now throws FileNotFoundException when a test reads a
missing file, as the real file system does. It also keeps the exact
bytes when it moves or copies a file.

Add unit tests for the builder, the pattern set, the comparer, the
writer success and failure paths, the replace retry, the matcher, and
the resolver. The unit tests start no external programs.

Add a local component functional test that compares the matcher with
"git sparse-checkout check-rules" with core.ignoreCase on and off.

Assisted-by: Claude Opus 5.5
Signed-off-by: Tyrie Vella <[email protected]>
When the sparse index is enabled, a git command that names a path
outside the sparse-checkout cone makes git expand the whole index in
memory. The pre-command hook can prevent this: it can ask the mount to
widen the cone before git runs. This change adds the hook side of that
protocol. A mount that does not handle the requests replies
UnknownRequest, and the hook treats every reply other than success as
"not applied" and lets git run.

Add GitPathspecParser, a table-driven parser that extracts the
pathspecs from the hook argv. Each git verb in the table states which
positional arguments are pathspecs, which options take a value, and
which flags remove the leading ref operand. The parser handles "--",
--end-of-options, --pathspec-from-file, --pathspec-file-nul, combined
short options, and the --git-pid and --exit_code arguments that git
appends.

Add ConePathspecResolver, which maps pathspecs to repo-relative cone
entries and drops any path that could leave the worktree. Git changes
to the top of the worktree before it runs the pre-command hook, so
relative pathspecs resolve against the worktree root plus GIT_PREFIX,
not against the current directory of the hook.

Add ConeCoverage, which reads a cone-mode sparse-checkout file with the
same rules as git's reader into a ConePatternSet, and uses
ConePathMatcher to find the paths that the cone does not cover.

Add the ConeWiden and ConeNarrow pipe messages and their wait budgets.
A widen carries only the git process id and repo-relative paths, and
the parser rejects any other path, because any local user can write to
the mount pipe.

Add ConeManagementHook, which the pre-command and post-command hooks
call. It does nothing unless the command names paths, the worktree has
a cone-mode sparse-checkout file, and gvfs.auto-sparse-index is true.
It sends only the paths outside the cone, and it skips git stash, which
still expanded the index after a widen in measurements. Every failure
lets git run.

After the hook sent a widen, it waits for the reply up to a 10 second
ceiling, not only for the 1 second send budget. The mount applies a
widen with a git process that holds index.lock. If the hook let the
user's git run first, that git could fail with "index.lock: File
exists". A narrow does not run git, so its 100 ms budget stays.

Assisted-by: Claude Opus 5.5
Signed-off-by: Tyrie Vella <[email protected]>
The pre-command hook asks the mount to widen the sparse-checkout cone
before a Git command that names paths outside the cone. The
post-command hook asks it to narrow the cone after the command. Until
now the mount answered both requests with UnknownRequest, and Git
expanded the whole index in memory to find those paths.

Add AutoSparseIndexConeManager. It handles ConeWiden and ConeNarrow
when gvfs.auto-sparse-index was true when the projection was created,
and core.sparseCheckout and index.sparse are true. The Git that the
mount runs must also report "feature: vfs-sparse-index" in "git
version --build-options". A Git without that line runs "sparse-checkout
reapply" but leaves a full index full. Otherwise the mount traces a
warning and replies NotEnabled.

The cone is the cone of the modified paths plus the paths of every
Git command that widened and did not narrow yet. TransientConeState
keeps those paths, keyed by the Git process id and its start time.
The manager removes the paths of a process that ended without a
narrow. It refuses a late widen for a command that already narrowed.

A widen writes the cone file, then runs "git sparse-checkout reapply"
with the virtual file system on. Thus the index has entries for the
new directories before Git runs. "git update-index
--force-write-index" does not do this. It collapses directories that
leave the cone, but it never expands a sparse-directory entry that
the cone now includes. With the virtual file system on, reapply
expands only those directories and keeps the skip-worktree bits. Its
post-index-change hook reports no change, so the projection stays
valid. "-c index.deleteSparseDirectories=false" stops Git from
deleting working-tree directories.

Only the Git process that holds the GVFS lock can widen. It waits in
its pre-command hook, so no other Git command writes the index. The
manager refuses a widen that makes Git check out a deleted file: when
reapply expands a directory, Git checks out each modified path that
is missing from the working directory. Git also reports success when
it cannot replace the index, so the mount checks that the index file
changed. If the apply fails, the manager restores the previous cone
file.

A narrow writes only the cone file. It arrives after the hook
released the GVFS lock, and the mount blocks a replacement of
.git\index while no Git command holds the lock. The index keeps the
expanded entries until the next widen collapses them.

The manager holds the lock file of Git's own sparse-checkout writers
while it changes the cone. It does not take the GVFS lock, because
the requesting Git command holds it.

Assisted-by: Claude Opus 5.5
Signed-off-by: Tyrie Vella <[email protected]>
When a user edits, creates, or deletes a file outside the sparse-index
cone without a Git command, GVFS records the path in the modified paths,
but the cone does not change. The directory of the file stays a
sparse-directory entry, so the index has no entry for the file, and the
virtual file system hook cannot clear its skip-worktree bit. Git then
does not see the change: "git status" does not list it, "git add ."
stops with "outside of your sparse-checkout definition", and
"git commit -a" leaves it out.

The file system callbacks now report each created, written, renamed,
or deleted path to the cone manager. When the applied cone does not
include the path, the callback creates the file .gvfs\ConeChangePending
and returns. It does not wait for a Git command. The pre-command hook
checks that file. If it exists, the hook sends a new ConeApply request
before Git reads the index. The mount applies the cone of all modified
paths, as for a widen, while the command holds the GVFS lock. A command
that reads the index without the lock (for example "git diff", or
"git status" with optional locks off) takes the lock for the apply and
releases it before Git runs. A failed apply keeps the change pending
for the next Git command.

The background task that adds a changed path to the modified paths
waits while a Git command holds the GVFS lock. A change that arrives
before its modified path therefore stays in the cone until the modified
paths have it, or until a check finds it clean.

The cone includes a modified file only while the file can differ from
HEAD. After a Git command releases the GVFS lock, and when changes
inside the cone stop for two seconds, the mount runs
"git status --porcelain=v2 --untracked-files=normal" on its own thread.
It writes a cone file without the modified files that Git does not list,
alone or in an untracked folder. Under a virtual file system, Git looks
for untracked files only in the paths that the mount reports. If another
process has the cone file open, the mount writes it again after the
delay, without Git. Git does not collapse the directories of clean files
while they are modified paths, because the virtual file system hook
clears their skip-worktree bits. The next change to such a file makes
the apply include it again.

When Git advertises "feature: vfs-sparse-index", it changes only the
index when the cone changes, so the mount does not refuse a widen that
expands the directory of a deleted file. The mount also skips the
sparse-directory probe for a deleted file or modified folder that the
applied cone already includes.

Assisted-by: Claude Opus 5.5
Signed-off-by: Tyrie Vella <[email protected]>
@tyrielv
Tyrie Vella (tyrielv) force-pushed the tyrielv/sparse-index/unstage-after-soft-reset branch from c97baa2 to 9379195 Compare November 18, 2026 16:25
With a sparse index, "git reset --soft" can stage a file that is inside
a sparse-directory entry. No file system write occurs, so no callback
adds the file to the modified paths. A later unstage of that file then
failed or hid the change:

- "git restore --staged -- <path>" failed with "pathspec did not match
  any file(s) known to git".
- "git restore --staged ." unstaged the file, but its index entry kept
  skip-worktree. "git status" and "git diff" did not show the change.
- "git reset" expanded the whole index.

The mount prepares an unstage with "git diff --cached <pathspec>", and
adds the staged files to the modified paths. Git does not match a
pathspec with a path inside a sparse-directory entry, so this query
found no file when the pre-command hook sent it before the widen. The
mount added nothing, and the index kept the file inside the
sparse-directory entry.

The pre-command hook now sends the widen before the unstage
preparation, so the named paths have index entries when the mount runs
"git diff --cached". The mount reports each staged file that it adds to
the modified paths to the working-tree change observer. If the cone
does not include the file, the observer makes a cone change pending,
and the hook applies it before Git runs. For an unstage command, the
hook stops the command when the widen times out or the apply fails,
because Git would otherwise hide the unstaged change.

A mixed "git reset" (not --patch) is now an unstage operation when GVFS
manages a sparse-index cone. ConeManagementHook.IsSparseIndexConeManaged
is the one gate for this and for the widen and narrow requests. With a
full index, Git prepares these files itself, so the hook does not send
the request.

The preparation writes the staged content of an added file only when
the file was not a modified path yet. Before, it also overwrote a file
that the user created, staged, and edited again, and so lost the
unstaged edit.

Assisted-by: Claude Opus 5.5
Signed-off-by: Tyrie Vella <[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.

1 participant