diff --git a/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj b/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj
index ad505ef38..63a256d41 100644
--- a/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj
+++ b/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj
@@ -11,6 +11,8 @@
+
+
diff --git a/tools/visualstudio-extension/test/CoreTests/FixtureMutationTests.cs b/tools/visualstudio-extension/test/CoreTests/FixtureMutationTests.cs
new file mode 100644
index 000000000..0ade9bd15
--- /dev/null
+++ b/tools/visualstudio-extension/test/CoreTests/FixtureMutationTests.cs
@@ -0,0 +1,182 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using VerseAngelScript.VisualStudio.Tests;
+
+internal static class FixtureMutationTests
+{
+ private static readonly TimeSpan Budget = TimeSpan.FromSeconds(5);
+ private static readonly Encoding Utf8 = new UTF8Encoding(false, true);
+ internal static void Run(Action check) => RunAsync(check).GetAwaiter().GetResult();
+
+ private static async Task RunAsync(Action check)
+ {
+ var stream = new RecordingStream();
+ int opens = 0, conflicts = 0;
+ await FixtureMutation.AppendOnceAsync("fixture", "\n漢😀", Budget, CancellationToken.None,
+ error => { check(FixtureMutation.IsSharingConflict(error), "Only verified sharing conflicts notify acquisition retry"); ++conflicts; },
+ path => { ++opens; if (opens <= 2) throw Sharing(opens == 1 ? 32 : 33); return stream; });
+ check(opens == 3 && conflicts == 2, "Both exact Windows sharing/lock errors retry acquisition");
+ check(stream.Writes == 1 && stream.Flushes == 1 && stream.Disposals == 1, "Acquired fixture is mutated, flushed and disposed once");
+ check(Utf8.GetString(stream.ToArray()) == "before\n漢😀", "Retry produces exactly one UTF-8 append without a BOM");
+
+ foreach (var failure in new Exception[] {
+ new IOException("being used by another process"),
+ new IOException("Wrong HRESULT facility", unchecked((int)0x80130020)),
+ new IOException("I/O data error", unchecked((int)0x80070017)),
+ new UnauthorizedAccessException("Denied") })
+ {
+ opens = 0;
+ var actual = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!", Budget, CancellationToken.None,
+ open: path => { ++opens; throw failure; }));
+ check(ReferenceEquals(actual, failure) && opens == 1, "Nonsharing acquisition failure propagates without retry: " + failure.GetType().Name);
+ }
+
+ foreach (var stage in new[] { "seek", "write", "flush", "dispose" })
+ {
+ var failure = Sharing(32);
+ stream = new RecordingStream { FailStage = stage, Failure = failure };
+ opens = 0;
+ var actual = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!mutation", Budget, CancellationToken.None,
+ open: path => { ++opens; return stream; }));
+ check(ReferenceEquals(actual, failure) && opens == 1, "Post-open " + stage + " error is never retried, even with sharing HRESULT");
+ check(stream.Writes == (stage == "seek" ? 0 : 1), "Post-open " + stage + " cannot replay mutation");
+ check(Utf8.GetString(stream.ToArray()) == (stage == "seek" ? "before" : stage == "write" ? "before!" : "before!mutation"), "Partial/complete " + stage + " mutation retained exactly once");
+ check(stream.Disposals == 1, "Post-open " + stage + " disposes owned stream");
+ }
+
+ var elapsed = TimeSpan.Zero;
+ opens = 0;
+ var locked = Sharing(33);
+ var timedOut = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!", Budget, CancellationToken.None,
+ open: path => { ++opens; elapsed += TimeSpan.FromTicks(Budget.Ticks / 2); throw locked; }, elapsed: () => elapsed));
+ check(timedOut is TimeoutException && ReferenceEquals(timedOut.InnerException, locked) && opens == 2, "Retries share one bounded deadline and preserve their last verified conflict");
+
+ elapsed = TimeSpan.Zero;
+ stream = new RecordingStream();
+ timedOut = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!", Budget, CancellationToken.None,
+ open: path => { elapsed = Budget; return stream; }, elapsed: () => elapsed));
+ check(timedOut is TimeoutException && stream.Writes == 0 && stream.Disposals == 1, "Late acquisition is disposed without writing after the deadline");
+
+ using (var cancel = new CancellationTokenSource())
+ {
+ cancel.Cancel(); opens = 0;
+ var cancelled = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!", Budget, cancel.Token,
+ open: path => { ++opens; return new RecordingStream(); }));
+ check(cancelled is OperationCanceledException && opens == 0, "Pre-cancelled mutation never opens the fixture");
+ }
+ using (var cancel = new CancellationTokenSource())
+ {
+ opens = 0;
+ var cancelled = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!", Budget, cancel.Token,
+ contention: error => cancel.Cancel(), open: path => { ++opens; throw Sharing(32); }));
+ check(cancelled is OperationCanceledException && opens == 1, "Cancellation stops acquisition retries before any write");
+ }
+ using (var cancel = new CancellationTokenSource())
+ {
+ stream = new RecordingStream();
+ var cancelled = await Failure(() => FixtureMutation.AppendOnceAsync("fixture", "!", Budget, cancel.Token,
+ open: path => { cancel.Cancel(); return stream; }));
+ check(cancelled is OperationCanceledException && stream.Writes == 0 && stream.Disposals == 1, "Cancellation after acquisition disposes without mutation");
+ }
+
+ string root = Path.Combine(Path.GetTempPath(), "vas-fixture-mutation-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try
+ {
+ string path = Path.Combine(root, "existing.txt");
+ File.WriteAllText(path, "before", Utf8);
+ await FixtureMutation.AppendOnceAsync(path, "!", Budget, CancellationToken.None);
+ check(File.ReadAllText(path, Utf8) == "before!", "Real file receives exactly one append");
+ string missing = Path.Combine(root, "missing.txt");
+ var missingError = await Failure(() => FixtureMutation.AppendOnceAsync(missing, "!", Budget, CancellationToken.None));
+ check(missingError is FileNotFoundException && !File.Exists(missing), "Missing fixture fails rather than being silently created");
+ if (Environment.OSVersion.Platform == PlatformID.Win32NT) await WindowsReadLease(path, check);
+ else Console.WriteLine("SKIP real Windows fixture sharing handles: non-Windows host.");
+ }
+ finally { Directory.Delete(root, true); }
+ }
+
+ private static async Task WindowsReadLease(string path, Action check)
+ {
+ var before = File.ReadAllBytes(path);
+ var conflict = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ Task append;
+ using (var cancel = new CancellationTokenSource())
+ {
+ var readLease = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ append = FixtureMutation.AppendOnceAsync(path, "!", Budget, cancel.Token, error => conflict.TrySetResult(error));
+ try
+ {
+ var first = await Task.WhenAny(conflict.Task, append);
+ if (first == append) await append;
+ check(ReferenceEquals(first, conflict.Task), "Held ShareRead lease reaches verified acquisition contention");
+ check(FixtureMutation.IsSharingConflict(await conflict.Task) && !append.IsCompleted, "Read lease prevents early mutation");
+ check(File.ReadAllBytes(path).SequenceEqual(before), "Bytes unchanged while write access is denied");
+ readLease.Dispose(); readLease = null;
+ await append;
+ }
+ finally
+ {
+ cancel.Cancel();
+ readLease?.Dispose();
+ try { await append; }
+ catch (OperationCanceledException) when (cancel.IsCancellationRequested) { }
+ }
+ }
+ check(File.ReadAllBytes(path).SequenceEqual(before.Concat(new[] { (byte)'!' })), "Release admits one real Windows append");
+
+ before = File.ReadAllBytes(path);
+ using (var readLease = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
+ using (var cancel = new CancellationTokenSource())
+ {
+ conflict = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ append = FixtureMutation.AppendOnceAsync(path, "!", Budget, cancel.Token, error => conflict.TrySetResult(error));
+ check(ReferenceEquals(await Task.WhenAny(conflict.Task, append), conflict.Task), "Real cancellation case reaches held read lease");
+ cancel.Cancel();
+ check(await Failure(() => append) is OperationCanceledException, "Real sharing wait cancels without mutation");
+ check(File.ReadAllBytes(path).SequenceEqual(before), "Cancelled real acquisition preserves exact bytes");
+ }
+ using (var readLease = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
+ {
+ long expired = 0;
+ var error = await Failure(() => FixtureMutation.AppendOnceAsync(path, "!", Budget, CancellationToken.None,
+ contention: failure => Interlocked.Exchange(ref expired, 1),
+ elapsed: () => Interlocked.Read(ref expired) == 0 ? TimeSpan.Zero : Budget));
+ check(error is TimeoutException && error.InnerException is IOException sharing && FixtureMutation.IsSharingConflict(sharing), "Real Windows sharing conflict reaches the deterministic deadline");
+ check(File.ReadAllBytes(path).SequenceEqual(before), "Timed out real acquisition preserves exact bytes");
+ }
+ }
+
+ private static IOException Sharing(int code) => new IOException("Controlled sharing conflict", unchecked((int)(0x80070000u + code)));
+ private static async Task Failure(Func action)
+ {
+ try { await action(); }
+ catch (Exception error) { return error; }
+ throw new Exception("Expected fixture mutation failure was accepted.");
+ }
+
+ private sealed class RecordingStream : MemoryStream
+ {
+ internal int Writes, Flushes, Disposals;
+ internal string FailStage;
+ internal Exception Failure;
+ internal RecordingStream() { var bytes = Utf8.GetBytes("before"); base.Write(bytes, 0, bytes.Length); }
+ public override long Seek(long offset, SeekOrigin origin)
+ { if (FailStage == "seek") throw Failure; return base.Seek(offset, origin); }
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ ++Writes;
+ // Simulate a failure after a partial write, not just an exception
+ // before any bytes: replaying the operation would corrupt the fixture.
+ base.Write(buffer, offset, FailStage == "write" ? Math.Min(1, count) : count);
+ if (FailStage == "write") throw Failure;
+ }
+ public override void Flush() { ++Flushes; if (FailStage == "flush") throw Failure; base.Flush(); }
+ protected override void Dispose(bool disposing)
+ { ++Disposals; base.Dispose(disposing); if (FailStage == "dispose") throw Failure; }
+ }
+}
diff --git a/tools/visualstudio-extension/test/CoreTests/Program.cs b/tools/visualstudio-extension/test/CoreTests/Program.cs
index 96b96e828..1849474e6 100644
--- a/tools/visualstudio-extension/test/CoreTests/Program.cs
+++ b/tools/visualstudio-extension/test/CoreTests/Program.cs
@@ -22,6 +22,7 @@ private static int Main(string[] args)
try
{
DescriptorTests(); ReportTests(); PositionTests(); CompilerPathTests(); InputEventTests(); WorkspaceEventTests(); ProcessTests();
+ FixtureMutationTests.Run(Check);
string native = Environment.GetEnvironmentVariable("VAS_NATIVE_ARGV_FIXTURE");
if (!string.IsNullOrEmpty(native)) NativeArguments(native);
else if (Environment.OSVersion.Platform == PlatformID.Win32NT) throw new Exception("Windows core gate requires VAS_NATIVE_ARGV_FIXTURE (tests/vasbuild/rider_argv_fixture.cpp).");
diff --git a/tools/visualstudio-extension/test/HostTests/HostTests.csproj b/tools/visualstudio-extension/test/HostTests/HostTests.csproj
index 3dae09182..bf3f35d67 100644
--- a/tools/visualstudio-extension/test/HostTests/HostTests.csproj
+++ b/tools/visualstudio-extension/test/HostTests/HostTests.csproj
@@ -40,6 +40,7 @@
+
diff --git a/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs b/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs
index 954daee18..9fcd1a617 100644
--- a/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs
+++ b/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs
@@ -555,7 +555,7 @@ public async Task BlockedBuildInputAndCompilerChangesInvalidate()
else
{
var path = change == "source" ? fixture.Entry : change == "config" ? fixture.Config : fixture.Manifest;
- File.AppendAllText(path, "\n");
+ await AppendBlockedInputAsync(fixture, path, generation, holdReadLease: change == "manifest");
}
await WaitForAsync(() => !Busy && fixture.NoLiveProcesses() && Convert.ToInt64(Member(Coordinator, "Generation")) > generation, "concurrent " + change + " change invalidates and stops process");
var status = Status;
@@ -575,23 +575,19 @@ public async Task BlockedBuildInputAndCompilerChangesInvalidate()
await ChooseAndBuildAsync(racing, 0);
await WaitForAsync(() => Busy && racing.Calls.Count(call => call == "build") == cycle + 1, "blocked process for concurrent cancel cycle");
var mutationStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- var mutation = Task.Run(() =>
+ var before = File.ReadAllBytes(racing.Entry);
+ var mutation = Task.Run(async () =>
{
mutationStarted.SetResult(true);
// Actual file changes race native watcher cancellation against
// the UI command; no callback ordering is assumed or forced.
for (var edit = 0; edit < 4; edit++)
- {
- for (var attempt = 0; ; attempt++)
- {
- try { File.AppendAllText(racing.Entry, " "); break; }
- catch (IOException) when (attempt < 100) { System.Threading.Thread.Sleep(5); }
- }
- }
+ await FixtureMutation.AppendOnceAsync(racing.Entry, " ", TimeSpan.FromSeconds(5), CancellationToken.None);
});
await mutationStarted.Task;
ExecuteCommand(CancelCommand);
await mutation;
+ Assert.Equal(before.Concat(Encoding.UTF8.GetBytes(" ")).ToArray(), File.ReadAllBytes(racing.Entry));
await WaitForAsync(() => !Busy && racing.NoLiveProcesses(), "concurrent watcher/command cancellation owns and reaps process");
File.WriteAllText(racing.ReleaseFile, "late output after concurrent cancellation");
await Task.Delay(150);
@@ -603,7 +599,50 @@ public async Task BlockedBuildInputAndCompilerChangesInvalidate()
Assert.Equal((cycle + 1) * 2, racing.Calls.Count);
Assert.False(Directory.Exists(racing.OutputDirectory));
}
- SaveEvidence(nameof(BlockedBuildInputAndCompilerChangesInvalidate), "sourceMutationCancels", "configMutationCancels", "manifestMutationCancels", "compilerSettingCancels", "lateOutputIgnored", "processesReaped", "concurrentWatcherCancelSafe");
+ SaveEvidence(nameof(BlockedBuildInputAndCompilerChangesInvalidate), "sourceMutationCancels", "configMutationCancels", "manifestMutationCancels", "compilerSettingCancels", "lateOutputIgnored", "processesReaped", "concurrentWatcherCancelSafe", "sharingAcquisitionResponsive", "exactSingleInputMutation");
+ }
+
+ private async Task AppendBlockedInputAsync(Fixture fixture, string path, long generation, bool holdReadLease)
+ {
+ await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
+ Assert.True(Busy && !fixture.NoLiveProcesses());
+ Assert.Equal(generation, Convert.ToInt64(Member(Coordinator, "Generation")));
+ var before = File.ReadAllBytes(path);
+ var contention = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ FileStream reader = holdReadLease ? new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read) : null;
+ using (var cancellation = new CancellationTokenSource())
+ {
+ var mutation = FixtureMutation.AppendOnceAsync(path, "\n", TimeSpan.FromSeconds(5), cancellation.Token,
+ error => contention.TrySetResult(error));
+ try
+ {
+ if (holdReadLease)
+ {
+ var first = await Task.WhenAny(contention.Task, mutation);
+ if (first == mutation) await mutation; // Propagate an unexpected acquisition failure.
+ Assert.Same(contention.Task, first);
+ await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
+ Assert.True(FixtureMutation.IsSharingConflict(await contention.Task));
+ Assert.False(mutation.IsCompleted);
+ Assert.Equal(before, File.ReadAllBytes(path));
+ Assert.True(Busy && !fixture.NoLiveProcesses());
+ Assert.Equal(generation, Convert.ToInt64(Member(Coordinator, "Generation")));
+ var flags = QueryCommand(CancelCommand); // The real native UI remains usable while write acquisition waits.
+ Assert.True((flags & (uint)OLECMDF.OLECMDF_ENABLED) != 0);
+ reader.Dispose(); reader = null;
+ }
+ await mutation;
+ await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
+ Assert.Equal(before.Concat(new[] { (byte)'\n' }).ToArray(), File.ReadAllBytes(path));
+ }
+ finally
+ {
+ cancellation.Cancel();
+ reader?.Dispose();
+ try { await mutation; }
+ catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { }
+ }
+ }
}
[IdeFact(MinVersion = VisualStudioVersion.VS18, MaxVersion = VisualStudioVersion.VS18, RootSuffix = "VASIntegration", MaxAttempts = 1)]
diff --git a/tools/visualstudio-extension/test/Shared/FixtureMutation.cs b/tools/visualstudio-extension/test/Shared/FixtureMutation.cs
new file mode 100644
index 000000000..a6500ec9b
--- /dev/null
+++ b/tools/visualstudio-extension/test/Shared/FixtureMutation.cs
@@ -0,0 +1,62 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace VerseAngelScript.VisualStudio.Tests
+{
+ // Test fixtures sometimes overlap the production reader's short ShareRead
+ // snapshot. Acquire an existing file once, then perform exactly one append.
+ // This helper is compiled into test executables only, never the VSIX.
+ internal static class FixtureMutation
+ {
+ internal static bool IsSharingConflict(IOException error) =>
+ error.HResult == unchecked((int)0x80070020) || error.HResult == unchecked((int)0x80070021);
+
+ internal static Task AppendOnceAsync(string path, string suffix, TimeSpan timeout, CancellationToken cancellation,
+ Action contention = null, Func open = null, Func elapsed = null)
+ {
+ if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout));
+ var bytes = new UTF8Encoding(false, true).GetBytes(suffix);
+ var clock = Stopwatch.StartNew();
+ var age = elapsed ?? (() => clock.Elapsed);
+ var acquire = open ?? (name => new FileStream(name, FileMode.Open, FileAccess.Write, FileShare.Read));
+ return Task.Run(async () =>
+ {
+ IOException lastConflict = null;
+ Stream stream;
+ while (true)
+ {
+ cancellation.ThrowIfCancellationRequested();
+ if (age() >= timeout) throw new TimeoutException("Timed out acquiring fixture write access: " + path, lastConflict);
+ try { stream = acquire(path); }
+ catch (IOException error) when (IsSharingConflict(error))
+ {
+ lastConflict = error;
+ contention?.Invoke(error);
+ // Requeue only after a verified pre-write sharing conflict.
+ // Yield the worker between attempts without resetting the
+ // original deadline or assuming the reader has released it.
+ var remaining = timeout - age();
+ if (remaining > TimeSpan.Zero)
+ await Task.Delay(remaining < TimeSpan.FromMilliseconds(10) ? remaining : TimeSpan.FromMilliseconds(10), cancellation);
+ continue;
+ }
+ break;
+ }
+ using (stream)
+ {
+ cancellation.ThrowIfCancellationRequested();
+ if (age() >= timeout) throw new TimeoutException("Fixture write access arrived after its deadline: " + path, lastConflict);
+ // Never retry any operation after acquisition: a write or flush
+ // failure can follow a partial mutation, even with a lock HRESULT.
+ stream.Seek(0, SeekOrigin.End);
+ stream.Write(bytes, 0, bytes.Length);
+ stream.Flush();
+ }
+ }, cancellation);
+ }
+ }
+}
diff --git a/tools/visualstudio-extension/test/check_results.py b/tools/visualstudio-extension/test/check_results.py
index 6702b7095..0874ff5a9 100644
--- a/tools/visualstudio-extension/test/check_results.py
+++ b/tools/visualstudio-extension/test/check_results.py
@@ -30,7 +30,7 @@
"CanonicalMissingIncludesAndAncestorChangesInvalidate": {"nativeMissingInclude", "canonicalAliasCreate", "ancestorRename", "ancestorDelete", "sameSessionUiInvalidated", "nativeSuccessRowsCleared", "staleSessionGuardsRejected", "staleNativeWarningDoesNotNavigate"},
"FirstTraversalDirtyIncludeAliasBlocksPublication": {"firstTraversalObserved", "dirtyTxtHardLinkRejected", "noStalePublication", "unrelatedDirtyAllowed"},
"MismatchedProofAndTruncatedReportsNeverPublish": {"mismatchedDigestRejected", "truncatedTerminalRejected", "noDiagnosticPublication", "actualProcessCalls"},
- "BlockedBuildInputAndCompilerChangesInvalidate": {"sourceMutationCancels", "configMutationCancels", "manifestMutationCancels", "compilerSettingCancels", "lateOutputIgnored", "processesReaped", "concurrentWatcherCancelSafe"},
+ "BlockedBuildInputAndCompilerChangesInvalidate": {"sourceMutationCancels", "configMutationCancels", "manifestMutationCancels", "compilerSettingCancels", "lateOutputIgnored", "processesReaped", "concurrentWatcherCancelSafe", "sharingAcquisitionResponsive", "exactSingleInputMutation"},
"DescriptorCancellationReapsProcessBeforeRestart": {"descriptorBlocked", "cancelCommand", "cleanupRetainsOwnership", "repeatIgnoredDuringCleanup", "processReaped", "restartAfterCleanup"},
"DirtyAliasChangedAfterReadBlocksImmediateBuild": {"descriptorRead", "rdtAliasChanged", "immediateBuildBlocked", "zeroBuildProcesses"},
"PackageDisposalCancelsRunningBuildAndLateResults": {"nativePackageClose", "processCancelled", "lateResultIgnored", "isolatedHostSuffix"},