diff --git a/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.TimestampCache.cs b/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.TimestampCache.cs index 2b2f028ea7..a2123f20c4 100644 --- a/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.TimestampCache.cs +++ b/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.TimestampCache.cs @@ -10,10 +10,12 @@ internal readonly struct TimestampCache { private readonly Dictionary _timestampCache = new(StringComparers.Paths); private readonly IFileSystem _fileSystem; + private readonly ITimestampCache? _solutionBuildCache; - public TimestampCache(IFileSystem fileSystem) + public TimestampCache(IFileSystem fileSystem, ITimestampCache? solutionBuildCache = null) { _fileSystem = fileSystem; + _solutionBuildCache = solutionBuildCache; } /// @@ -27,11 +29,22 @@ public TimestampCache(IFileSystem fileSystem) /// Otherwise, query the filesystem, cache the result, then return it. /// If the file is not found, return . /// - public DateTime? GetTimestampUtc(string path) + public DateTime? GetTimestampUtc(string path, bool useSolutionBuildCache = false) { if (!_timestampCache.TryGetValue(path, out DateTime time)) { - if (!_fileSystem.TryGetLastFileWriteTimeUtc(path, out DateTime? newTime)) + DateTime? newTime; + + if (useSolutionBuildCache && _solutionBuildCache is not null) + { + newTime = _solutionBuildCache.GetTimestampUtc(path); + } + else if (!_fileSystem.TryGetLastFileWriteTimeUtc(path, out newTime)) + { + return null; + } + + if (newTime is null) { return null; } diff --git a/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.cs b/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.cs index d45174b4c4..9e1f025626 100644 --- a/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.cs +++ b/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/BuildUpToDateCheck.cs @@ -58,7 +58,7 @@ internal sealed partial class BuildUpToDateCheck private ISubscription _subscription; private int _isDisposed; private int _checkNumber; - private IEnumerable? _lastCopyTargetsFromThisProject; + private IEnumerable? _lastOutputsFromThisProject; /// /// Gets the set of up-to-date checkers that apply to this project. @@ -276,7 +276,10 @@ bool CheckInputsAndOutputs(IEnumerable<(string Path, string? ItemType, bool IsRe log.VerboseLiteral(input); - DateTime? inputTime = timestampCache.GetTimestampUtc(input); + bool useSolutionBuildCache = itemType == ResolvedAnalyzerReference.SchemaName + || itemType == ResolvedCompilationReference.SchemaName; + + DateTime? inputTime = timestampCache.GetTimestampUtc(input, useSolutionBuildCache: useSolutionBuildCache); if (inputTime is null) { @@ -641,7 +644,7 @@ private bool CheckMarkers(Log log, in TimestampCache timestampCache, UpToDateChe { log.VerboseLiteral(inputMarker); - DateTime? inputMarkerTime = timestampCache.GetTimestampUtc(inputMarker); + DateTime? inputMarkerTime = timestampCache.GetTimestampUtc(inputMarker, useSolutionBuildCache: true); if (inputMarkerTime is null) { @@ -720,7 +723,7 @@ private bool CheckBuiltFromInputFiles(Log log, in TimestampCache timestampCache, private bool CheckCopyToOutputDirectoryItems(Log log, UpToDateCheckImplicitConfiguredInput state, IEnumerable<(string Path, ImmutableArray CopyItems)> copyItemsByProject, ConfiguredFileSystemOperationAggregator fileSystemAggregator, bool? isBuildAccelerationEnabled, SolutionBuildContext solutionBuildContext, CancellationToken token) { - ITimestampCache timestampCache = solutionBuildContext.CopyItemTimestamps; + ITimestampCache timestampCache = solutionBuildContext.Timestamps; string outputFullPath = Path.Combine(state.MSBuildProjectDirectory!, state.OutputRelativeOrFullPath!); @@ -854,15 +857,15 @@ void IProjectBuildEventListener.NotifyBuildStarting(DateTime buildStartTimeUtc) async Task IProjectBuildEventListener.NotifyBuildCompletedAsync(bool wasSuccessful, bool isRebuild) { - if (_lastCopyTargetsFromThisProject is not null) + if (_lastOutputsFromThisProject is not null) { // The project build has completed. We must assume this project modified its outputs, // so we remove the outputs that were likely modified from our cache. The next requests // for these files will perform a fresh query. - _solutionBuildContextProvider.CurrentSolutionBuildContext?.CopyItemTimestamps?.ClearTimestamps(_lastCopyTargetsFromThisProject); + _solutionBuildContextProvider.CurrentSolutionBuildContext?.Timestamps.ClearTimestamps(_lastOutputsFromThisProject); // We don't use this again after clearing the cache, so release it for GC. - _lastCopyTargetsFromThisProject = null; + _lastOutputsFromThisProject = null; } if (_lastBuildStartTimeUtc == default) @@ -952,9 +955,6 @@ private async Task IsUpToDateInternalAsync( token.ThrowIfCancellationRequested(); - // Short-lived cache of timestamp by path - var timestampCache = new TimestampCache(_fileSystem); - // Ensure we have a context object for the current solution build. // // Ordinarily, this is created when the SBM calls ISolutionBuildEventListener.NotifySolutionBuildStarting, @@ -976,6 +976,11 @@ private async Task IsUpToDateInternalAsync( Assumes.NotNull(solutionBuildContext); } + // Validation runs follow a build and must query the latest timestamps. + var timestampCache = new TimestampCache( + _fileSystem, + isValidationRun ? null : solutionBuildContext.Timestamps); + globalProperties.TryGetValue(FastUpToDateCheckIgnoresKindsGlobalPropertyName, out string? ignoreKindsString); (LogLevel requestedLogLevel, Guid projectGuid) = await ( @@ -1002,7 +1007,7 @@ private async Task IsUpToDateInternalAsync( logger.FileSystemOperations = fileSystemOperations; - HashSet copyItemPaths = new(StringComparers.Paths); + HashSet outputPaths = new(StringComparers.Paths); try { @@ -1035,6 +1040,11 @@ private async Task IsUpToDateInternalAsync( { token.ThrowIfCancellationRequested(); + if (!isValidationRun) + { + AddPotentialOutputPaths(outputPaths, implicitState); + } + if (logConfigurations) { logger.Info(nameof(VSResources.FUTD_CheckingConfiguration_1), implicitState.ProjectConfiguration.GetDisplayString()); @@ -1074,10 +1084,6 @@ private async Task IsUpToDateInternalAsync( var configuredFileSystemOperations = new ConfiguredFileSystemOperationAggregator(fileSystemOperations, isBuildAccelerationEnabled, copyInfo.TargetsWithoutReferenceAssemblies); - string outputFullPath = Path.Combine(implicitState.MSBuildProjectDirectory!, implicitState.OutputRelativeOrFullPath!); - - copyItemPaths.UnionWith(implicitState.ProjectCopyData.CopyItems.Select(copyItem => Path.Combine(outputFullPath, copyItem.RelativeTargetPath))); - if (!CheckGlobalConditions(logger, lastSuccessfulBuildStartTimeUtc, validateFirstRun: !isValidationRun, implicitState) || !CheckInputsAndOutputs(logger, lastSuccessfulBuildStartTimeUtc, timestampCache, implicitState, ignoreKinds, token) || !CheckBuiltFromInputFiles(logger, timestampCache, implicitState, token) || @@ -1140,7 +1146,10 @@ private async Task IsUpToDateInternalAsync( _lastFailureReason = logger.FailureReason; _lastFailureDescription = logger.FailureDescription; - _lastCopyTargetsFromThisProject = copyItemPaths; + if (!isValidationRun) + { + _lastOutputsFromThisProject = outputPaths; + } } async ValueTask IsBuildAccelerationEnabledAsync(bool isCopyItemsComplete, IReadOnlyList? duplicateCopyItemRelativeTargetPaths, UpToDateCheckImplicitConfiguredInput implicitState) @@ -1226,6 +1235,57 @@ private async Task IsUpToDateInternalAsync( } } + private void AddPotentialOutputPaths(HashSet outputPaths, UpToDateCheckImplicitConfiguredInput state) + { + AddItems(state.UpToDateCheckOutputItemsByKindBySetName); + AddItems(state.UpToDateCheckBuiltItemsByKindBySetName); + + if (!Strings.IsNullOrWhiteSpace(state.ProjectTargetPath)) + { + outputPaths.Add(state.ProjectTargetPath); + } + + if (!Strings.IsNullOrWhiteSpace(state.ProjectCopyData.TargetPath)) + { + outputPaths.Add(state.ProjectCopyData.TargetPath); + } + + if (!Strings.IsNullOrWhiteSpace(state.CopyUpToDateMarkerItem)) + { + outputPaths.Add(_configuredProject.UnconfiguredProject.MakeRooted(state.CopyUpToDateMarkerItem)); + } + + foreach ((string destinationRelative, _) in state.BuiltFromInputFileItems) + { + outputPaths.Add(_configuredProject.UnconfiguredProject.MakeRooted(destinationRelative)); + } + + if (!Strings.IsNullOrWhiteSpace(state.MSBuildProjectDirectory) + && !Strings.IsNullOrWhiteSpace(state.OutputRelativeOrFullPath)) + { + string outputFullPath = Path.Combine(state.MSBuildProjectDirectory, state.OutputRelativeOrFullPath); + + foreach (CopyItem copyItem in state.ProjectCopyData.CopyItems) + { + outputPaths.Add(Path.Combine(outputFullPath, copyItem.RelativeTargetPath)); + } + } + + void AddItems(ImmutableDictionary>> itemsByKindBySetName) + { + foreach (ImmutableDictionary> itemsByKind in itemsByKindBySetName.Values) + { + foreach (ImmutableArray items in itemsByKind.Values) + { + foreach (string path in items) + { + outputPaths.Add(_configuredProject.UnconfiguredProject.MakeRooted(path)); + } + } + } + } + } + public Task IsUpToDateCheckEnabledAsync(CancellationToken cancellationToken = default) { return _projectSystemOptions.GetIsFastUpToDateCheckEnabledAsync(cancellationToken); diff --git a/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/SolutionBuildContext.cs b/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/SolutionBuildContext.cs index 80e8eda8e4..1d81a0c7a6 100644 --- a/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/SolutionBuildContext.cs +++ b/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/UpToDate/SolutionBuildContext.cs @@ -11,20 +11,17 @@ namespace Microsoft.VisualStudio.ProjectSystem.VS.UpToDate; internal sealed class SolutionBuildContext { /// - /// A cache of timestamps for the absolute paths of both source and target of copy items - /// across all projects. + /// A cache of timestamps for absolute paths across all projects. /// /// - /// In large solutions we end up checking many, many copy items. These items get their - /// own cache that lasts the duration of the solution build, rather than the default cache - /// which only lasts for the project build. This cache has a high hit rate. As project - /// builds complete, we clear each project's output items from the cache so that we re-query - /// them on the next call. + /// In large solutions, many projects check the same inputs and copy items. This cache lasts + /// for the duration of the solution build. As project builds complete, we clear each + /// project's output items so that future checks query potentially modified files again. /// - public ITimestampCache CopyItemTimestamps { get; } + public ITimestampCache Timestamps { get; } public SolutionBuildContext(IFileSystem fileSystem) { - CopyItemTimestamps = new ConcurrentTimestampCache(fileSystem); + Timestamps = new ConcurrentTimestampCache(fileSystem); } } diff --git a/tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Mocks/IFileSystemMock.cs b/tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Mocks/IFileSystemMock.cs index 6f5318f598..0c6051cf83 100644 --- a/tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Mocks/IFileSystemMock.cs +++ b/tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Mocks/IFileSystemMock.cs @@ -42,6 +42,7 @@ public void SetLastWriteTime() private string? _currentDirectory; public Dictionary Files { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + public Dictionary LastWriteTimeQueryCounts { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); public void Create(string path) { @@ -163,6 +164,9 @@ public DateTime GetLastFileWriteTimeOrMinValueUtc(string path) public bool TryGetLastFileWriteTimeUtc(string path, [NotNullWhen(true)]out DateTime? result) { + LastWriteTimeQueryCounts.TryGetValue(path, out int queryCount); + LastWriteTimeQueryCounts[path] = queryCount + 1; + if (Files.TryGetValue(path, out FileData value)) { result = value.LastWriteTimeUtc; diff --git a/tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/UpToDate/BuildUpToDateCheckTests.cs b/tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/UpToDate/BuildUpToDateCheckTests.cs index f0ac48b990..44d21db134 100644 --- a/tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/UpToDate/BuildUpToDateCheckTests.cs +++ b/tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/UpToDate/BuildUpToDateCheckTests.cs @@ -174,6 +174,7 @@ private async Task SetupAsync( Dictionary? sourceSnapshot = null, bool disableFastUpToDateCheck = false, string outDir = _outputPathRelative, + string projectTargetPath = "", DateTime? lastSuccessfulBuildStartTimeUtc = null, DateTime? lastItemsChangedAtUtc = null, UpToDateCheckImplicitConfiguredInput? upToDateCheckImplicitConfiguredInput = null, @@ -196,6 +197,7 @@ private async Task SetupAsync( { "MSBuildAllProjects", _msBuildAllProjects }, { "OutputPath", outDir }, { "OutDir", outDir }, + { ConfigurationGeneral.TargetPathProperty, projectTargetPath }, { ConfigurationGeneral.DisableFastUpToDateCheckProperty, disableFastUpToDateCheck.ToString() }, { ConfigurationGeneral.AccelerateBuildsInVisualStudioProperty, _isBuildAccelerationEnabledInProject?.ToString() ?? "" } } @@ -254,6 +256,68 @@ public async Task IsUpToDateCheckEnabledAsync_DelegatesToProjectSystemOptions(bo await _buildUpToDateCheck.IsUpToDateCheckEnabledAsync(CancellationToken.None)); } + [Fact] + public async Task IsUpToDateAsync_ReusesReferenceTimestampsAcrossProjectChecksAndInvalidatesOutputsAfterBuild() + { + string resolvedReferencePath = @"C:\Dev\Solution\Reference\obj\Reference.dll"; + + var projectSnapshot = new Dictionary + { + [UpToDateCheckBuilt.SchemaName] = SimpleItems(@"bin\Debug\Built.dll"), + [ResolvedCompilationReference.SchemaName] = new IProjectRuleSnapshotModel + { + Items = new Dictionary>(StringComparers.ItemNames) + { + { + "Reference", + ImmutableStringDictionary.EmptyOrdinal + .Add("CopyUpToDateMarker", "ReferenceMarkerPath") + .Add("ResolvedPath", resolvedReferencePath) + .Add("OriginalPath", resolvedReferencePath) + } + } + } + }; + + DateTime inputTime = DateTime.UtcNow.AddMinutes(-2); + DateTime outputTime = DateTime.UtcNow.AddMinutes(-1); + + _fileSystem.AddFile(resolvedReferencePath, inputTime); + _fileSystem.AddFile(_builtPath, outputTime); + + await SetupAsync( + projectSnapshot, + projectTargetPath: resolvedReferencePath, + lastSuccessfulBuildStartTimeUtc: outputTime); + + string expectedLog = $""" + Build acceleration is not enabled for this project. See https://aka.ms/vs-build-acceleration. + Comparing timestamps of inputs and outputs: + Adding UpToDateCheckBuilt outputs: + {_builtPath} + Adding newest import input: + {_projectPath} + Adding ResolvedCompilationReference inputs: + {resolvedReferencePath} + No inputs are newer than earliest output '{_builtPath}' ({ToLocalTime(outputTime)}). Newest input is '{resolvedReferencePath}' ({ToLocalTime(inputTime)}). + Project is up-to-date. + """; + + await AssertUpToDateAsync(expectedLog); + await AssertUpToDateAsync(expectedLog); + + Assert.Equal(3, _fileSystem.LastWriteTimeQueryCounts[resolvedReferencePath]); + Assert.Equal(4, _fileSystem.LastWriteTimeQueryCounts[_builtPath]); + + ((IProjectBuildEventListener)_buildUpToDateCheck).NotifyBuildStarting(buildStartTimeUtc: DateTime.UtcNow); + await ((IProjectBuildEventListener)_buildUpToDateCheck).NotifyBuildCompletedAsync(wasSuccessful: true, isRebuild: false); + + await AssertUpToDateAsync(expectedLog); + + Assert.Equal(5, _fileSystem.LastWriteTimeQueryCounts[resolvedReferencePath]); + Assert.Equal(6, _fileSystem.LastWriteTimeQueryCounts[_builtPath]); + } + [Theory] [InlineData(BuildAction.Clean)] [InlineData(BuildAction.Compile)]