Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ internal readonly struct TimestampCache
{
private readonly Dictionary<string, DateTime> _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;
}

/// <summary>
Expand All @@ -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 <see langword="null"/>.
/// </summary>
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ internal sealed partial class BuildUpToDateCheck
private ISubscription _subscription;
private int _isDisposed;
private int _checkNumber;
private IEnumerable<string>? _lastCopyTargetsFromThisProject;
private IEnumerable<string>? _lastOutputsFromThisProject;

/// <summary>
/// Gets the set of up-to-date checkers that apply to this project.
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -720,7 +723,7 @@ private bool CheckBuiltFromInputFiles(Log log, in TimestampCache timestampCache,

private bool CheckCopyToOutputDirectoryItems(Log log, UpToDateCheckImplicitConfiguredInput state, IEnumerable<(string Path, ImmutableArray<CopyItem> 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!);

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -952,9 +955,6 @@ private async Task<bool> 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,
Expand All @@ -976,6 +976,11 @@ private async Task<bool> 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 (
Expand All @@ -1002,7 +1007,7 @@ private async Task<bool> IsUpToDateInternalAsync(

logger.FileSystemOperations = fileSystemOperations;

HashSet<string> copyItemPaths = new(StringComparers.Paths);
HashSet<string> outputPaths = new(StringComparers.Paths);

try
{
Expand Down Expand Up @@ -1035,6 +1040,11 @@ private async Task<bool> IsUpToDateInternalAsync(
{
token.ThrowIfCancellationRequested();

if (!isValidationRun)
{
AddPotentialOutputPaths(outputPaths, implicitState);
}

if (logConfigurations)
{
logger.Info(nameof(VSResources.FUTD_CheckingConfiguration_1), implicitState.ProjectConfiguration.GetDisplayString());
Expand Down Expand Up @@ -1074,10 +1084,6 @@ private async Task<bool> 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) ||
Expand Down Expand Up @@ -1140,7 +1146,10 @@ private async Task<bool> IsUpToDateInternalAsync(
_lastFailureReason = logger.FailureReason;
_lastFailureDescription = logger.FailureDescription;

_lastCopyTargetsFromThisProject = copyItemPaths;
if (!isValidationRun)
{
_lastOutputsFromThisProject = outputPaths;
}
}

async ValueTask<bool?> IsBuildAccelerationEnabledAsync(bool isCopyItemsComplete, IReadOnlyList<string>? duplicateCopyItemRelativeTargetPaths, UpToDateCheckImplicitConfiguredInput implicitState)
Expand Down Expand Up @@ -1226,6 +1235,57 @@ private async Task<bool> IsUpToDateInternalAsync(
}
}

private void AddPotentialOutputPaths(HashSet<string> 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<string, ImmutableDictionary<string, ImmutableArray<string>>> itemsByKindBySetName)
{
foreach (ImmutableDictionary<string, ImmutableArray<string>> itemsByKind in itemsByKindBySetName.Values)
{
foreach (ImmutableArray<string> items in itemsByKind.Values)
{
foreach (string path in items)
{
outputPaths.Add(_configuredProject.UnconfiguredProject.MakeRooted(path));
}
}
}
}
}

public Task<bool> IsUpToDateCheckEnabledAsync(CancellationToken cancellationToken = default)
{
return _projectSystemOptions.GetIsFastUpToDateCheckEnabledAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,17 @@ namespace Microsoft.VisualStudio.ProjectSystem.VS.UpToDate;
internal sealed class SolutionBuildContext
{
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public ITimestampCache CopyItemTimestamps { get; }
public ITimestampCache Timestamps { get; }

public SolutionBuildContext(IFileSystem fileSystem)
{
CopyItemTimestamps = new ConcurrentTimestampCache(fileSystem);
Timestamps = new ConcurrentTimestampCache(fileSystem);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public void SetLastWriteTime()
private string? _currentDirectory;

public Dictionary<string, FileData> Files { get; } = new Dictionary<string, FileData>(StringComparer.OrdinalIgnoreCase);
public Dictionary<string, int> LastWriteTimeQueryCounts { get; } = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

public void Create(string path)
{
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ private async Task<UpToDateCheckImplicitConfiguredInput> SetupAsync(
Dictionary<string, IProjectRuleSnapshotModel>? sourceSnapshot = null,
bool disableFastUpToDateCheck = false,
string outDir = _outputPathRelative,
string projectTargetPath = "",
DateTime? lastSuccessfulBuildStartTimeUtc = null,
DateTime? lastItemsChangedAtUtc = null,
UpToDateCheckImplicitConfiguredInput? upToDateCheckImplicitConfiguredInput = null,
Expand All @@ -196,6 +197,7 @@ private async Task<UpToDateCheckImplicitConfiguredInput> SetupAsync(
{ "MSBuildAllProjects", _msBuildAllProjects },
{ "OutputPath", outDir },
{ "OutDir", outDir },
{ ConfigurationGeneral.TargetPathProperty, projectTargetPath },
{ ConfigurationGeneral.DisableFastUpToDateCheckProperty, disableFastUpToDateCheck.ToString() },
{ ConfigurationGeneral.AccelerateBuildsInVisualStudioProperty, _isBuildAccelerationEnabledInProject?.ToString() ?? "" }
}
Expand Down Expand Up @@ -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<string, IProjectRuleSnapshotModel>
{
[UpToDateCheckBuilt.SchemaName] = SimpleItems(@"bin\Debug\Built.dll"),
[ResolvedCompilationReference.SchemaName] = new IProjectRuleSnapshotModel
{
Items = new Dictionary<string, IImmutableDictionary<string, string>>(StringComparers.ItemNames)
{
{
"Reference",
ImmutableStringDictionary<string>.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)]
Expand Down
Loading