From a85950357d46a7d1fe4eea370175844cbd2070af Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Wed, 18 Nov 2026 13:37:01 -0800 Subject: [PATCH] Stop index-writing commands when the cone cannot be prepared With a sparse index, Git has no index entry for a file inside a directory that the sparse-checkout cone does not include. The pre-command hook asks the mount to widen the cone for the paths that a command names. It also asks the mount to apply the pending changes in the working tree. A request can fail, for example under load or after a mount timeout. Then the hook let Git run, and Git expanded the index in memory. That is not correct for commands that write the index. "git add", "rm", "mv", "checkout -- ", and "restore " check the paths against the sparse-checkout patterns and fail. "git stash", "add -u", "commit -a", "checkout ", "switch", "merge", "cherry-pick", "rebase", "revert", and "reset --keep" do not see a local change to a file outside the cone, and they report success. The stash saves nothing. The history commands move HEAD, and the file keeps the old content. Classify the commands in the pre-command hook. When a widen or an apply that the hook sent is not applied, stop a command that writes the index before Git runs. The message is "GVFS could not prepare the sparse index (: ). Run the command again." When the hook cannot read the cone file or the feature flag, it also stops the command. When it knows that GVFS does not manage the cone, it never stops a command. An unstage command also writes the index. It now stops for every failed widen as well, not only after a timeout, and before the unstage preparation runs. When the hook cannot check the pending-change marker, it counts the change as pending. Other commands run. When their apply failed, they can miss a change outside the cone, so the hook writes a warning to stderr. Before the hook stops a command after a reply timeout, it waits for the mount to finish the request. Otherwise the next Git command can start while the mount still writes the index. The mount now replies "NL" when the requesting Git process does not hold the GVFS lock, so that the message can name the lock. A widen reply "NE" (no cone management in the mount) no longer counts as a failure. The hook does not send a widen with more paths than the mount accepts, because the mount refuses it every time. For the functional tests, the mount reads a fault file that the GVFS_TEST_CONE_REQUEST_FAULT_FILE environment variable names. The mount refuses the widen and apply requests that the file lists. Without the variable, the mount reads no file. Assisted-by: Claude Opus 5.5 Signed-off-by: Tyrie Vella --- .../ConeManagementNamedPipeMessages.cs | 19 +- .../Sparse/AutoSparseIndexConeManager.cs | 82 ++-- .../Sparse/ConeRequestFaultInjection.cs | 142 +++++++ .../AutoSparseIndexConeTests.cs | 2 +- .../AutoSparseIndexFailClosedTests.cs | 381 ++++++++++++++++++ .../ConeManagementHookTests.cs | 8 +- GVFS/GVFS.Hooks/ConeCommandClassifier.cs | 310 ++++++++++++++ GVFS/GVFS.Hooks/ConeManagementHook.cs | 52 ++- GVFS/GVFS.Hooks/ConeRequestOutcome.cs | 10 + GVFS/GVFS.Hooks/PendingConeChangeHook.cs | 54 ++- GVFS/GVFS.Hooks/PreCommandConeRequests.cs | 212 ++++++++-- GVFS/GVFS.Hooks/Program.ConeManagement.cs | 70 +++- GVFS/GVFS.Hooks/Program.cs | 34 +- GVFS/GVFS.Mount/InProcessMount.cs | 37 +- .../Sparse/AutoSparseIndexConeManagerTests.cs | 37 +- .../Sparse/ConeRequestFaultInjectionTests.cs | 95 +++++ GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj | 3 + .../Hooks/ConeCommandClassifierTests.cs | 117 ++++++ .../Hooks/ConeManagementHookTests.cs | 49 ++- .../Hooks/PendingConeChangeHookTests.cs | 67 +++ .../Hooks/PreCommandConeRequestsTests.cs | 188 ++++++++- 21 files changed, 1833 insertions(+), 136 deletions(-) create mode 100644 GVFS/GVFS.Common/Sparse/ConeRequestFaultInjection.cs create mode 100644 GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexFailClosedTests.cs create mode 100644 GVFS/GVFS.Hooks/ConeCommandClassifier.cs create mode 100644 GVFS/GVFS.UnitTests/Common/Sparse/ConeRequestFaultInjectionTests.cs create mode 100644 GVFS/GVFS.UnitTests/Hooks/ConeCommandClassifierTests.cs diff --git a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs index 2a233ccac..0bde9470c 100644 --- a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs +++ b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs @@ -15,11 +15,13 @@ public static partial class NamedPipeMessages /// CommandId after Git runs, so that the mount can remove the cone entries that /// it added for that command. /// - /// The hook treats every reply other than as "not applied" - /// and lets Git run. This includes and + /// The hook treats every reply other than as "not applied". + /// This includes , , /// , from an older mount that /// does not handle these messages, , no reply within the - /// wait budget, and no mount. Git then expands the sparse index in memory. + /// wait budget, and no mount. For a read-only command, Git then runs and expands the + /// sparse index in memory. A command that writes the index stops before Git runs when a + /// widen or an apply that it sent is not applied, unless the feature is off. /// /// /// A widen request carries only repo-relative git-form paths that the hook resolved @@ -63,10 +65,17 @@ public static class ConeManagement /// The mount received the request, but automatic sparse index is not enabled. public const string NotEnabledResult = "NE"; + /// + /// The mount did not apply a widen or an apply, because the requesting Git process + /// does not hold the GVFS lock. A hook that does not know this result treats it as + /// . + /// + public const string NotLockHolderResult = "NL"; + /// /// The time that the pre-command hook allows to connect and send a widen request. If - /// the hook cannot send the request in this time, it lets Git run, and it does not - /// send the request. + /// the hook cannot send the request in this time, it does not send the request, and + /// the widen fails (see PreCommandConeRequests in the hooks). /// public const int WidenWaitBudgetMs = 1000; diff --git a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs index a9efb0c56..c36a2555d 100644 --- a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs +++ b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs @@ -48,8 +48,11 @@ namespace GVFS.Common.Sparse /// does not change. Only a dehydrate (see below) can make the manager invalidate it. /// /// - /// Every failure lets Git run, because the hook treats any reply other than success as - /// "not applied". Git then expands the index in memory, which is slower but correct. + /// A failure does not change the cone or the index. The hook then lets a read-only command + /// run, and Git expands the index in memory. Git then reads a path without a local change + /// correctly, but it can miss a local change outside the cone, so the hook warns. The hook + /// stops a command that writes the index before Git runs (see PreCommandConeRequests + /// in the hooks). /// /// /// Working-tree changes: Git sees a change to a file only when the index has an entry for @@ -102,7 +105,7 @@ namespace GVFS.Common.Sparse /// public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver { - /// A widen with more paths is refused, and Git expands the index in memory. + /// A widen with more paths is refused. The hook does not send such a widen. public const int MaxWidenPaths = 1000; /// @@ -159,10 +162,10 @@ public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver private const string ReconcileEventName = "ConeReconcile"; private const int MaxTracedPaths = 10; - // A widen that waited longer than this for earlier requests does not start Git. Git then - // expands the index in memory. This keeps a widen far inside the hook's reply ceiling - // (WidenReplyCeilingMs), after which Git runs while the child Git process can still - // hold the index lock. + // A widen that waited longer than this for earlier requests does not start Git, and the + // hook gets a failure (see PreCommandConeRequests). This keeps a widen far inside the + // hook's reply ceiling (WidenReplyCeilingMs), after which the hook stops waiting while + // the child Git process can still hold the index lock. private const int MaxQueueWaitBeforeApplyMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs / 2; // A check that cannot write the cone file tries again after the change-check delay, at @@ -342,7 +345,6 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t return NamedPipeMessages.ConeManagement.NotEnabledResult; } - bool succeeded; switch (message.Header) { case NamedPipeMessages.ConeManagement.WidenRequest: @@ -352,8 +354,7 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t return NamedPipeMessages.ConeManagement.FailureResult; } - succeeded = manager.TryWiden(widen); - break; + return ToReply(manager.HandleWiden(widen)); case NamedPipeMessages.ConeManagement.NarrowRequest: if (!NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.NarrowParameters narrow)) @@ -362,8 +363,7 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t return NamedPipeMessages.ConeManagement.FailureResult; } - succeeded = manager.TryNarrow(narrow); - break; + return manager.TryNarrow(narrow) ? NamedPipeMessages.ConeManagement.SuccessResult : NamedPipeMessages.ConeManagement.FailureResult; case NamedPipeMessages.ConeManagement.ApplyRequest: if (!NamedPipeMessages.ConeManagement.ApplyParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.ApplyParameters apply)) @@ -372,14 +372,11 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t return NamedPipeMessages.ConeManagement.FailureResult; } - succeeded = manager.TryApply(apply); - break; + return ToReply(manager.HandleApply(apply)); default: throw new ArgumentException($"'{message.Header}' is not a cone request.", nameof(message)); } - - return succeeded ? NamedPipeMessages.ConeManagement.SuccessResult : NamedPipeMessages.ConeManagement.FailureResult; } /// @@ -387,7 +384,45 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t /// the result before Git runs. The cone also gets every pending working-tree change. /// /// True when the cone and the index include the paths. - public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters) + internal bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters) + { + return IsApplied(this.HandleWiden(parameters)); + } + + /// + /// Apply the pending working-tree changes to the cone and the index before a Git command + /// reads the index. The hook waits for the result before Git runs. + /// + /// True when the cone and the index include every pending change. + internal bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters) + { + return IsApplied(this.HandleApply(parameters)); + } + + private static bool IsApplied(ConeChange change) + { + return change == ConeChange.Applied || change == ConeChange.ConeUnchanged; + } + + /// + /// Return the reply to a widen or an apply. A hook stops a command that writes the index + /// when the reply is not , and + /// lets it tell the + /// user that another Git command holds the GVFS lock. + /// + private static string ToReply(ConeChange change) + { + if (IsApplied(change)) + { + return NamedPipeMessages.ConeManagement.SuccessResult; + } + + return change == ConeChange.NotLockHolder + ? NamedPipeMessages.ConeManagement.NotLockHolderResult + : NamedPipeMessages.ConeManagement.FailureResult; + } + + private ConeChange HandleWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters) { ArgumentNullException.ThrowIfNull(parameters); @@ -398,20 +433,14 @@ public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters ApplyAttempt attempt = new ApplyAttempt(); ConeChange change = this.RunAndCatch(() => this.Widen(parameters, attempt, stopwatch, metadata), metadata); this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: true, metadata); - bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged; // A widen slower than WidenWaitBudgetMs is a warning. The hook waits for the reply up // to WidenReplyCeilingMs, so the user's Git command waits for the widen. this.TraceResult(WidenEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.WidenWaitBudgetMs, metadata); - return succeeded; + return change; } - /// - /// Apply the pending working-tree changes to the cone and the index before a Git command - /// reads the index. The hook waits for the result before Git runs. - /// - /// True when the cone and the index include every pending change. - public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters) + private ConeChange HandleApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters) { ArgumentNullException.ThrowIfNull(parameters); @@ -425,10 +454,9 @@ public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters : ConeChange.NoCommandId, metadata); this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: false, metadata); - bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged; this.TraceResult(ApplyEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs, metadata); - return succeeded; + return change; } /// diff --git a/GVFS/GVFS.Common/Sparse/ConeRequestFaultInjection.cs b/GVFS/GVFS.Common/Sparse/ConeRequestFaultInjection.cs new file mode 100644 index 000000000..a17ce4529 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConeRequestFaultInjection.cs @@ -0,0 +1,142 @@ +using GVFS.Common.NamedPipes; +using System; +using System.Collections.Generic; +using System.IO; + +namespace GVFS.Common.Sparse +{ + /// + /// Test only: makes the mount refuse cone widen and apply requests, so that the functional + /// tests can check what the hooks do when the mount cannot prepare the sparse index. + /// + /// + /// The mount reads the environment variable once, + /// when it starts. Only the functional tests set it. When it is not set, this class does + /// nothing and the mount reads no file. + /// + /// When it is set, the mount reads the named file at each widen and apply request, so that a + /// test can add and remove a fault while the mount runs. Each line of the file has a request + /// header ( or + /// ), a space, and the reply + /// ( or + /// ). The mount sends that + /// reply and does not change the cone or the index. A missing file means no fault. + /// + /// + public sealed class ConeRequestFaultInjection + { + /// The environment variable that names the fault file. Test only. + public const string FaultFileEnvironmentVariable = "GVFS_TEST_CONE_REQUEST_FAULT_FILE"; + + // A fault file is a few short lines. A larger file is not a fault file. + private const int MaxFaultFileBytes = 4096; + + private readonly string faultFilePath; + private readonly Func readFile; + + private ConeRequestFaultInjection(string faultFilePath, Func readFile) + { + this.faultFilePath = faultFilePath; + this.readFile = readFile; + } + + /// The path of the fault file. + public string FaultFilePath => this.faultFilePath; + + /// + /// Return the fault injection that configures, or + /// null when the variable is not set. + /// + /// Reads an environment variable. + /// Returns the content of a file, or null when it does not exist. + public static ConeRequestFaultInjection FromEnvironment(Func getEnvironmentVariable, Func readFile = null) + { + ArgumentNullException.ThrowIfNull(getEnvironmentVariable); + + string path = getEnvironmentVariable(FaultFileEnvironmentVariable); + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + + return new ConeRequestFaultInjection(path, readFile ?? ReadSmallFile); + } + + /// + /// Return the reply that the fault file sets for , or null + /// when the mount must handle the request. Never throws. + /// + public string GetForcedReply(string requestHeader) + { + if (requestHeader != NamedPipeMessages.ConeManagement.WidenRequest && + requestHeader != NamedPipeMessages.ConeManagement.ApplyRequest) + { + return null; + } + + string content; + try + { + content = this.readFile(this.faultFilePath); + } + catch (Exception e) when (!(e is OutOfMemoryException)) + { + // A fault file that cannot be read, or a path that is not valid, means no fault. + return null; + } + + return content == null ? null : ParseFaults(content).GetValueOrDefault(requestHeader); + } + + /// + /// Parse the content of a fault file. Lines that are not valid are ignored. + /// + internal static Dictionary ParseFaults(string content) + { + Dictionary faults = new Dictionary(StringComparer.Ordinal); + foreach (string rawLine in content.Split('\n')) + { + string[] fields = rawLine.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (fields.Length != 2) + { + continue; + } + + bool isRequest = fields[0] == NamedPipeMessages.ConeManagement.WidenRequest || + fields[0] == NamedPipeMessages.ConeManagement.ApplyRequest; + bool isReply = fields[1] == NamedPipeMessages.ConeManagement.FailureResult || + fields[1] == NamedPipeMessages.ConeManagement.NotLockHolderResult; + if (isRequest && isReply) + { + faults[fields[0]] = fields[1]; + } + } + + return faults; + } + + private static string ReadSmallFile(string path) + { + FileInfo file = new FileInfo(path); + if (!file.Exists || (file.Attributes & (FileAttributes.ReparsePoint | FileAttributes.Device)) != 0) + { + return null; + } + + // Read at most one byte more than the limit, so that a file that grows after the + // check cannot make the read unbounded. + using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + byte[] buffer = new byte[MaxFaultFileBytes + 1]; + int length = 0; + int read; + while (length < buffer.Length && (read = stream.Read(buffer, length, buffer.Length - length)) > 0) + { + length += read; + } + + return length > MaxFaultFileBytes ? null : System.Text.Encoding.UTF8.GetString(buffer, 0, length); + } + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs index 3d168d364..a4695422f 100644 --- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs @@ -125,7 +125,7 @@ public void UnlockedCommandDoesNotChangeTheCone() ProcessResult diff = this.GitWithTrace($"diff --stat -- {file}", out _); diff.ExitCode.ShouldEqual(0, diff.Errors); - diff.Errors.ShouldContain(HookFailurePrefix + ": Rejected"); + diff.Errors.ShouldContain(HookFailurePrefix + ": NotLockHolder"); this.ReadConeFile().ShouldEqual(coneBefore); } diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexFailClosedTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexFailClosedTests.cs new file mode 100644 index 000000000..022744b95 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexFailClosedTests.cs @@ -0,0 +1,381 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Functional tests for commands that write the index when the mount cannot widen the + /// sparse-index cone or apply a pending working-tree change. Without the cone change, Git has + /// no index entry for a file outside the cone: it fails, or it does not see a local change + /// and reports success. The pre-command hook must stop such a command before Git runs, and + /// let other commands run with a warning. + /// + /// + /// The fixture mounts with the test-only fault file of the mount (see + /// ConeRequestFaultInjection), so that a test can make the mount refuse a request. + /// + [TestFixture] + public class AutoSparseIndexFailClosedTests : AutoSparseIndexTestsBase + { + private const string FaultFileEnvironmentVariable = "GVFS_TEST_CONE_REQUEST_FAULT_FILE"; + private const string RefuseWidenAndApply = "ConeWiden F\nConeApply F\n"; + private const string RefuseApplyAsNotLockHolder = "ConeApply NL\n"; + private const string StoppedMessage = "GVFS could not prepare the sparse index"; + private const string UnstageStoppedMessage = "VFS for Git could not add the staged files to the sparse-index cone"; + private const string StaleIndexWarning = "GVFS: the sparse index is not up to date (apply: Rejected); this command can miss changes outside the sparse-checkout cone. Run it again."; + private const string LocalChange = "local change outside the cone"; + private const string ConeChangePendingFile = "ConeChangePending"; + + // The test cases of this fixture take this many files. + private const int FilesUsed = 28; + + // Git refuses a command that would overwrite a local change with one of these messages. + private static readonly string[] LocalChangeRefusals = + { + "would be overwritten", + "You have unstaged changes", + "not uptodate", + }; + + // Files of HEAD, each in a different leaf directory outside the root-only cone + private Queue unusedFiles; + private string faultFile; + private string startBranch; + private string startCommit; + private int branchCount; + + [OneTimeSetUp] + public void MountWithTheFaultFile() + { + List> parents = this.DeepHeadFiles + .GroupBy(path => ParentDirectory(path), StringComparer.OrdinalIgnoreCase) + .ToList(); + this.unusedFiles = new Queue(parents + .Where(group => !parents.Any(other => other.Key.StartsWith(group.Key + "/", StringComparison.OrdinalIgnoreCase))) + .Select(group => group.First())); + this.unusedFiles.Count.ShouldBeAtLeast(FilesUsed, "HEAD has too few leaf directories"); + + this.faultFile = Path.Combine(this.Enlistment.EnlistmentRoot, "cone-request-faults.txt"); + this.SetFaults(string.Empty); + + // The mount reads the variable when it starts. + Environment.SetEnvironmentVariable(FaultFileEnvironmentVariable, this.faultFile); + try + { + this.Enlistment.UnmountGVFS(); + this.Enlistment.MountGVFS(); + } + finally + { + Environment.SetEnvironmentVariable(FaultFileEnvironmentVariable, null); + } + + this.startBranch = this.GitShouldSucceed("rev-parse --abbrev-ref HEAD").Trim(); + this.startCommit = this.GitShouldSucceed("rev-parse HEAD").Trim(); + } + + [TearDown] + public void ResetToTheStart() + { + this.SetFaults(string.Empty); + this.GitShouldSucceed("reset --hard --quiet"); + this.GitShouldSucceed("checkout -q -f " + this.startBranch); + this.GitShouldSucceed("reset --hard --quiet " + this.startCommit); + this.GitShouldSucceed("stash clear"); + } + + [TestCase("add -- {0}", "widen", "staged")] + [TestCase("add .", "apply", "staged")] + [TestCase("add -A", "apply", "staged")] + [TestCase("add -u", "apply", "staged")] + [TestCase("rm --cached -q -- {0}", "widen", "removed")] + [TestCase("commit -a -m \"Edited outside the cone\"", "apply", "committed")] + [TestCase("commit -m \"Edited outside the cone\" -- {0}", "widen", "committed")] + [TestCase("stash", "apply", "stashed")] + [TestCase("stash push -- {0}", "apply", "stashed")] + [TestCase("checkout -- {0}", "widen", "discarded")] + [TestCase("restore -- {0}", "widen", "discarded")] + public void WorkingTreeCommandStopsAndRunsAfterTheFaultIsGone(string commandFormat, string request, string effect) + { + string file = this.unusedFiles.Dequeue(); + string command = string.Format(commandFormat, file); + this.EditWhileTheMountRefuses(file, RefuseWidenAndApply); + + this.ShouldStopBeforeGitRuns(command, $"{StoppedMessage} ({request}: Rejected). Run the command again.", file); + + this.SetFaults(string.Empty); + ProcessResult retry = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + retry.ExitCode.ShouldEqual(0, $"git {command} failed after the fault was removed: {retry.Output} {retry.Errors}"); + switch (effect) + { + case "staged": + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(file); + break; + + case "removed": + this.GitShouldSucceed("diff --cached --name-status").ShouldContain("D\t" + file); + break; + + case "committed": + this.GitShouldSucceed("diff --name-only HEAD~1 HEAD").ShouldContain(file); + break; + + case "stashed": + this.GitShouldSucceed("stash show --name-only").ShouldContain(file); + this.HasLocalChange(file).ShouldBeFalse(); + break; + + case "discarded": + this.HasLocalChange(file).ShouldBeFalse(); + break; + + default: + Assert.Fail("Unknown effect " + effect); + break; + } + } + + [TestCase("restore --staged -- {0}", false)] + [TestCase("checkout HEAD -- {0}", true)] + public void UnstageCommandStopsForAFailedWidenAndRunsAfterTheFaultIsGone(string commandFormat, bool discardsTheChange) + { + // An unstage writes the index, so a failed widen stops it, as it stops a command that + // writes the index. + string file = this.unusedFiles.Dequeue(); + string command = string.Format(commandFormat, file); + this.EditWhileTheMountRefuses(file, RefuseWidenAndApply); + + this.ShouldStopBeforeGitRuns(command, UnstageStoppedMessage + " (widen: Rejected).", file); + + this.SetFaults(string.Empty); + ProcessResult retry = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + retry.ExitCode.ShouldEqual(0, $"git {command} failed after the fault was removed: {retry.Output} {retry.Errors}"); + this.HasLocalChange(file).ShouldEqual(!discardsTheChange); + this.GitShouldSucceed("diff --cached --name-only").ShouldNotContain(ignoreCase: true, file); + } + [TestCase("checkout -q {0}")] + [TestCase("switch -q {0}")] + [TestCase("merge --no-edit {0}")] + [TestCase("cherry-pick {0}")] + [TestCase("rebase {0}")] + [TestCase("reset -q --keep {0}")] + public void HistoryCommandStopsAndGitRefusesAfterTheFaultIsGone(string commandFormat) + { + // A branch changes the file, and the file has a local change. Git must refuse to + // move HEAD, because it would leave the file without the change of the branch. + string file = this.unusedFiles.Dequeue(); + string command = string.Format(commandFormat, this.CreateBranchThatChanges(file)); + this.EditWhileTheMountRefuses(file, RefuseWidenAndApply); + + this.ShouldStopBeforeGitRuns(command, StoppedMessage + " (apply: Rejected). Run the command again.", file); + this.GitShouldRefuseAfterTheFaultIsGone(command, file); + } + + [TestCase] + public void RevertStopsAndGitRefusesAfterTheFaultIsGone() + { + // HEAD changes the file, and the file has a local change that the revert would lose. + string file = this.unusedFiles.Dequeue(); + this.GitShouldSucceed("checkout -q " + this.CreateBranchThatChanges(file)); + this.EditWhileTheMountRefuses(file, RefuseWidenAndApply); + + this.ShouldStopBeforeGitRuns("revert --no-edit HEAD", StoppedMessage + " (apply: Rejected). Run the command again.", file); + this.GitShouldRefuseAfterTheFaultIsGone("revert --no-edit HEAD", file); + } + + [TestCase] + public void StopMessageNamesTheGVFSLock() + { + string file = this.unusedFiles.Dequeue(); + this.EditWhileTheMountRefuses(file, RefuseApplyAsNotLockHolder); + + this.ShouldStopBeforeGitRuns( + "commit -a -m \"Edited outside the cone\"", + StoppedMessage + " (apply: NotLockHolder).", + file, + "This Git command does not hold the GVFS lock."); + } + + [TestCase("status --porcelain", true)] + [TestCase("diff --name-only", true)] + [TestCase("diff --cached --name-only", true)] + [TestCase("ls-files -- {0}", true)] + [TestCase("blame -- {0}", true)] + [TestCase("log -1 -p -- {0}", false)] + public void ReadOnlyCommandRunsWithAWarningWhenTheApplyFails(string commandFormat, bool sendsAnApply) + { + // "git log" does not read the index, so the hook does not apply the change for it. + string file = this.unusedFiles.Dequeue(); + string command = string.Format(commandFormat, file); + this.EditWhileTheMountRefuses(file, RefuseWidenAndApply); + + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Output} {result.Errors}"); + result.Output.ShouldNotContain(ignoreCase: false, StoppedMessage); + if (sendsAnApply) + { + result.Errors.ShouldContain(StaleIndexWarning); + } + else + { + result.Errors.ShouldNotContain(ignoreCase: false, StaleIndexWarning); + } + + this.ConeChangeIsPending().ShouldBeTrue("the refused apply must keep the change pending"); + this.HasLocalChange(file).ShouldBeTrue(); + } + + [TestCase] + public void CommitOfTheStagedFilesOnlyRunsWithAWarningWhenTheApplyFails() + { + // The commit does not read the local change, so the hook lets it run. + string stagedFile = $"fail-closed-staged-{this.branchCount++}.txt"; + File.WriteAllText(this.Enlistment.GetVirtualPathTo(stagedFile), "staged\n"); + this.GitShouldSucceed("add -- " + stagedFile); + string file = this.unusedFiles.Dequeue(); + this.EditWhileTheMountRefuses(file, RefuseWidenAndApply); + + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "commit -m \"Staged files only\""); + + result.ExitCode.ShouldEqual(0, $"git commit failed: {result.Output} {result.Errors}"); + result.Errors.ShouldContain(StaleIndexWarning); + string committed = this.GitShouldSucceed("diff --name-only HEAD~1 HEAD"); + committed.ShouldContain(stagedFile); + committed.ShouldNotContain(ignoreCase: true, file); + this.HasLocalChange(file).ShouldBeTrue(); + } + + private static string Sha256(string path) + { + using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + return Convert.ToHexString(SHA256.HashData(stream)); + } + } + + /// + /// Make the mount refuse requests as says, then edit + /// and wait until the mount makes the cone change pending. The + /// fault comes first, so that no other Git command applies the change. + /// + private void EditWhileTheMountRefuses(string file, string faults) + { + this.SetFaults(faults); + File.AppendAllText(this.Enlistment.GetVirtualPathTo(file), LocalChange + "\n"); + + Stopwatch stopwatch = Stopwatch.StartNew(); + while (!this.ConeChangeIsPending() && stopwatch.ElapsedMilliseconds < 10000) + { + System.Threading.Thread.Sleep(50); + } + + this.ConeChangeIsPending().ShouldBeTrue("the mount did not make the cone change pending"); + } + + /// + /// Run while the fault file refuses requests, and check that the + /// hook stopped it before Git ran. + /// + private void ShouldStopBeforeGitRuns(string command, string expectedMessage, string changedFile, string expectedSecondLine = null) + { + string indexPath = this.Enlistment.GetDotGitPath("index"); + string head = this.GitShouldSucceed("rev-parse HEAD").Trim(); + string stashes = this.GitShouldSucceed("stash list"); + string indexBefore = Sha256(indexPath); + + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + + string output = result.Output + result.Errors; + result.ExitCode.ShouldNotEqual(0, $"git {command} was not stopped: {output}"); + output.ShouldContain(expectedMessage); + if (expectedSecondLine != null) + { + output.ShouldContain(expectedSecondLine); + } + + // Git did not run: no index lock, the same index, HEAD, stashes, and working tree. + File.Exists(indexPath + ".lock").ShouldBeFalse("git left an index lock"); + Sha256(indexPath).ShouldEqual(indexBefore, "the index changed"); + this.GitShouldSucceed("rev-parse HEAD").Trim().ShouldEqual(head); + this.GitShouldSucceed("stash list").ShouldEqual(stashes); + this.HasLocalChange(changedFile).ShouldBeTrue(); + } + + /// + /// Remove the fault, run again, and check that Git (not the + /// hook) refused it because of the local change. + /// + private void GitShouldRefuseAfterTheFaultIsGone(string command, string changedFile) + { + string head = this.GitShouldSucceed("rev-parse HEAD").Trim(); + this.SetFaults(string.Empty); + + ProcessResult retry = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + + string output = retry.Output + retry.Errors; + retry.ExitCode.ShouldNotEqual(0, $"git {command} did not see the local change: {output}"); + output.ShouldNotContain(ignoreCase: false, StoppedMessage); + LocalChangeRefusals.Any(refusal => output.Contains(refusal)).ShouldBeTrue($"git {command} failed for another reason: {output}"); + this.GitShouldSucceed("rev-parse HEAD").Trim().ShouldEqual(head); + this.HasLocalChange(changedFile).ShouldBeTrue(); + } + + private bool ConeChangeIsPending() + { + return File.Exists(Path.Combine(this.Enlistment.DotGVFSRoot, ConeChangePendingFile)); + } + + private void SetFaults(string faults) + { + File.WriteAllText(this.faultFile, faults); + } + + private bool HasLocalChange(string file) + { + return File.ReadAllText(this.Enlistment.GetVirtualPathTo(file)).Contains(LocalChange); + } + + /// + /// Create a branch with a commit on top of HEAD that changes . The + /// commit is made in a temporary index, so the working tree does not change. + /// + private string CreateBranchThatChanges(string file) + { + string changedContent = this.GitShouldSucceed("cat-file blob HEAD:" + file) + "changed by a commit\n"; + ProcessResult hash = GitProcess.InvokeProcess( + this.Enlistment.RepoRoot, + "hash-object -w --stdin", + inputStream: new MemoryStream(Encoding.UTF8.GetBytes(changedContent))); + hash.ExitCode.ShouldEqual(0, hash.Errors); + + string temporaryIndex = Path.Combine(this.Enlistment.EnlistmentRoot, $"fail-closed-test-index-{this.branchCount}"); + Dictionary environment = new Dictionary { { "GIT_INDEX_FILE", temporaryIndex } }; + string plainIndex = $"{BypassGVFS} -c index.sparse=false -c core.sparseCheckout=false"; + this.GitShouldSucceed(environment, $"{plainIndex} read-tree HEAD"); + this.GitShouldSucceed(environment, $"{plainIndex} update-index --cacheinfo 100644,{hash.Output.Trim()},{file}"); + string tree = this.GitShouldSucceed(environment, $"{plainIndex} write-tree").Trim(); + File.Delete(temporaryIndex); + + string commit = this.GitShouldSucceed($"commit-tree {tree} -p HEAD -m \"Change {file}\"").Trim(); + string branch = $"tests/functional/fail-closed-{this.branchCount++}"; + this.GitShouldSucceed($"branch {branch} {commit}"); + return branch; + } + + private string GitShouldSucceed(Dictionary environment, string command) + { + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output; + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs index 4812d57e3..77fd46ca3 100644 --- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs @@ -57,9 +57,11 @@ public void GitRunsWhenTheMountRepliesNotEnabled() "add " + Path.GetFileName(OutOfConeFile), TraceEnvironment); outOfCone.ExitCode.ShouldEqual(0, outOfCone.Errors); - outOfCone.Errors.ShouldContain( - "gvfs cone-management: widen not applied: Rejected", - "gvfs cone-management: narrow not applied: Rejected"); + outOfCone.Errors.ShouldNotContain( + ignoreCase: false, + "gvfs cone-management: widen not applied", + "gvfs cone-management: narrow not applied", + "GVFS could not prepare the sparse index"); GitProcess.Invoke(this.Enlistment.RepoRoot, "diff --cached --name-only") .ShouldContain(InConeFile, OutOfConeFile); diff --git a/GVFS/GVFS.Hooks/ConeCommandClassifier.cs b/GVFS/GVFS.Hooks/ConeCommandClassifier.cs new file mode 100644 index 000000000..93b8dd958 --- /dev/null +++ b/GVFS/GVFS.Hooks/ConeCommandClassifier.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GVFS.Hooks +{ + /// + /// What a failed cone request means for a Git command (see ). + /// + internal enum ConeCommandKind + { + /// + /// The command does not write the index from working-tree changes, or it is plumbing. A + /// failed request only makes Git slower, so Git always runs. + /// + Other, + + /// + /// The command writes the index, and it is wrong when the cone does not include the paths + /// that it names or the working-tree changes that it reads. When a request fails, the hook + /// stops the command before Git runs. + /// + WritesIndex, + + /// + /// The command unstages files (see ). + /// + Unstage, + } + + /// + /// Classifies a Git command for the pre-command cone requests. + /// + /// + /// With a sparse index, Git has no index entry for a file inside a directory that the cone + /// does not include. When the mount could not widen the cone or apply a pending change, the + /// commands below then fail (for example git add reports that the path is outside the + /// sparse-checkout definition), or they run without the change and report success (for + /// example git stash, git commit -a, and git checkout <branch> do + /// not see a local change to such a file). Read-only commands and plumbing run. They do not + /// change the index from the working tree, and the hook warns when they can miss a change. + /// + internal static class ConeCommandClassifier + { + /// The Git command, in lowercase, without a "git-" prefix. + /// The hook arguments: the hook type, the command, and the command's arguments. + /// Returns true when GVFS manages a sparse-index cone. + public static ConeCommandKind Classify(string command, string[] args, Func isSparseIndexConeManaged) + { + ArgumentNullException.ThrowIfNull(args); + + switch (command) + { + case "restore": + case "checkout": + case "reset": + if (UnstageCommandParser.ShouldPrepareForUnstage(command, args, isSparseIndexConeManaged)) + { + return ConeCommandKind.Unstage; + } + + break; + } + + return WritesIndex(command, args) ? ConeCommandKind.WritesIndex : ConeCommandKind.Other; + } + + private static bool WritesIndex(string command, string[] args) + { + switch (command) + { + case "add": + case "am": + case "checkout": + case "cherry-pick": + case "merge": + case "mv": + case "pull": + case "rebase": + case "restore": + case "revert": + case "rm": + case "stage": + case "switch": + return true; + + case "apply": + return ApplyWritesTheIndex(args); + + case "commit": + return CommitReadsTheWorkingTree(args); + + case "reset": + // A mixed reset is an unstage command. A soft reset changes neither the index + // nor the working tree. + return HasOption(args, "--hard", "--merge", "--keep"); + + case "stash": + return StashReadsOrWritesTheWorkingTree(args); + + default: + return false; + } + } + + /// + /// Return true when git apply uses the index (--index, --cached, or + /// --3way) and applies the patch. With --check, --stat, + /// --numstat, or --summary, and without --apply, it only reads. + /// + private static bool ApplyWritesTheIndex(string[] args) + { + if (!HasOption(args, "--index", "--cached", "--3way") && !HasShortOption(args, '3', valueOptions: "pC")) + { + return false; + } + + return HasOption(args, "--apply") || !HasOption(args, "--check", "--stat", "--numstat", "--summary"); + } + + /// + /// Return true unless the stash subcommand only reads or changes the stash list + /// (list, show, drop, clear, store). A stash without a + /// subcommand, or with -- before the first argument, is stash push. + /// + private static bool StashReadsOrWritesTheWorkingTree(string[] args) + { + string subcommand = null; + bool skipNext = false; + foreach (string arg in UserArguments(args)) + { + if (skipNext) + { + skipNext = false; + continue; + } + + if (arg == "--") + { + break; + } + + if (!arg.StartsWith("-", StringComparison.Ordinal)) + { + subcommand = arg; + break; + } + + // The message of an implicit "stash push". + skipNext = arg == "-m" || arg == "--message"; + } + + switch (subcommand) + { + case "list": + case "show": + case "drop": + case "clear": + case "store": + return false; + + default: + return true; + } + } + + /// + /// Return true when a commit takes files from the working tree: -a/--all, + /// -i/--include, -o/--only, -p/--patch, + /// --interactive, --pathspec-from-file, or paths. A commit of the staged + /// files only does not read a change that is not staged. Abbreviated long options are not + /// recognized. + /// + private static bool CommitReadsTheWorkingTree(string[] args) + { + bool pastDashDash = false; + bool skipNext = false; + foreach (string arg in UserArguments(args)) + { + if (skipNext) + { + skipNext = false; + continue; + } + + if (pastDashDash) + { + return true; + } + + if (arg == "--") + { + pastDashDash = true; + continue; + } + + if (arg.StartsWith("--", StringComparison.Ordinal)) + { + string option = arg.Split('=')[0]; + switch (option) + { + case "--all": + case "--include": + case "--only": + case "--patch": + case "--interactive": + case "--pathspec-from-file": + return true; + + case "--message": + case "--file": + case "--reuse-message": + case "--reedit-message": + case "--template": + case "--author": + case "--date": + case "--fixup": + case "--squash": + case "--trailer": + case "--cleanup": + skipNext = !arg.Contains('='); + break; + } + + continue; + } + + if (arg.StartsWith("-", StringComparison.Ordinal) && arg.Length > 1) + { + if (ShortClusterHas(arg, "aiop", valueOptions: "mFcCt", attachedValueOptions: "Su", out skipNext)) + { + return true; + } + + continue; + } + + return true; + } + + return false; + } + + /// + /// Return true when the cluster of short options (for example + /// -qam) has one of . The rest of the cluster after a letter + /// in or is the + /// value of that option, not more options. + /// + /// Options that take a value, attached or in the next argument. + /// Options that take an optional value, which must be attached. + /// True when the value of the last option is the next argument. + private static bool ShortClusterHas(string arg, string flags, string valueOptions, string attachedValueOptions, out bool valueInNextArgument) + { + valueInNextArgument = false; + for (int i = 1; i < arg.Length; i++) + { + char option = arg[i]; + if (flags.IndexOf(option) >= 0) + { + return true; + } + + if (valueOptions.IndexOf(option) >= 0) + { + valueInNextArgument = i == arg.Length - 1; + return false; + } + + if (attachedValueOptions.IndexOf(option) >= 0) + { + return false; + } + } + + return false; + } + + private static bool HasShortOption(string[] args, char flag, string valueOptions) + { + bool skipNext = false; + foreach (string arg in UserArguments(args).TakeWhile(arg => arg != "--")) + { + if (skipNext) + { + skipNext = false; + continue; + } + + if (arg.Length > 1 && arg[0] == '-' && arg[1] != '-' && + ShortClusterHas(arg, flag.ToString(), valueOptions, attachedValueOptions: string.Empty, out skipNext)) + { + return true; + } + } + + return false; + } + + private static bool HasOption(string[] args, params string[] options) + { + return UserArguments(args).TakeWhile(arg => arg != "--").Any(arg => options.Contains(arg.Split('=')[0])); + } + + private static IEnumerable UserArguments(string[] args) + { + return args.Skip(2).Where(arg => arg != null && !arg.StartsWith("--git-pid=", StringComparison.Ordinal)); + } + } +} diff --git a/GVFS/GVFS.Hooks/ConeManagementHook.cs b/GVFS/GVFS.Hooks/ConeManagementHook.cs index 46545aa6b..67b1088ec 100644 --- a/GVFS/GVFS.Hooks/ConeManagementHook.cs +++ b/GVFS/GVFS.Hooks/ConeManagementHook.cs @@ -17,9 +17,11 @@ namespace GVFS.Hooks /// runs. Otherwise Git expands the whole sparse index in memory to find those paths. /// The post-command hook asks the mount to narrow the cone again. /// - /// Cone management must never fail a Git command. Every failure, including no mount, a - /// mount that does not know the request, a slow mount, and an exception, lets Git run. - /// Git is then slower, but correct. The hook waits at most + /// This class never fails a Git command itself. Every failure, including no mount, a mount + /// that does not know the request, a slow mount, and an exception, gives an outcome, and + /// decides with it: a command that writes the index + /// stops before Git runs, and other commands run (Git is then slower, but correct). + /// The hook waits at most /// to connect and send /// a widen. After it sent a widen, it waits for the reply, at most /// : the mount applies @@ -88,6 +90,12 @@ public ConeManagementHook( /// The value of the feature flag. internal delegate bool ReadSparseIndexConfig(out bool ignoreCase); + /// + /// The widen that the hook sent and stopped waiting for (), + /// or null. The mount can still run Git for it. + /// + public Task AbandonedRequest { get; private set; } + /// /// If the command names paths outside the cone, ask the mount to widen the cone. Never /// throws. @@ -273,6 +281,13 @@ private ConeRequestOutcome Widen(string[] args, int waitBudgetMs, int replyCeili } } + // The mount refuses such a widen every time, so the hook does not send it (see + // PreCommandConeRequests.WidenLeavesNoGap). + if (paths.Count > AutoSparseIndexConeManager.MaxWidenPaths) + { + return ConeRequestOutcome.TooManyPaths; + } + NamedPipeMessages.ConeManagement.WidenParameters parameters = new NamedPipeMessages.ConeManagement.WidenParameters(GetCommandId(args), paths); @@ -325,6 +340,7 @@ private void TraceOutcome(string request, ConeRequestOutcome outcome) case ConeRequestOutcome.SkippedStash: case ConeRequestOutcome.SkippedInCone: case ConeRequestOutcome.NoResolvablePaths: + case ConeRequestOutcome.TooManyPaths: this.trace($"{request} skipped: {outcome}"); break; @@ -363,8 +379,8 @@ private ConeRequestOutcome SendBounded(string header, string body, int waitBudge return ConeRequestOutcome.MountUnavailable; } - // After the budget ends, the hook lets Git run. A request sent after that - // could make the mount run Git while the user's Git runs. + // After the budget ends, the hook does not wait for this task. A request sent + // after that could make the mount run Git while the user's Git runs. lock (sendGate) { if (sendAbandoned) @@ -378,9 +394,21 @@ private ConeRequestOutcome SendBounded(string header, string body, int waitBudge sending.TrySetResult(true); pipeClient.SendRequest(new NamedPipeMessages.Message(header, body)); NamedPipeMessages.Message response = pipeClient.ReadResponse(); - return response.Header == NamedPipeMessages.ConeManagement.SuccessResult - ? ConeRequestOutcome.Applied - : ConeRequestOutcome.Rejected; + switch (response.Header) + { + case NamedPipeMessages.ConeManagement.SuccessResult: + return ConeRequestOutcome.Applied; + + case NamedPipeMessages.ConeManagement.NotLockHolderResult: + return ConeRequestOutcome.NotLockHolder; + + case NamedPipeMessages.ConeManagement.NotEnabledResult: + // The mount has no cone manager, so it never changes the cone. + return ConeRequestOutcome.FeatureDisabled; + + default: + return ConeRequestOutcome.Rejected; + } } }); @@ -401,7 +429,13 @@ private ConeRequestOutcome SendBounded(string header, string body, int waitBudge int replyWaitMs = replyCeilingMs ?? Math.Max(0, waitBudgetMs - (int)stopwatch.ElapsedMilliseconds); if (!task.Wait(replyWaitMs)) { - return replyCeilingMs.HasValue ? ConeRequestOutcome.ReplyTimedOut : ConeRequestOutcome.TimedOut; + if (replyCeilingMs.HasValue) + { + this.AbandonedRequest = task; + return ConeRequestOutcome.ReplyTimedOut; + } + + return ConeRequestOutcome.TimedOut; } return task.Result; diff --git a/GVFS/GVFS.Hooks/ConeRequestOutcome.cs b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs index e06ada95d..5afa823fa 100644 --- a/GVFS/GVFS.Hooks/ConeRequestOutcome.cs +++ b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs @@ -55,5 +55,15 @@ internal enum ConeRequestOutcome /// The hook could not take the GVFS lock for a command that does not take it, so it did not send the request. LockUnavailable, + + /// The mount did not apply the request, because the Git command does not hold the GVFS lock. + NotLockHolder, + + /// + /// The command names more paths outside the cone than the mount widens for one command + /// (see AutoSparseIndexConeManager.MaxWidenPaths), so the hook did not send a widen + /// (see ). + /// + TooManyPaths, } } diff --git a/GVFS/GVFS.Hooks/PendingConeChangeHook.cs b/GVFS/GVFS.Hooks/PendingConeChangeHook.cs index 60d0ec3fe..fd83ffcbe 100644 --- a/GVFS/GVFS.Hooks/PendingConeChangeHook.cs +++ b/GVFS/GVFS.Hooks/PendingConeChangeHook.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Threading; using System.Threading.Tasks; @@ -24,7 +25,8 @@ namespace GVFS.Hooks /// applied yet, as it can miss any change that a concurrent command makes. /// /// - /// As for the other cone requests, every failure lets Git run. When the mount replies that + /// This class returns every failure as an outcome, and + /// decides if Git runs. When the mount replies that /// the feature is off, or does not know the request, the hook deletes the pending file, /// because that mount never applies the change. /// @@ -37,9 +39,10 @@ internal sealed class PendingConeChangeHook // The release must reach the mount, or the lock stays with the Git process until it ends. private const int ReleaseConnectTimeoutMs = 5000; - // After a timeout, the hook of a command without the lock still waits this long for the - // mount to finish, so that it does not release the lock while the mount changes the index. - private const int ApplyCompletionWaitMs = 60000; + // After a timeout, a hook still waits this long for the mount to finish before it releases + // the GVFS lock or ends, so that the next Git command does not start while the mount + // changes the index. + internal const int ApplyCompletionWaitMs = 60000; // Built-in commands that read the index or the working tree through the index and do not // take the GVFS lock. "status" is here for "--no-optional-locks", which only checks the @@ -79,6 +82,13 @@ public PendingConeChangeHook(Func isPending, Action deletePendingFile, Fun this.trace = trace ?? (message => { }); } + /// + /// The apply that the hook sent for a command that holds the GVFS lock and stopped waiting + /// for (), or null. The mount can still run + /// Git for it. + /// + public Task AbandonedRequest { get; private set; } + /// /// If a cone change is pending, ask the mount to apply it, and wait for the reply. Never throws. /// @@ -125,6 +135,30 @@ internal static bool IsUnlockedIndexReader(string[] args) return args != null && args.Length > 1 && args[1] != null && UnlockedIndexReaders.Contains(args[1]); } + /// + /// Return true when the mount's pending file exists, and also when the hook cannot tell. + /// An apply with nothing pending costs one request, but a missed pending change makes a + /// command miss a working-tree change outside the cone. + /// + /// Returns the attributes of a path, or throws when it does not exist. + internal static bool IsPendingFilePresentOrUnknown(Func getPendingFilePath, Func getAttributes, Action trace) + { + try + { + getAttributes(getPendingFilePath()); + return true; + } + catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) + { + return false; + } + catch (Exception e) when (!(e is OutOfMemoryException)) + { + trace?.Invoke($"cannot check for a pending cone change: {e.Message}"); + return true; + } + } + private ConeRequestOutcome Apply(string[] args, bool holdsLock, Func createLockRequest, int waitBudgetMs, int lockWaitBudgetMs) { if (!this.isPending()) @@ -135,7 +169,14 @@ private ConeRequestOutcome Apply(string[] args, bool holdsLock, Func heldApply = this.StartApply(commandId); + ConeRequestOutcome outcome = this.WaitForApply(heldApply, waitBudgetMs); + if (outcome == ConeRequestOutcome.ReplyTimedOut) + { + this.AbandonedRequest = heldApply; + } + + return outcome; } if (!IsUnlockedIndexReader(args)) @@ -259,6 +300,9 @@ private Task StartApply(string commandId) case NamedPipeMessages.ConeManagement.SuccessResult: return ConeRequestOutcome.Applied; + case NamedPipeMessages.ConeManagement.NotLockHolderResult: + return ConeRequestOutcome.NotLockHolder; + case NamedPipeMessages.ConeManagement.NotEnabledResult: case NamedPipeMessages.UnknownRequest: // This mount never applies the change, so the file is stale. diff --git a/GVFS/GVFS.Hooks/PreCommandConeRequests.cs b/GVFS/GVFS.Hooks/PreCommandConeRequests.cs index be52aa7a9..39bf6fc16 100644 --- a/GVFS/GVFS.Hooks/PreCommandConeRequests.cs +++ b/GVFS/GVFS.Hooks/PreCommandConeRequests.cs @@ -23,9 +23,22 @@ namespace GVFS.Hooks /// unstaged change. /// /// - /// For other commands, a failed request only makes Git slower, so Git always runs. For an - /// unstage command, a widen that timed out or an apply that failed can hide the unstaged - /// change, so the hook must stop the command (see ). + /// An unstage command also writes the index. A widen or an apply that the hook sent and the + /// mount did not apply can hide the unstaged change, so the hook stops the command with the + /// same rules as for a command that writes the index (see ). A failed + /// widen stops the command before the preparation. + /// + /// + /// For a command that writes the index (see ), a + /// widen or an apply that the hook sent and the mount did not apply means that Git has no + /// index entry for a path or a change that the command needs. Git then fails, or it skips the + /// change and reports success. Thus the hook stops the command before Git runs. The hook + /// never stops a command when it knows that GVFS does not manage a sparse-index cone. When it + /// cannot read the cone file or the feature flag, it stops the command. + /// + /// + /// Other commands always run. Read-only commands do not lose a change, but after a failed + /// apply they can miss a working-tree change outside the cone, so the hook warns. /// /// /// All dependencies are delegates, so that unit tests can check the order without a mount. @@ -33,46 +46,137 @@ namespace GVFS.Hooks /// internal static class PreCommandConeRequests { - /// True when the command unstages files. + /// The kind of the command (see ). /// Returns true when the mount's pending file exists. /// Asks the mount to widen the cone for the named paths. /// Asks the mount to add the staged files to the modified paths. /// Asks the mount to apply the pending cone change. + /// + /// Returns false only when it is known that GVFS does not manage a sparse-index cone. + /// Called only before the hook stops a command that writes the index or unstages files. + /// /// - /// The request that makes an unstage command unsafe, or null when Git can run. Always - /// null for other commands. + /// The request that did not prepare the index, or null. For a command that writes the + /// index or unstages files, the hook stops the command. For other commands, Git runs and + /// the hook warns. /// - public static string Send( - bool isUnstage, + public static ConeRequestFailure Send( + ConeCommandKind kind, Func isConeChangePending, Func sendWiden, Action sendPrepareForUnstage, - Func applyPendingConeChange) + Func applyPendingConeChange, + Func mayManageSparseIndexCone) { ArgumentNullException.ThrowIfNull(isConeChangePending); ArgumentNullException.ThrowIfNull(sendWiden); ArgumentNullException.ThrowIfNull(sendPrepareForUnstage); ArgumentNullException.ThrowIfNull(applyPendingConeChange); + ArgumentNullException.ThrowIfNull(mayManageSparseIndexCone); // Check before the widen: a widen that the mount applied also applied the pending change. bool pending = isConeChangePending(); ConeRequestOutcome widenOutcome = sendWiden(); - if (!isUnstage) + switch (kind) { - if (pending && widenOutcome != ConeRequestOutcome.Applied) - { - applyPendingConeChange(); - } + case ConeCommandKind.Unstage: + return SendForUnstage(widenOutcome, isConeChangePending, sendPrepareForUnstage, applyPendingConeChange, mayManageSparseIndexCone); - return null; + case ConeCommandKind.WritesIndex: + if (!WidenLeavesNoGap(widenOutcome)) + { + return mayManageSparseIndexCone() ? new ConeRequestFailure(ConeRequestFailure.Widen, widenOutcome) : null; + } + + if (pending && widenOutcome != ConeRequestOutcome.Applied) + { + ConeRequestOutcome applyOutcome = applyPendingConeChange(); + if (!ApplyLeavesNoGap(applyOutcome) && mayManageSparseIndexCone()) + { + return new ConeRequestFailure(ConeRequestFailure.Apply, applyOutcome); + } + } + + return null; + + default: + // Git runs. A failed apply can hide a working-tree change from the command, so + // the caller warns. A failed widen does not: the mount refuses every widen of a + // command that does not hold the GVFS lock, and a named path without a change + // is correct after the in-memory expansion. + if (pending && widenOutcome != ConeRequestOutcome.Applied) + { + ConeRequestOutcome applyOutcome = applyPendingConeChange(); + if (!ApplyLeavesNoGap(applyOutcome) && applyOutcome != ConeRequestOutcome.NotAnIndexReader) + { + return new ConeRequestFailure(ConeRequestFailure.Apply, applyOutcome); + } + } + + return null; + } + } + + /// + /// Return true when the widen leaves no named path out of the cone that the mount can + /// add: the mount applied it, the hook did not need it, or no widen can help. + /// + /// + /// is here because the mount refuses such a + /// widen every time, and a stop would stop the command at every attempt. A pending apply + /// still runs, so Git sees every working-tree change. A named path without a change stays + /// outside the cone, and Git expands the index in memory: git add, rm, and + /// mv then fail and report that the path is outside the sparse-checkout + /// definition. + /// + internal static bool WidenLeavesNoGap(ConeRequestOutcome outcome) + { + switch (outcome) + { + case ConeRequestOutcome.Applied: + case ConeRequestOutcome.NoPathsNamed: + case ConeRequestOutcome.NoConeFile: + case ConeRequestOutcome.FeatureDisabled: + case ConeRequestOutcome.SkippedStash: + case ConeRequestOutcome.SkippedInCone: + case ConeRequestOutcome.NoResolvablePaths: + case ConeRequestOutcome.TooManyPaths: + return true; + + default: + return false; + } + } + + /// Return true when no pending change is left after the apply. + internal static bool ApplyLeavesNoGap(ConeRequestOutcome outcome) + { + switch (outcome) + { + case ConeRequestOutcome.Applied: + case ConeRequestOutcome.NothingPending: + case ConeRequestOutcome.FeatureDisabled: + return true; + + default: + return false; } + } - // After a timeout, the mount can still change the cone and the index. The staged-file - // query and Git can then see an index that does not have the named paths yet. - if (widenOutcome == ConeRequestOutcome.TimedOut) + private static ConeRequestFailure SendForUnstage( + ConeRequestOutcome widenOutcome, + Func isConeChangePending, + Action sendPrepareForUnstage, + Func applyPendingConeChange, + Func mayManageSparseIndexCone) + { + // Without the widen, the staged-file query of the preparation does not find a staged + // file inside a sparse-directory entry. After a timeout, the mount can also still + // change the cone and the index. + if (!WidenLeavesNoGap(widenOutcome)) { - return "widen: " + widenOutcome; + return mayManageSparseIndexCone() ? new ConeRequestFailure(ConeRequestFailure.Widen, widenOutcome) : null; } sendPrepareForUnstage(); @@ -86,16 +190,68 @@ public static string Send( } ConeRequestOutcome applyOutcome = applyPendingConeChange(); - switch (applyOutcome) - { - case ConeRequestOutcome.Applied: - case ConeRequestOutcome.NothingPending: - case ConeRequestOutcome.FeatureDisabled: - return null; + return ApplyLeavesNoGap(applyOutcome) || !mayManageSparseIndexCone() + ? null + : new ConeRequestFailure(ConeRequestFailure.Apply, applyOutcome); + } + } - default: - return "apply: " + applyOutcome; - } + /// A cone request that did not prepare the index for a command. + internal sealed class ConeRequestFailure + { + public const string Widen = "widen"; + public const string Apply = "apply"; + + public ConeRequestFailure(string request, ConeRequestOutcome outcome) + { + this.Request = request; + this.Outcome = outcome; + } + + /// or . + public string Request { get; } + + public ConeRequestOutcome Outcome { get; } + + /// + /// True when the request failed because this Git command does not hold the GVFS lock. The + /// usual cause is another Git command that holds it. + /// + public bool IsLockConflict => this.Outcome == ConeRequestOutcome.NotLockHolder || this.Outcome == ConeRequestOutcome.LockUnavailable; + + /// + /// Return the message for a command that writes the index, when the hook stops it before + /// Git runs. + /// + public string[] GetIndexWriteStoppedMessage() + { + string first = "GVFS could not prepare the sparse index (" + this + ")."; + return this.IsLockConflict + ? new[] + { + first, + "This Git command does not hold the GVFS lock. Usually another Git command holds it.", + "Run the command again when the other Git command is done.", + } + : new[] + { + first + " Run the command again.", + "If it fails again, run 'gvfs status' to check the mount, or run 'gvfs unmount' and 'gvfs mount'.", + }; + } + + /// + /// Return the warning for a command that runs although the apply that it needed did not + /// succeed. + /// + public string GetStaleIndexWarning() + { + return "GVFS: the sparse index is not up to date (" + this + "); this command can miss changes outside the sparse-checkout cone. Run it again."; + } + + public override string ToString() + { + return this.Request + ": " + this.Outcome; } } } diff --git a/GVFS/GVFS.Hooks/Program.ConeManagement.cs b/GVFS/GVFS.Hooks/Program.ConeManagement.cs index 334570bf9..f7af21ca8 100644 --- a/GVFS/GVFS.Hooks/Program.ConeManagement.cs +++ b/GVFS/GVFS.Hooks/Program.ConeManagement.cs @@ -7,6 +7,8 @@ using GVFS.Platform.Windows; using System; using System.IO; +using System.Linq; +using System.Threading.Tasks; namespace GVFS.Hooks { @@ -24,11 +26,19 @@ public partial class Program // True when the pre-command hook took the GVFS lock for the Git command. private static bool commandHoldsGVFSLock; + // The hooks that sent the widen and the apply of this command, or null. + private static ConeManagementHook widenHook; + private static PendingConeChangeHook applyHook; + + // True when a read of the cone file or of the feature flag failed since the last reset. + private static bool coneStateReadFailed; + private static ConeRequestOutcome TrySendConeWiden(string[] args) { try { - return CreateConeManagementHook().TrySendWiden(args); + widenHook = CreateConeManagementHook(); + return widenHook.TrySendWiden(args); } catch (Exception e) { @@ -45,7 +55,8 @@ private static ConeRequestOutcome TryApplyPendingConeChange(string[] args) { try { - return new PendingConeChangeHook(IsConeChangePending, DeleteConeChangePendingFile, () => new NamedPipeClient(enlistmentPipename), TraceConeDiagnostic) + applyHook = new PendingConeChangeHook(IsConeChangePending, DeleteConeChangePendingFile, () => new NamedPipeClient(enlistmentPipename), TraceConeDiagnostic); + return applyHook .TryApply( args, commandHoldsGVFSLock, @@ -64,23 +75,57 @@ private static ConeRequestOutcome TryApplyPendingConeChange(string[] args) } /// - /// Return true when the mount's pending file exists (see - /// ). When nothing is pending, this - /// is the only cost that cone management adds to a command that names no paths. + /// Before the hook stops a command, wait for a widen or an apply that it stopped waiting + /// for. The mount can still run Git for it, and that Git holds the index lock. The GVFS + /// lock of this command is released when the command ends, so the next Git command could + /// otherwise start while the mount still writes the index. /// - private static bool IsConeChangePending() + private static void WaitForAbandonedConeRequests() { + Task[] abandoned = new[] { widenHook?.AbandonedRequest, applyHook?.AbandonedRequest } + .Where(task => task != null && !task.IsCompleted) + .ToArray(); + if (abandoned.Length == 0) + { + return; + } + + Console.Error.WriteLine("Waiting for GVFS to finish the sparse index change..."); try { - return File.Exists(GetConeChangePendingPath()); + if (!Task.WaitAll(abandoned, PendingConeChangeHook.ApplyCompletionWaitMs)) + { + TraceConeDiagnostic("cone request still running; stopping the command"); + } } - catch (Exception e) + catch (AggregateException e) { - TraceConeDiagnostic($"cannot check for a pending cone change: {e.Message}"); - return false; + TraceConeDiagnostic($"cone request failed: {e.InnerException?.Message}"); } } + /// + /// Return false only when it is known that GVFS does not manage a sparse-index cone for + /// this worktree. When the hook cannot read the cone file or the feature flag, it cannot + /// tell, and a command that writes the index must stop. + /// + private static bool MayManageSparseIndexCone() + { + coneStateReadFailed = false; + return IsSparseIndexConeManaged() || coneStateReadFailed; + } + + /// + /// Return true when the mount's pending file exists (see + /// ), or when the hook cannot check it. + /// When nothing is pending, this is the only cost that cone management adds to a command + /// that names no paths. + /// + private static bool IsConeChangePending() + { + return PendingConeChangeHook.IsPendingFilePresentOrUnknown(GetConeChangePendingPath, File.GetAttributes, TraceConeDiagnostic); + } + private static void DeleteConeChangePendingFile() { try @@ -125,6 +170,7 @@ private static bool IsSparseIndexConeManaged() } catch (Exception e) { + coneStateReadFailed = true; TraceConeDiagnostic($"cannot check for a sparse-index cone: {e.Message}"); return false; } @@ -162,6 +208,7 @@ private static bool ReadAutoSparseIndexConfig(out bool ignoreCase) } catch (Exception e) { + coneStateReadFailed = true; TraceConeDiagnostic($"cannot read {GVFSConstants.GitConfig.AutoSparseIndex}: {e.Message}"); return GVFSConstants.GitConfig.AutoSparseIndexDefault; } @@ -199,6 +246,7 @@ private static string ReadConeFile() if ((file.Attributes & (FileAttributes.ReparsePoint | FileAttributes.Device)) != 0) { + coneStateReadFailed = true; TraceConeDiagnostic($"cone file not read: {sparseCheckoutPath} is not a regular file"); return null; } @@ -213,6 +261,7 @@ private static string ReadConeFile() content.Write(buffer, 0, read); if (content.Length > MaxConeFileBytes) { + coneStateReadFailed = true; TraceConeDiagnostic($"cone file not read: {sparseCheckoutPath} is larger than {MaxConeFileBytes} bytes"); return null; } @@ -223,6 +272,7 @@ private static string ReadConeFile() } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + coneStateReadFailed = true; TraceConeDiagnostic($"cone file not read: {e.Message}"); return null; } diff --git a/GVFS/GVFS.Hooks/Program.cs b/GVFS/GVFS.Hooks/Program.cs index 773a1c56f..158439726 100644 --- a/GVFS/GVFS.Hooks/Program.cs +++ b/GVFS/GVFS.Hooks/Program.cs @@ -111,7 +111,6 @@ public static void Main(string[] args) private static void RunPreCommands(string[] args) { string command = GetGitCommand(args); - bool isUnstage = false; switch (command) { case "fetch": @@ -126,31 +125,44 @@ private static void RunPreCommands(string[] args) TryDisplayCachedHydrationStatus(); } break; - case "restore": - case "checkout": - case "reset": - isUnstage = UnstageCommandParser.ShouldPrepareForUnstage(command, args, IsSparseIndexConeManaged); - break; case "worktree": RunWorktreePreCommand(args); break; } - string unsafeRequest = PreCommandConeRequests.Send( - isUnstage, + ConeCommandKind kind = ConeCommandClassifier.Classify(command, args, IsSparseIndexConeManaged); + ConeRequestFailure failure = PreCommandConeRequests.Send( + kind, IsConeChangePending, () => TrySendConeWiden(args), () => SendPrepareForUnstageMessage(command, args), - () => TryApplyPendingConeChange(args)); + () => TryApplyPendingConeChange(args), + MayManageSparseIndexCone); - if (unsafeRequest != null) + if (failure == null) + { + return; + } + + if (kind == ConeCommandKind.Other) + { + Console.Error.WriteLine(failure.GetStaleIndexWarning()); + return; + } + + WaitForAbandonedConeRequests(); + if (kind == ConeCommandKind.Unstage) { ExitWithError( - "VFS for Git could not add the staged files to the sparse-index cone (" + unsafeRequest + ").", + "VFS for Git could not add the staged files to the sparse-index cone (" + failure + ").", "Without them in the cone, Git would not show the changes that this command unstages.", "", "Run the command again. If it fails again, run 'gvfs unmount' and 'gvfs mount', and then run it again."); } + else + { + ExitWithError(failure.GetIndexWriteStoppedMessage()); + } } private static bool ArgsBlockHydrationStatus(string[] args) diff --git a/GVFS/GVFS.Mount/InProcessMount.cs b/GVFS/GVFS.Mount/InProcessMount.cs index 376c29964..c08499558 100644 --- a/GVFS/GVFS.Mount/InProcessMount.cs +++ b/GVFS/GVFS.Mount/InProcessMount.cs @@ -57,6 +57,10 @@ public class InProcessMount // Handles cone widen and narrow requests. Null when gvfs.auto-sparse-index was false // when the projection was created. private AutoSparseIndexConeManager coneManager; + + // Test only: refuses cone requests (see ConeRequestFaultInjection). Null unless the + // functional tests set its environment variable. + private ConeRequestFaultInjection coneRequestFaults; private GVFSDatabase gvfsDatabase; private GVFSEnlistment enlistment; private ITracer tracer; @@ -1011,9 +1015,24 @@ private void HandleGetHydrationStatusRequest(NamedPipeServer.Connection connecti private void HandleConeRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection) { - string result = this.currentState == MountState.Ready - ? AutoSparseIndexConeManager.HandleRequest(this.coneManager, this.tracer, message) - : NamedPipeMessages.MountNotReadyResult; + string result; + if (this.currentState != MountState.Ready) + { + result = NamedPipeMessages.MountNotReadyResult; + } + else if (this.coneRequestFaults?.GetForcedReply(message.Header) is string forcedReply) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", "Mount"); + metadata.Add("Header", message.Header); + metadata.Add("Reply", forcedReply); + this.tracer.RelatedEvent(EventLevel.Informational, "ConeRequestFaultInjected", metadata); + result = forcedReply; + } + else + { + result = AutoSparseIndexConeManager.HandleRequest(this.coneManager, this.tracer, message); + } connection.TrySendResponse(result); } @@ -1815,6 +1834,16 @@ private void MountAndStartWorkingDirectoryCallbacks(CacheServerInfo cache, bool { this.fileSystemCallbacks.SetWorkingDirectoryChangeObserver(this.coneManager); this.coneManager.Start(); + + this.coneRequestFaults = ConeRequestFaultInjection.FromEnvironment(Environment.GetEnvironmentVariable); + if (this.coneRequestFaults != null) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", "Mount"); + metadata.Add("FaultFile", this.coneRequestFaults.FaultFilePath); + metadata.Add(TracingConstants.MessageKey.WarningMessage, $"{ConeRequestFaultInjection.FaultFileEnvironmentVariable} is set. This is for tests only: the fault file can make the mount refuse cone requests."); + this.tracer.RelatedEvent(EventLevel.Warning, "ConeRequestFaultInjection", metadata); + } } else { @@ -2322,6 +2351,8 @@ private void UnmountAndStopWorkingDirectoryCallbacks(bool willRemountInSameProce this.coneManager = null; } + this.coneRequestFaults = null; + if (this.fileSystemCallbacks != null) { this.fileSystemCallbacks.Stop(); diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs index f60a30e34..fc2b1a097 100644 --- a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs +++ b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs @@ -530,17 +530,6 @@ public void EntriesOfAProcessWithAnIndeterminateStateAreKept() this.ConeFile.ShouldEqual(ConeWithAB); } - [TestCase] - public void HandleRequestRepliesFailureForARefusedWiden() - { - this.environment.LockHolder = SecondGit; - NamedPipeMessages.Message widen = new NamedPipeMessages.Message( - NamedPipeMessages.ConeManagement.WidenRequest, - new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody()); - - AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); - } - [TestCase] public void ConcurrentWidensAndNarrowsEndWithTheConeOfTheModifiedPaths() { @@ -589,6 +578,32 @@ public void HandleRequestAppliesValidRequests() this.ConeFile.ShouldEqual(Header); } + [TestCase(NamedPipeMessages.ConeManagement.WidenRequest)] + [TestCase(NamedPipeMessages.ConeManagement.ApplyRequest)] + public void HandleRequestRepliesNotLockHolderForACommandThatDoesNotHoldTheGVFSLock(string header) + { + this.environment.LockHolder = SecondGit; + string body = header == NamedPipeMessages.ConeManagement.WidenRequest + ? new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody() + : new NamedPipeMessages.ConeManagement.ApplyParameters(FirstGit.ToString()).ToBody(); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(header, body)) + .ShouldEqual(NamedPipeMessages.ConeManagement.NotLockHolderResult); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void HandleRequestRepliesFailureForARefusedWiden() + { + string[] paths = Enumerable.Range(0, AutoSparseIndexConeManager.MaxWidenPaths + 1).Select(i => $"D{i}/f.txt").ToArray(); + NamedPipeMessages.Message widen = new NamedPipeMessages.Message( + NamedPipeMessages.ConeManagement.WidenRequest, + new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), paths).ToBody()); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + } + [TestCase("100\0C:\\outside.txt")] [TestCase("100\0/abs/path.txt")] [TestCase("100\0A/../../outside.txt")] diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConeRequestFaultInjectionTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConeRequestFaultInjectionTests.cs new file mode 100644 index 000000000..364f5c3b1 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConeRequestFaultInjectionTests.cs @@ -0,0 +1,95 @@ +using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConeRequestFaultInjectionTests + { + private const string FaultFile = @"mock:\faults.txt"; + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + public void IsOffWithoutTheEnvironmentVariable(string value) + { + ConeRequestFaultInjection.FromEnvironment(name => value, path => throw new AssertionException("must not read a file")).ShouldBeNull(); + } + + [TestCase] + public void ReadsTheFaultFileAtEachRequest() + { + string content = null; + int reads = 0; + ConeRequestFaultInjection faults = ConeRequestFaultInjection.FromEnvironment( + name => name == ConeRequestFaultInjection.FaultFileEnvironmentVariable ? FaultFile : null, + path => + { + path.ShouldEqual(FaultFile); + reads++; + return content; + }); + + faults.GetForcedReply(NamedPipeMessages.ConeManagement.WidenRequest).ShouldBeNull(); + + content = "ConeWiden F\r\nConeApply NL\n"; + faults.GetForcedReply(NamedPipeMessages.ConeManagement.WidenRequest).ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + faults.GetForcedReply(NamedPipeMessages.ConeManagement.ApplyRequest).ShouldEqual(NamedPipeMessages.ConeManagement.NotLockHolderResult); + + content = string.Empty; + faults.GetForcedReply(NamedPipeMessages.ConeManagement.WidenRequest).ShouldBeNull(); + reads.ShouldEqual(4); + } + + [TestCase] + public void NeverForcesANarrow() + { + ConeRequestFaultInjection faults = ConeRequestFaultInjection.FromEnvironment(name => FaultFile, path => "ConeNarrow F\n"); + + faults.GetForcedReply(NamedPipeMessages.ConeManagement.NarrowRequest).ShouldBeNull(); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void AFileThatCannotBeReadIsNoFault() + { + ConeRequestFaultInjection faults = ConeRequestFaultInjection.FromEnvironment(name => FaultFile, path => throw new IOException("in use")); + + faults.GetForcedReply(NamedPipeMessages.ConeManagement.WidenRequest).ShouldBeNull(); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void APathThatIsNotValidIsNoFault() + { + ConeRequestFaultInjection faults = ConeRequestFaultInjection.FromEnvironment(name => "C:\\bad\0path", path => throw new ArgumentException("not a valid path")); + + faults.GetForcedReply(NamedPipeMessages.ConeManagement.ApplyRequest).ShouldBeNull(); + } + + [TestCase("ConeWiden S")] + [TestCase("ConeWiden")] + [TestCase("ConeWiden F extra")] + [TestCase("ConeNarrow F")] + [TestCase("conewiden F")] + public void IgnoresLinesThatAreNotValid(string line) + { + ConeRequestFaultInjection.ParseFaults(line).ShouldBeEmpty(); + } + + [TestCase] + public void ParsesValidLines() + { + Dictionary faults = ConeRequestFaultInjection.ParseFaults(" ConeApply F \n\nConeWiden NL"); + + faults[NamedPipeMessages.ConeManagement.ApplyRequest].ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + faults[NamedPipeMessages.ConeManagement.WidenRequest].ShouldEqual(NamedPipeMessages.ConeManagement.NotLockHolderResult); + } + } +} diff --git a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj index cc9c71a9a..0595a567e 100644 --- a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj +++ b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj @@ -28,6 +28,9 @@ + + Hooks\ConeCommandClassifier.cs + Hooks\ConeManagementHook.cs diff --git a/GVFS/GVFS.UnitTests/Hooks/ConeCommandClassifierTests.cs b/GVFS/GVFS.UnitTests/Hooks/ConeCommandClassifierTests.cs new file mode 100644 index 000000000..6f5c9d0e1 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Hooks/ConeCommandClassifierTests.cs @@ -0,0 +1,117 @@ +using GVFS.Hooks; +using GVFS.Tests.Should; +using NUnit.Framework; +using System.Linq; + +namespace GVFS.UnitTests.Hooks +{ + [TestFixture] + public class ConeCommandClassifierTests + { + [TestCase("add -- a/b.txt")] + [TestCase("add .")] + [TestCase("add -A")] + [TestCase("add -u")] + [TestCase("stage -u")] + [TestCase("am patch.mbox")] + [TestCase("apply --index fix.patch")] + [TestCase("apply --cached fix.patch")] + [TestCase("apply -3 fix.patch")] + [TestCase("apply -v3 fix.patch")] + [TestCase("apply --3way fix.patch")] + [TestCase("apply --check --apply --index fix.patch")] + [TestCase("checkout -- a/b.txt")] + [TestCase("checkout topic")] + [TestCase("cherry-pick topic")] + [TestCase("commit -a -m message")] + [TestCase("commit -am message")] + [TestCase("commit --all -m message")] + [TestCase("commit -m message -- a/b.txt")] + [TestCase("commit -m message a/b.txt")] + [TestCase("commit -i -m message a/b.txt")] + [TestCase("commit --only -m message a/b.txt")] + [TestCase("commit -p")] + [TestCase("commit --interactive")] + [TestCase("commit --include -m message a/b.txt")] + [TestCase("commit --patch")] + [TestCase("commit -o -m message a/b.txt")] + [TestCase("commit --pathspec-from-file=paths.txt -m message")] + [TestCase("commit -qam message")] + [TestCase("commit --message message a/b.txt")] + [TestCase("merge topic")] + [TestCase("mv a/b.txt a/c.txt")] + [TestCase("pull")] + [TestCase("rebase topic")] + [TestCase("reset --hard")] + [TestCase("reset --keep HEAD~1")] + [TestCase("reset --merge")] + [TestCase("restore a/b.txt")] + [TestCase("revert HEAD")] + [TestCase("rm a/b.txt")] + [TestCase("stash")] + [TestCase("stash push -- a/b.txt")] + [TestCase("stash pop")] + [TestCase("stash -- list")] + [TestCase("stash -m list")] + [TestCase("stash -q apply")] + [TestCase("stash create")] + [TestCase("switch topic")] + public void CommandsThatWriteTheIndexFromTheWorkingTree(string commandLine) + { + Classify(commandLine).ShouldEqual(ConeCommandKind.WritesIndex); + } + + [TestCase("status")] + [TestCase("diff -- a/b.txt")] + [TestCase("log -- a/b.txt")] + [TestCase("apply fix.patch")] + [TestCase("apply --check fix.patch")] + [TestCase("commit -m message")] + [TestCase("commit -m -a")] + [TestCase("commit --message=-a")] + [TestCase("commit -F message.txt")] + [TestCase("commit -qm message")] + [TestCase("commit -Sdeadbeef -m message")] + [TestCase("commit -uno -m message")] + [TestCase("commit --author author -m message")] + [TestCase("apply --check --index fix.patch")] + [TestCase("apply --stat --cached fix.patch")] + [TestCase("apply -p3 fix.patch")] + [TestCase("commit --amend --no-edit")] + [TestCase("reset --soft HEAD~1")] + [TestCase("stash list")] + [TestCase("stash show -p")] + [TestCase("stash drop")] + [TestCase("stash clear")] + [TestCase("stash store abc123")] + [TestCase("update-index --refresh")] + [TestCase("read-tree HEAD")] + [TestCase("sparse-checkout list")] + public void OtherCommands(string commandLine) + { + Classify(commandLine).ShouldEqual(ConeCommandKind.Other); + } + + [TestCase("restore --staged a/b.txt")] + [TestCase("checkout HEAD -- a/b.txt")] + [TestCase("reset -- a/b.txt")] + public void UnstageCommandsKeepTheirOwnRules(string commandLine) + { + Classify(commandLine).ShouldEqual(ConeCommandKind.Unstage); + } + + [TestCase] + public void ResetWithoutAManagedConeIsNotAnUnstageCommand() + { + // A mixed reset needs the unstage preparation only for a sparse-index cone. + Classify("reset -- a/b.txt", isConeManaged: false).ShouldEqual(ConeCommandKind.Other); + } + + private static ConeCommandKind Classify(string commandLine, bool isConeManaged = true) + { + string[] userArgs = commandLine.Split(' '); + string[] args = new[] { "pre-command" }.Concat(userArgs).Concat(new[] { "--git-pid=1234" }).ToArray(); + return ConeCommandClassifier.Classify(userArgs[0], args, () => isConeManaged); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs index 16ab7bc26..9f3b277f8 100644 --- a/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs +++ b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs @@ -1,4 +1,5 @@ using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; using GVFS.Hooks; using GVFS.UnitTests.Mock.Common; using GVFS.Tests.Should; @@ -7,6 +8,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Linq; using System.Threading; namespace GVFS.UnitTests.Hooks @@ -194,8 +196,7 @@ public void WidenForStashSendsNoRequest() [TestCase(NamedPipeMessages.UnknownRequest)] [TestCase(NamedPipeMessages.MountNotReadyResult)] [TestCase(NamedPipeMessages.ConeManagement.FailureResult)] - [TestCase(NamedPipeMessages.ConeManagement.NotEnabledResult)] - public void WidenWithNonSuccessReplyLetsGitRun(string responseHeader) + public void WidenWithNonSuccessReplyIsRejected(string responseHeader) { this.clientFactory = () => ReplyWith(responseHeader); @@ -203,6 +204,42 @@ public void WidenWithNonSuccessReplyLetsGitRun(string responseHeader) this.createdClients[0].Requests.Count.ShouldEqual(1); } + [TestCase] + public void WidenToAMountWithoutConeManagementIsFeatureDisabled() + { + // The mount has no cone manager, so a command that writes the index must not stop. + this.clientFactory = () => ReplyWith(NamedPipeMessages.ConeManagement.NotEnabledResult); + + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.FeatureDisabled); + } + + [TestCase] + public void WidenMapsTheNotLockHolderReply() + { + this.clientFactory = () => ReplyWith(NamedPipeMessages.ConeManagement.NotLockHolderResult); + + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NotLockHolder); + } + + [TestCase] + public void WidenWithMorePathsThanTheMountAcceptsSendsNoRequest() + { + // The mount refuses such a widen every time, so the hook does not send it. + string[] paths = Enumerable.Range(0, AutoSparseIndexConeManager.MaxWidenPaths + 1).Select(i => $"Z{i}/z.txt").ToArray(); + + this.Widen(new[] { "add" }.Concat(paths).ToArray()).ShouldEqual(ConeRequestOutcome.TooManyPaths); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void WidenWithAsManyPathsAsTheMountAcceptsIsSent() + { + string[] paths = Enumerable.Range(0, AutoSparseIndexConeManager.MaxWidenPaths).Select(i => $"Z{i}/z.txt").ToArray(); + + this.Widen(new[] { "add" }.Concat(paths).ToArray()).ShouldEqual(ConeRequestOutcome.Applied); + this.GetSingleWidenRequest().Paths.Count.ShouldEqual(AutoSparseIndexConeManager.MaxWidenPaths); + } + [TestCase] public void WidenWithoutMountLetsGitRun() { @@ -238,10 +275,16 @@ public void WidenWithoutAReplyLetsGitRunAtTheReplyCeiling() this.clientFactory = () => ReplyAfter(releaseReply); Stopwatch stopwatch = Stopwatch.StartNew(); - this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: ReplyBudgetMs, replyCeilingMs: 50) + ConeManagementHook hook = this.CreateHook(); + hook.TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: ReplyBudgetMs, replyCeilingMs: 50) .ShouldEqual(ConeRequestOutcome.ReplyTimedOut); stopwatch.Stop(); + + // The hook keeps the request, so that it can wait for the mount before it stops Git. + hook.AbandonedRequest.ShouldNotBeNull(); + hook.AbandonedRequest.IsCompleted.ShouldBeFalse(); releaseReply.Set(); + hook.AbandonedRequest.Wait(ReplyBudgetMs).ShouldBeTrue(); (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook must not wait for the reply after the ceiling ends."); } diff --git a/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs index d5d1eeaea..ba58b68c7 100644 --- a/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs +++ b/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs @@ -1,9 +1,12 @@ using GVFS.Common.NamedPipes; using GVFS.Hooks; using GVFS.Tests.Should; +using GVFS.UnitTests.Category; using GVFS.UnitTests.Mock.Common; using NUnit.Framework; +using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; @@ -112,6 +115,60 @@ public void UnlockedIndexReaderDoesNotWaitForAnotherGitCommand() this.RequestHeaders().ShouldMatchInOrder(NamedPipeMessages.AcquireLock.AcquireRequest); } + [TestCase] + public void PendingFileThatExistsIsPending() + { + PendingConeChangeHook.IsPendingFilePresentOrUnknown(() => @"mock:\.gvfs\ConeChangePending", path => FileAttributes.Normal, trace: null) + .ShouldBeTrue(); + } + + [TestCase(typeof(FileNotFoundException))] + [TestCase(typeof(DirectoryNotFoundException))] + [Category(CategoryConstants.ExceptionExpected)] + public void PendingFileThatDoesNotExistIsNotPending(Type exceptionType) + { + PendingConeChangeHook.IsPendingFilePresentOrUnknown(() => @"mock:\.gvfs\ConeChangePending", path => throw (Exception)Activator.CreateInstance(exceptionType), trace: null) + .ShouldBeFalse(); + } + + [TestCase(typeof(UnauthorizedAccessException))] + [TestCase(typeof(IOException))] + [TestCase(typeof(ArgumentException))] + [Category(CategoryConstants.ExceptionExpected)] + public void PendingFileThatCannotBeCheckedCountsAsPending(Type exceptionType) + { + // A missed pending change makes a command miss a working-tree change outside the cone. + List traces = new List(); + PendingConeChangeHook.IsPendingFilePresentOrUnknown(() => @"mock:\.gvfs\ConeChangePending", path => throw (Exception)Activator.CreateInstance(exceptionType), traces.Add) + .ShouldBeTrue(); + traces.Count.ShouldEqual(1); + } + + [TestCase] + public void LockHolderKeepsTheApplyThatTimedOut() + { + // The event is not disposed, because the abandoned request task still waits on it. + ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false); + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + releaseReply.Wait(); + return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null); + }, + }); + + PendingConeChangeHook hook = this.CreateHook(); + hook.TryApply(BuildArgs("commit", "-a"), holdsLock: true, this.CreateLockRequest, waitBudgetMs: 10) + .ShouldEqual(ConeRequestOutcome.ReplyTimedOut); + + // The hook keeps the request, so that it can wait for the mount before it stops Git. + hook.AbandonedRequest.ShouldNotBeNull(); + hook.AbandonedRequest.IsCompleted.ShouldBeFalse(); + releaseReply.Set(); + hook.AbandonedRequest.Wait(30000).ShouldBeTrue(); + } + [TestCase] public void UnlockedIndexReaderKeepsTheLockUntilTheMountFinishesAfterATimeout() { @@ -171,6 +228,16 @@ public void MountThatIsNotReadyKeepsThePendingFile() this.pendingFileDeleted.ShouldBeFalse(); } + [TestCase] + public void ApplyForACommandThatDoesNotHoldTheLockKeepsThePendingFile() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.NotLockHolderResult)); + + this.Apply(holdsLock: true, "add").ShouldEqual(ConeRequestOutcome.NotLockHolder); + + this.pendingFileDeleted.ShouldBeFalse(); + } + [TestCase] public void UnlockedIndexReaderWithoutAProcessIdSendsNothing() { diff --git a/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs b/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs index b0e7e9718..418cfb839 100644 --- a/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs +++ b/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs @@ -24,7 +24,7 @@ public void UnstageWidensBeforeItPrepares() { // Git does not match a pathspec with a path inside a sparse-directory entry, so the // staged-file query of the preparation must run after the widen. - this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull(); + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull(); this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?"); } @@ -32,9 +32,11 @@ public void UnstageWidensBeforeItPrepares() [TestCase("Applied")] [TestCase("NoPathsNamed")] [TestCase("NoResolvablePaths")] + [TestCase("TooManyPaths")] + [TestCase("FeatureDisabled")] public void UnstageAppliesAChangeThatThePreparationMadePending(string widenOutcome) { - this.Send(isUnstage: true, widenOutcome: Parse(widenOutcome), preparationMakesPending: true).ShouldBeNull(); + this.Send(ConeCommandKind.Unstage, widenOutcome: Parse(widenOutcome), preparationMakesPending: true).ShouldBeNull(); this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?", "apply"); } @@ -43,7 +45,7 @@ public void UnstageAppliesAChangeThatThePreparationMadePending(string widenOutco public void UnstageAppliesOnceAChangeThatWasPendingBeforeAWidenThatDidNotApply() { this.pending = true; - this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull(); + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull(); this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?", "apply"); } @@ -52,7 +54,7 @@ public void UnstageAppliesOnceAChangeThatWasPendingBeforeAWidenThatDidNotApply() public void UnstageDoesNotApplyWhenNothingIsPendingAfterThePreparation() { this.pending = true; - this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.Applied, widenClearsPending: true).ShouldBeNull(); + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.Applied, widenClearsPending: true).ShouldBeNull(); this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?"); } @@ -61,7 +63,7 @@ public void UnstageDoesNotApplyWhenNothingIsPendingAfterThePreparation() [TestCase("FeatureDisabled")] public void UnstageRunsWhenTheApplyHasNothingToDo(string applyOutcome) { - this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome)) + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome)) .ShouldBeNull(); } @@ -74,45 +76,185 @@ public void UnstageStopsWhenTheApplyFails(string applyOutcome) { // Without the apply, the unstaged file stays inside a sparse-directory entry with // skip-worktree set, and Git does not report the change. - this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome)) + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome)) .ShouldEqual("apply: " + applyOutcome); } - [TestCase] - public void UnstageStopsWithoutPreparingWhenTheWidenTimedOut() + [TestCase("TimedOut")] + [TestCase("ReplyTimedOut")] + [TestCase("Rejected")] + [TestCase("Failed")] + [TestCase("MountUnavailable")] + [TestCase("NotLockHolder")] + public void UnstageStopsWithoutPreparingWhenTheWidenIsNotApplied(string widenOutcome) { - // The mount can still change the cone and the index after the hook stops waiting. - this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.TimedOut).ShouldEqual("widen: TimedOut"); + // An unstage writes the index, so it stops for every failed widen, as a command that + // writes the index does. The preparation does not run. + this.Send(ConeCommandKind.Unstage, widenOutcome: Parse(widenOutcome)).ShouldEqual("widen: " + widenOutcome); - this.calls.ShouldMatchInOrder("pending?", "widen"); + this.calls.ShouldMatchInOrder("pending?", "widen", "managed?"); + } + + [TestCase] + public void UnstageRunsWhenGVFSDoesNotManageTheCone() + { + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.Rejected, isConeManaged: false).ShouldBeNull(); + this.Send(ConeCommandKind.Unstage, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: ConeRequestOutcome.Rejected, isConeManaged: false) + .ShouldBeNull(); } [TestCase] public void OtherCommandSkipsTheApplyAfterAnAppliedWiden() { this.pending = true; - this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull(); + this.Send(ConeCommandKind.Other, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull(); this.calls.ShouldMatchInOrder("pending?", "widen"); } - [TestCase] - public void OtherCommandAppliesAPendingChangeWhenTheWidenDidNotApply() + [TestCase("Failed")] + [TestCase("Rejected")] + [TestCase("ReplyTimedOut")] + [TestCase("LockUnavailable")] + [TestCase("MountUnavailable")] + public void OtherCommandRunsAndReportsAFailedApplyForTheWarning(string applyOutcome) { + // The command runs, but it can miss the pending change, so the hook warns. this.pending = true; - this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.TimedOut, applyOutcome: ConeRequestOutcome.Failed).ShouldBeNull(); + this.Send(ConeCommandKind.Other, widenOutcome: ConeRequestOutcome.Rejected, applyOutcome: Parse(applyOutcome)) + .ShouldEqual("apply: " + applyOutcome); this.calls.ShouldMatchInOrder("pending?", "widen", "apply"); } + [TestCase("Applied")] + [TestCase("NothingPending")] + [TestCase("FeatureDisabled")] + [TestCase("NotAnIndexReader")] + public void OtherCommandHasNoWarningWhenTheApplyLeavesNoGapOrIsNotNeeded(string applyOutcome) + { + this.pending = true; + this.Send(ConeCommandKind.Other, widenOutcome: ConeRequestOutcome.NotLockHolder, applyOutcome: Parse(applyOutcome)).ShouldBeNull(); + } + [TestCase] public void OtherCommandDoesNotApplyWhenNothingIsPending() { - this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull(); + this.Send(ConeCommandKind.Other, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen"); + } + + [TestCase] + public void OtherCommandHasNoWarningForAFailedWiden() + { + // The mount refuses every widen of a command that does not hold the GVFS lock. + this.Send(ConeCommandKind.Other, widenOutcome: ConeRequestOutcome.NotLockHolder).ShouldBeNull(); this.calls.ShouldMatchInOrder("pending?", "widen"); } + [TestCase("Rejected")] + [TestCase("TimedOut")] + [TestCase("ReplyTimedOut")] + [TestCase("MountUnavailable")] + [TestCase("Failed")] + [TestCase("NotLockHolder")] + public void IndexWriterStopsWhenTheWidenIsNotApplied(string widenOutcome) + { + // Git has no index entry for the named path, so it fails or skips the path. + this.pending = true; + this.Send(ConeCommandKind.WritesIndex, widenOutcome: Parse(widenOutcome)).ShouldEqual("widen: " + widenOutcome); + + this.calls.ShouldMatchInOrder("pending?", "widen", "managed?"); + } + + [TestCase("Applied")] + [TestCase("NoPathsNamed")] + [TestCase("NoConeFile")] + [TestCase("FeatureDisabled")] + [TestCase("SkippedStash")] + [TestCase("SkippedInCone")] + [TestCase("NoResolvablePaths")] + [TestCase("TooManyPaths")] + public void IndexWriterRunsWhenTheWidenIsDoneOrNotNeeded(string widenOutcome) + { + this.Send(ConeCommandKind.WritesIndex, widenOutcome: Parse(widenOutcome)).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen"); + } + + [TestCase("Rejected")] + [TestCase("ReplyTimedOut")] + [TestCase("MountUnavailable")] + [TestCase("Failed")] + [TestCase("NotAnIndexReader")] + [TestCase("LockUnavailable")] + [TestCase("NotLockHolder")] + public void IndexWriterStopsWhenThePendingApplyFails(string applyOutcome) + { + // Git has no index entry for the changed file, so it does not see the change. + this.pending = true; + this.Send(ConeCommandKind.WritesIndex, widenOutcome: ConeRequestOutcome.NoPathsNamed, applyOutcome: Parse(applyOutcome)) + .ShouldEqual("apply: " + applyOutcome); + + this.calls.ShouldMatchInOrder("pending?", "widen", "apply", "managed?"); + } + + [TestCase("Applied")] + [TestCase("NothingPending")] + [TestCase("FeatureDisabled")] + public void IndexWriterRunsWhenTheApplyLeavesNothingPending(string applyOutcome) + { + this.pending = true; + this.Send(ConeCommandKind.WritesIndex, widenOutcome: ConeRequestOutcome.SkippedInCone, applyOutcome: Parse(applyOutcome)).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen", "apply"); + } + + [TestCase] + public void IndexWriterSkipsTheApplyAfterAnAppliedWiden() + { + this.pending = true; + this.Send(ConeCommandKind.WritesIndex, widenOutcome: ConeRequestOutcome.Applied, applyOutcome: ConeRequestOutcome.Rejected).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen"); + } + + [TestCase] + public void IndexWriterRunsWhenGVFSDoesNotManageTheCone() + { + this.pending = true; + this.Send(ConeCommandKind.WritesIndex, widenOutcome: ConeRequestOutcome.Failed, isConeManaged: false).ShouldBeNull(); + this.Send(ConeCommandKind.WritesIndex, widenOutcome: ConeRequestOutcome.NoPathsNamed, applyOutcome: ConeRequestOutcome.Rejected, isConeManaged: false) + .ShouldBeNull(); + } + + [TestCase] + public void StopMessageNamesTheRequestAndTheOutcome() + { + new ConeRequestFailure(ConeRequestFailure.Apply, ConeRequestOutcome.ReplyTimedOut).GetIndexWriteStoppedMessage().ShouldMatchInOrder( + "GVFS could not prepare the sparse index (apply: ReplyTimedOut). Run the command again.", + "If it fails again, run 'gvfs status' to check the mount, or run 'gvfs unmount' and 'gvfs mount'."); + } + + [TestCase("NotLockHolder")] + [TestCase("LockUnavailable")] + public void StopMessageNamesTheGVFSLock(string outcome) + { + new ConeRequestFailure(ConeRequestFailure.Widen, Parse(outcome)).GetIndexWriteStoppedMessage().ShouldMatchInOrder( + $"GVFS could not prepare the sparse index (widen: {outcome}).", + "This Git command does not hold the GVFS lock. Usually another Git command holds it.", + "Run the command again when the other Git command is done."); + } + + [TestCase] + public void WarningNamesTheRequestAndTheOutcome() + { + new ConeRequestFailure(ConeRequestFailure.Apply, ConeRequestOutcome.Rejected).GetStaleIndexWarning().ShouldEqual( + "GVFS: the sparse index is not up to date (apply: Rejected); this command can miss changes outside the sparse-checkout cone. Run it again."); + } + // ConeRequestOutcome is internal, and NUnit test methods are public, so test cases name it. private static ConeRequestOutcome Parse(string outcome) { @@ -120,14 +262,15 @@ private static ConeRequestOutcome Parse(string outcome) } private string Send( - bool isUnstage, + ConeCommandKind kind, ConeRequestOutcome widenOutcome, bool preparationMakesPending = false, bool widenClearsPending = false, - ConeRequestOutcome applyOutcome = ConeRequestOutcome.Applied) + ConeRequestOutcome applyOutcome = ConeRequestOutcome.Applied, + bool isConeManaged = true) { return PreCommandConeRequests.Send( - isUnstage, + kind, () => { this.calls.Add("pending?"); @@ -155,7 +298,12 @@ private string Send( { this.calls.Add("apply"); return applyOutcome; - }); + }, + () => + { + this.calls.Add("managed?"); + return isConeManaged; + })?.ToString(); } } }