Skip to content

Keep project active through post-build telemetry - #14679

Merged
AR-May merged 10 commits into
dotnet:mainfrom
AR-May:fix-telemetry-active-build-guard
Aug 13, 2026
Merged

AR-May merged 10 commits into
dotnet:mainfrom
AR-May:fix-telemetry-active-build-guard

Conversation

@AR-May

@AR-May AR-May commented Aug 10, 2026

Copy link
Copy Markdown
Member

Co-authored-by: Copilot [email protected]

Context

Under memory pressure, MSBuild serializes inactive project configurations to disk to reduce memory use.  CacheIfPossible()  previously considered a configuration safe to cache once it had no actively executing targets.

In multithreaded mode, multiple request engines run in the same process and share the configuration cache. After a project's last target completed, another request engine could sweep the configuration while the original request was still executing post-build telemetry.  UpdateStatisticsPostBuild()  then accessed  RequestConfiguration.Project , which fails when the configuration is cached:

 MSB0001: Internal MSBuild Error: We shouldn't be accessing the ProjectInstance when the configuration is cached.

Traditional multiprocess builds do not normally expose this race because each worker process owns a separate configuration cache, and its memory sweep does not run concurrently in the middle of that request's  BuildProject()  execution.

Changes Made

Add a scoped  ProjectInstance  usage counter to  BuildRequestConfiguration :

  • Entering the scope retrieves the project if it was previously cached and increments the usage count under the configuration lock.
  •  CacheIfPossible()  skips configurations with active project usage.
  • Disposing the scope decrements the count under the same lock.
  • The counter supports nested or overlapping usage.

 BuildProject()  holds this scope for its full lifetime, ensuring the project remains available through post-build telemetry.

Why protect the whole  BuildProject()  operation?

A narrower set of scopes would leave short intervals where an MT cache sweep could serialize the project, only for the next scope to immediately retrieve it. Protecting the complete operation avoids that unnecessary disk churn.

The memory-retention impact is limited:

  • In MT mode, the potentially long cross-node results-transfer wait is skipped because all thread nodes share the same results cache.
  • Target execution already sets  IsCacheable = false , so the long-running portion of  BuildProject()  was already protected from caching.
  • In non-MT mode, another request engine cannot concurrently sweep this configuration: other workers have separate caches, and the current engine processes its completion-triggered sweep only after  BuildProject()  returns. The scope therefore changes no practical caching behavior there beyond small lock/counter overhead.

Testing

Added unit test ProjectInstanceUsagePreventsConfigurationCaching. Unfortunately can not create a deterministic regression test for the error.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: bd117dd2-4173-4f41-8d99-21ef024bf8ad
@AR-May

AR-May commented Aug 10, 2026

Copy link
Copy Markdown
Member Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@AR-May

AR-May commented Aug 10, 2026

Copy link
Copy Markdown
Member Author

Validation of the caching guard

Setup

  • Repo under test: dotnet/msbuild itself (MSBuild.slnx) — this is what reproduced the failure.
  • A/B isolated to this change only: baseline = parent e45cc3de8a, patched = cf54e451a5. Both built as bootstrap SDKs and copied outside artifacts/, so the engine under test isn't overwritten by the build it is running.
  • Repro command:
$env:MSBUILDDEBUGFORCECACHING='1'
dotnet build MSBuild.slnx --no-restore -mt -v:q
  • Each iteration is cold: dotnet build-server shutdown, kill leftover nodes, wipe artifacts/, restore, then build.

Results

Engine Cold-clean crashes
Baseline (no fix) 2 / 6
Patched 0 / 6

Unpatched engines also failed in ad-hoc runs (stock SDK engine: 4x MSB0001). The patched engine did not fail in any run (~9 total) and completed with 0 errors on the same cycles where baseline died.

Observed failure — note this is a different call site than the one originally reported:

BuildRequestConfiguration.get_Project()
  <- ProjectLoggingContext.CreateLoggingContext
  <- RequestBuilder.HandleProjectStarted
  <- RequestBuilder.BuildProject()

Both this and UpdateStatisticsPostBuild sit inside the new scope (RequestBuilder.cs:1146), which is consistent with the fix addressing them.

@AR-May
AR-May marked this pull request as ready for review August 10, 2026 15:37
Copilot AI lite review requested due to automatic review settings August 10, 2026 15:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses a multithreaded race where a BuildRequestConfiguration can be memory-pressure cached after the last target finishes, while the original request is still running post-build telemetry that reads RequestConfiguration.Project, causing an internal error. It introduces a scoped ProjectInstance usage counter on the configuration and holds that scope for the full lifetime of RequestBuilder.BuildProject() so the configuration cannot be cached mid-operation.

Changes:

  • Add a scoped ProjectInstance usage counter (AcquireProjectInstanceUsage) to keep a configuration’s ProjectInstance in-memory and block CacheIfPossible() while in use.
  • Hold that scope for the entire RequestBuilder.BuildProject() execution to cover post-build telemetry.
  • Add a unit test validating that active usage prevents configuration caching (including nested usage).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
src/Build/BackEnd/Shared/BuildRequestConfiguration.cs Adds a usage-scoped counter and updates CacheIfPossible() to skip caching while the project instance is actively in use.
src/Build/BackEnd/Components/RequestBuilder/RequestBuilder.cs Acquires the new usage scope for the full BuildProject() lifetime to prevent caching during post-build telemetry.
src/Build.UnitTests/BackEnd/BuildRequestConfiguration_Tests.cs Adds a unit test ensuring active project usage blocks configuration caching (including nested usage).

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@ViktorHofer

Copy link
Copy Markdown
Member

Code review

Verdict: approve-with-comments. The core fix is correct — the increment (BuildRequestConfiguration.cs:669) and the guard read (:769) both happen under _syncLock, so there's no residual TOCTOU, and the using declaration releases on every exception path out of BuildProject including BuildAbortedException. I built the branch and ran BuildRequestConfiguration_Tests (43/43 pass).

The race being fixed, for the record:

T=0  RequestBuilder thread : _targetBuilder.BuildTargets(...) returns.
                             TargetBuilder.cs:207 restored IsCacheable = true,
                             TargetBuilder.cs:530 removed the last ActivelyBuildingTargets entry.
T=1  BuildRequestEngine thr: another request completes -> EvaluateRequestStates
                             -> CheckMemoryUsage -> ConfigCache.WriteConfigurationsToDisk
                             -> CacheIfPossible(): guard passes, _project.Cache() nulls
                                _globalProperties/_properties/_items, IsCached = true.
T=2  RequestBuilder thread : UpdateStatisticsPostBuild() reads RequestConfiguration.Project
                             -> Assumed.False(IsCached) -> InternalErrorException, build dies.

Worth calling out in the commit message: hoisting the retrieval to the top of BuildProject also fixes a latent InternalErrorException at RequestBuilder.cs:1185, where the SDK-resolved-environment-variable block read .Project before the old RetrieveFromCache() call site.

Major

M1 — The same root-cause race remains at three sibling call sites, and one documents an invariant this PR disproves.
ProjectCacheService.cs:844-850, ProjectCacheService.cs:494-500, BuildRequestEngine.cs:386-393

HandleProjectFinishedAsync does the identical check-then-act:

if (requestConfiguration.IsCached) { requestConfiguration.RetrieveFromCache(); }
// <-- sweep thread can CacheIfPossible() here
List<ProjectCacheDescriptor> d = GetProjectCacheDescriptors(requestConfiguration.Project).ToList();

Same T=1/T=2 interleaving — this runs post-build, so IsActivelyBuilding is false and IsCacheable has been restored. ShouldUseCache (:494) has the same shape. And BuildRequestEngine.cs:386-388 carries a comment asserting that config.RetrieveFromCache(); ... resultToReport.ProjectStateAfterBuild = config.Project; is safe "since only one thread can run in the BuildRequestEngine at a time" — exactly the invariant this PR contradicts, given the shared ConfigCache singleton.

Suggest applying using var _ = config.AcquireProjectInstanceUsage(); at those sites — that's what the new primitive is for. If that's out of scope here, please file a follow-up, reference it from the new comment at RequestBuilder.cs:1146, and correct the now-false safety comment at BuildRequestEngine.cs:386-388 so the next reader doesn't rely on it.

M2 — No regression test for the bug that was actually fixed.
BuildRequestConfiguration_Tests.cs:675-729

The new test covers the primitive well, but nothing covers the fix: delete the using at RequestBuilder.cs:1149 and the whole suite still passes. MSBUILDDEBUGFORCECACHING=1 (BuildRequestEngine.cs:153, consumed at :927) makes an engine-level test feasible — forced caching drives WriteConfigurationsToDisk on the engine thread while request builders are in their post-target tail.

Also, inside the scope the test only asserts IsCached.ShouldBeFalse() — the flag, not the state that matters. The neighbouring test at :421-424 proves CacheIfPossible nulls the instance collections, so:

using (configuration.AcquireProjectInstanceUsage())
{
    configuration.IsCached.ShouldBeFalse();
    instance.PropertiesToBuildWith.ShouldNotBeNull();   // the invariant telemetry depends on
    instance.ItemsToBuildWith.ShouldNotBeNull();

Minor

m1 — A leaked usage count is unrecoverable. BuildRequestConfiguration.cs:131, BuildManager.cs:2521-2528

End-of-build cleanup deliberately clears the analogous transient state (config.ActivelyBuildingTargets.Clear()), but _projectInstanceUsageCount is never reset. Concrete path: WaitForCancelCompletion (RequestBuilder.cs:290-310) times out on a hung task, throws UnableToCancel, and abandons the request thread — the using never runs. In VS, ClearNonExplicitlyLoadedConfigurations keeps ExplicitlyLoaded configurations across builds, so that ProjectInstance can never be evicted again for the life of devenv.exe. Suggest an internal void ResetProjectInstanceUsage() called alongside the ActivelyBuildingTargets.Clear() loop.

m2 — Acquisition can throw before any project logging context exists. RequestBuilder.cs:1149-1150

The scope constructor does disk I/O (RetrieveFromCache → File.OpenRead, converting DirectoryNotFoundException/UnauthorizedAccessException into CacheFileInaccessible). That call previously sat after HandleProjectStarted, so failures were attributed to the project; now it precedes _projectLoggingContext = null; and ProjectFirstEncountered, so a failure logs as UnhandledMSBuildError on the node context with no ProjectStarted/Finished pair in the binlog and no EndProjectRequest on the BuildCheck manager. Rare (AV or temp cleanup deleting Configuration{id}.cache), but a diagnostics regression. Either move the null assignment above the acquisition and wrap it in the same catch that builds the temporary ProjectLoggingContext (~:1198-1207), or say in the comment that node-level reporting is intentional here.

m3 — The comment is narrower than the bug. RequestBuilder.cs:1146-1148

"MT request engines share the configuration cache."

The race isn't MT-specific: in classic single-process mode the sweep already runs on the BuildRequestEngine thread while RequestBuilder runs on s_dedicatedScheduler, against the same ConfigCache singleton. This matters beyond wording — it determines whether this is a servicing/backport candidate. Suggested:

// The configuration cache is shared across the node and swept for memory pressure on the
// BuildRequestEngine thread (CheckMemoryUsage -> ConfigCache.WriteConfigurationsToDisk).
// A configuration becomes cacheable again as soon as its last target completes, but post-build
// telemetry still reads its ProjectInstance. Pin the project for the whole operation. See #<issue>.

Nits

  • BuildRequestConfiguration.cs:657-681 — ProjectInstanceUsageScope is a readonly struct with a side-effecting constructor; a copy underflows the counter and default(...) throws ArgumentNullException from lock (null). The pattern has repo precedent (ProjectRootElementCache.ReentrancyGuard, FileAccessManager.HandlerRegistration) so it's fine, but consider making the constructor private (the nested type can still be constructed from AcquireProjectInstanceUsage) and adding an Assumed.NotNull(_configuration, ...) at the top of Dispose.
  • BuildRequestConfiguration_Tests.cs:679 — suggest CacheIfPossible_WhileProjectInstanceUsageIsHeld_DoesNotCache to match MethodUnderTest_Scenario_ExpectedResult.
  • BuildRequestConfiguration_Tests.cs:702-728 — the class already has _env; _env.WithTransientTestState(...) could carry the ClearCacheFile() cleanup and own the ProjectCollection instead of the manual try/finally.
  • BuildRequestConfiguration_Tests.cs:714 — prefer public async Task + await Task.Run(configuration.CacheIfPossible) over .GetAwaiter().GetResult().
  • BuildRequestConfiguration.cs:645-651 — the pin is per-configuration, but ShallowCloneWithNewId (:1079) hands two configuration objects the same _project with independent locks and counters. Benign today (the source is discarded and never cached), but worth a sentence in the doc comment so nobody later assumes the pin protects the ProjectInstance itself.
  • Please reword commit cf3f8b5 ("Refactor") when squashing.

Notes on the areas I looked at specifically

Lifetime/refcount — lock is recursive so the nested RetrieveFromCache() is fine; the increment is placed after the Assumed.False(IsCached) check, so a failed acquisition can't leak a count; lock ordering is unchanged (only CacheIfPossible takes _syncLock → _project). Nested/re-entrant requests on the same configuration each take their own count, so the refcount rather than a bool is the right call. _projectInstanceUsageCount is correctly not translated in Translate — node-local transient state must start at 0 on the receiving node.

Memory — negligible impact. During TargetBuilder.BuildTargets the configuration is already unpinnable (IsCacheable forced false at TargetBuilder.cs:133, restored at :207; and while blocked on child requests the target is still in ActivelyBuildingTargets). The newly-pinned windows are project load/evaluation and the post-target telemetry tail, where the instance is in active use anyway. The only genuinely new window is the results-transfer block at RequestBuilder.cs:1247-1256 (non-MT multi-node), which is brief. Peak memory in large builds should be unchanged.

ChangeWave — not warranted, and I'd argue against one: no new or changed diagnostics, no property defaults, no CLI surface, no output-format change. The only observable delta is that a configuration isn't evicted during a sub-second window in which eviction was never safe. Gating a crash fix behind opt-in would leave the InternalErrorException on by default. Do consider servicing/backport though — see m3, since the MT framing affects that call.

Perf — clean. The struct scope avoids an allocation and doesn't box (consumed as a concrete-typed using local). Cost is one uncontended Monitor.Enter/Exit pair per project build plus an int comparison in CacheIfPossible, correctly ordered cheapest-first. No LINQ or string formatting added to a hot path.

Test cleanup — the finally + ClearCacheFile() at :727 is reliable, and the only other test writing Configuration1.cache (:420) is in the same class, so xUnit collection serialization prevents a collision. No cross-test leakage.

@AR-May AR-May self-assigned this Aug 11, 2026
AR-May added 4 commits August 12, 2026 14:45
Hold ProjectInstance usage scopes while project cache and results-transfer paths access configuration project state.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 0676fd4d-7cfb-4f3a-8acd-1e68b7d9f1c5
Create a temporary project logging context when acquiring the ProjectInstance usage scope fails, while retaining the scope for the full build operation.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 0676fd4d-7cfb-4f3a-8acd-1e68b7d9f1c5
Describe the node-wide configuration cache and BuildRequestEngine memory-pressure sweep without implying the race is MT-specific.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 0676fd4d-7cfb-4f3a-8acd-1e68b7d9f1c5
Document per-configuration ownership, diagnose default scope disposal, and modernize the cache-prevention test with async execution and TestEnvironment cleanup.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: 0676fd4d-7cfb-4f3a-8acd-1e68b7d9f1c5
@AR-May

AR-May commented Aug 12, 2026

Copy link
Copy Markdown
Member Author

M1: fixed!

M2: I already noted in the PR description that I can not create a deterministic regression test for the error.

m1: I don’t think we should reset the usage count during end-of-build cleanup. A cancellation timeout does not terminate the request task, so the task may still resume and access the ProjectInstance. Its active scope therefore remains valid and correctly tracked. Resetting the count in this case actually can corrupt tracking across builds: a new operation could increment the reset counter, then the old operation could resume and decrement it, leaving the count at zero while the new operation is still active. That would allow the project to be cached while in use -> bug.

In fact I think that defensive config.ActivelyBuildingTargets.Clear() might lead to bug with server! Example:

  1. Old request records target Build .
  2. Cleanup clears ActivelyBuildingTargets .
  3. A new request records its own Build  target.
  4. The old request resumes and executes Remove("Build") .
  5. It accidentally removes the new request’s entry.

m2: fixed!

nits mostly accepted for fixing.

@ViktorHofer

Copy link
Copy Markdown
Member

Follow-up review

Verdict: approve-with-comments. M1, m2 and m3 are properly fixed and the fixes are themselves correct. On m1 you're right and I withdraw it — with stronger evidence than either of us cited. On M2 I have to hold the line: a deterministic engine-level regression test is feasible, and I built and ran one to prove it. Two new findings, one major.

Re-ran BuildRequestConfiguration_Tests: 43/43 pass.

Status of every prior item

# Item Status
M1 Same race at three sibling .Project sites ✅ Fixed — all three, correctly
M2a No regression test for the actual bug ❌ Disputed → I hold the line. Deterministic test proven feasible (built + ran)
M2b New test asserts the flag, not the state ❌ Not addressed in commits 3–7
m1 Leaked usage count is unrecoverable 🔵 Disputed → I concede. Withdrawn.
m1′ Your claim that ActivelyBuildingTargets.Clear() is itself a latent bug ✅ Credible — please file separately
m2 Acquisition can throw before any project logging context exists ✅ Fixed, binlog/BuildCheck pairing intact
m3 Comment narrower than the bug ✅ Comment fixed — but my re-assessment reverses the servicing answer
nit 1 readonly struct ctor/default hazards 🟡 Partial — Assumed.NotNull added in Dispose (BuildRequestConfiguration.cs:679); ctor still internal (:665)
nit 2 Test naming convention ✅ Fixed
nit 3 Use _env / WithTransientTestState ✅ Fixed
nit 4 async Task + await Task.Run ✅ Fixed
nit 5 Document ShallowCloneWithNewId sharing ✅ Fixed (BuildRequestConfiguration.cs:649-653)
nit 6 Commit titled "Refactor" ⏳ Open — squash-time cleanup

M1 — verified fixed

All three sites now hold the scope across the whole .Project use, with no leaked counts and no new lock-ordering edge:

  • ProjectCacheService.cs:493-498 — using declaration; GetProjectCacheDescriptors(...).Any() forces the lazy enumerable inside the scope. Correct.
  • ProjectCacheService.cs:840-845 — good catch restructuring to .ToList() inside a using block rather than letting a lazy enumerable escape the scope.
  • BuildRequestEngine.cs:385-395 — scope covers both .Project and the result preparation; the false comment ("only one thread can run in the BuildRequestEngine at a time") is gone.

Lock ordering unchanged: ShouldUseCache is still called under BuildManager._syncLock, and the config _syncLock was already taken on that path by the old RetrieveFromCache(). No boxing at any of the three sites (using on a statically-typed struct calls Dispose directly).


m1 — you're right, I withdraw it. Here's stronger evidence than either of us had.

Your decrement-underflow argument is correct on its own terms, and Dispose makes it worse than you claimed: Assumed.True(_projectInstanceUsageCount > 0, ...) (BuildRequestConfiguration.cs:683) is not [Conditional("DEBUG")]. So a reset followed by a resumed abandoned scope's Dispose doesn't silently underflow — it throws InternalErrorException on a live build. My suggestion would have converted a benign leak into a crash.

But the decisive point is one neither of us raised: the leak I described already exists, unfixed, in the same code path — and resetting the counter wouldn't even remove the pin.

TargetBuilder.cs:132-133 sets configuration.IsCacheable = false, and the restore at :207 sits after the try/finally, i.e. on the success path only. Any exception out of ProcessTargetStack — including the BuildAbortedException thrown at :187-189 on cancellation — skips it, and BuildManager.Reset() (BuildManager.cs:2521-2526) clears ActivelyBuildingTargets but does not reset IsCacheable. So in your exact WaitForCancelCompletion → UnableToCancel scenario (RequestBuilder.cs:288-311), the configuration is already permanently unpinnable via IsCacheable == false, regardless of _projectInstanceUsageCount.

Which also answers "which failure mode is worse": moot. The spurious-unpin risk you identified is real, and the pin it would relieve is already held by another flag. Do nothing. If you want to close the loop cheaply, a one-line comment on _projectInstanceUsageCount (BuildRequestConfiguration.cs:128-131) noting that the count is intentionally never force-reset — because an abandoned request may still resume and dispose its scope — would save the next reviewer this whole round-trip.

The epoch-stamped-scope alternative isn't worth it: a field per scope and per configuration to fix a leak IsCacheable already causes anyway.

On ActivelyBuildingTargets.Clear() being a latent bug — I agree, and it's worse than your sketch. TargetBuilder.cs:485 writes and :180/:508/:530/:631 remove from a plain Dictionary<string,int>, and Remove(name) is unconditional — it doesn't check the stored GlobalRequestId — so a resumed stale thread removes whatever entry is there. And with Reset() running concurrently with a still-live abandoned thread you have unsynchronized Dictionary mutation, which can corrupt the dictionary outright, not just lose an entry. Real, exotic, and squarely a separate issue — please file it rather than growing this PR.


M2 — holding the line on (a); (b) is still open

(a) A deterministic engine-level regression test is feasible. I wrote one and ran it.

RequestBuilder_Tests already drives the real RequestBuilder.BuildProject() end to end against a MockHost, with a mock target builder (RequestBuilder_Tests.cs:492, TestTargetBuilder) and direct access to the real IConfigCache (:94). That gives a synchronous seam at exactly the T=1 moment of the race: whatever the mock target builder does immediately before returning runs on the RequestBuilder thread, between "last target finished" and UpdateStatisticsPostBuild(). No sleeps, no thread racing, no MSBUILDDEBUGFORCECACHING.

Add a hook to TestTargetBuilder, invoked just before it returns its result (RequestBuilder_Tests.cs:510-552):

[Fact]
public void BuildProject_ConfigurationCacheSweepAfterLastTarget_DoesNotCacheConfiguration()
{
    BuildRequestConfiguration configuration = CreateTestProject(1);
    try
    {
        var targetBuilder = (TestTargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder);
        var configCache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache);
        configCache.AddConfiguration(configuration);

        BuildRequest request = CreateNewBuildRequest(1, ["target1"]);
        var entry = new BuildRequestEntry(request, configuration, CreateStubTaskEnvironment());
        var result = new BuildResult(request);
        result.AddResultsForTarget("target1", GetEmptySuccessfulTargetResult());
        targetBuilder.SetResultsToReturn(result);

        bool? cachedDuringPostBuild = null;

        // Simulate the BuildRequestEngine memory-pressure sweep landing in the window between the
        // last target finishing and BuildProject() returning.
        targetBuilder.ActionBeforeReturningResult = () =>
        {
            configCache.WriteConfigurationsToDisk();
            cachedDuringPostBuild = configuration.IsCached;
        };

        _requestBuilder.BuildRequest(GetNodeLoggingContext(), entry);
        WaitForEvent(_buildRequestCompletedEvent, "Build Request Completed");

        cachedDuringPostBuild.ShouldBe(false);
        _buildRequestCompleted_Entry.Result.Exception.ShouldBeNull();
        Assert.Equal(BuildResultCode.Success, _buildRequestCompleted_Entry.Result.OverallResult);
    }
    finally
    {
        configuration.ClearCacheFile();
        DeleteTestProject(configuration);
    }
}

Measured, on this branch:

  • With your using at RequestBuilder.cs:1162-1163 in place → passes.
  • With that using removed and the old RetrieveFromCache() restored → fails:
    Shouldly.ShouldAssertException : cachedDuringPostBuild should be False but was True
    

So it's not "non-deterministic and awkward" — it's fully deterministic and about 30 lines. One caveat worth a comment in the test: without the fix this asserts on IsCached, not on an InternalErrorException, because UpdateStatisticsPostBuild() returns early when no telemetry collector is attached. Asserting the state is the right assertion anyway — it's the invariant the PR establishes, and it also covers the HandleProjectStarted → ProjectLoggingContext.CreateLoggingContext → .Project site from your own repro.

I'd like this in the PR. It's the difference between "the mechanism works" and "the caller uses the mechanism", and it's what stops someone deleting that using in six months.

(b) Still open, and independent of (a). BuildRequestConfiguration_Tests.cs:710 asserts only configuration.IsCached.ShouldBeFalse(). The neighbouring test at :417-424 shows what CacheIfPossible actually does — nulls GlobalPropertiesDictionary / ItemsToBuildWith / PropertiesToBuildWith. That's the state post-build telemetry reads. Please add inside the scope:

instance.PropertiesToBuildWith.ShouldNotBeNull();
instance.ItemsToBuildWith.ShouldNotBeNull();

Cheap, and it makes the test fail if the guard is ever reordered relative to the actual _project.Cache() call.


m2 — verified fixed, correctly

AcquireProjectInstanceUsageWithProjectLoggingContext() (RequestBuilder.cs:1316-1327) restores project-scoped diagnostics on the disk-I/O failure path. Verified:

  • CreateTemporaryProjectLoggingContext() (:1329-1336) uses the (nodeLoggingContext, request, projectFullPath, toolsVersion) overload, which passes projectProperties: null, projectItems: null — so it does not touch .Project and cannot throw a second MSB0001 while reporting the first failure. Important, since on this path the configuration is still cached.
  • ProjectStarted/ProjectFinished pair: the ctor logs ProjectStarted, and ReportResultAndCleanUp logs ProjectFinished for any non-null _projectLoggingContext. The error lands via RequestThreadProc's (_projectLoggingContext ?? _nodeLoggingContext).LogError(..., "UnhandledMSBuildError", ...) — now project-scoped.
  • BuildCheck pairing intact: the acquire is before HandleProjectStarted (which calls StartProjectRequest), and the throw exits before the try whose finally calls EndProjectRequest. Neither runs — symmetric.

m3 — comment fixed; my re-assessment reverses the servicing conclusion

RequestBuilder.cs:1158-1161 now reads "The configuration cache is shared across the node and may be swept for memory pressure on a BuildRequestEngine thread" — accurate and no longer MT-only. Good.

But I now believe the specific telemetry crash is effectively MT-only, and I withdraw that half of m3. I tried to build a non-MT interleaving and couldn't:

  • CheckMemoryUsage() only runs from EvaluateRequestStates() when completedEntries.Count > 0 (BuildRequestEngine.cs:832-834).
  • EvaluateRequestStates asserts at most one Active entry per engine (:791, Assumed.Null(activeEntry, "Multiple active requests")), and only an Active entry's RequestBuilder is inside BuildProject().
  • So a non-MT engine needs a Complete entry coexisting with an Active one whose builder happens to be in the post-target window. Completed entries are reaped by EvaluateRequestStates itself, and the engine ActionBlock is FIFO with DOP 1, so the reap-and-sweep action runs before the activation action that would put another request in that window.

With -mt, multiple engines share the one ConfigCache and the assertion is per-engine, so the overlap is trivially reachable — consistent with your A/B (2/6 baseline failures under -mt, 0/9 patched).


New findings

N1 — MAJOR: a fourth sibling site with the identical check-then-act, still unprotected, and this one is not MT-only.
ProjectCacheService.cs:530-540 and :558-573.

530:  EvaluateProjectIfNecessary(cacheRequest.Submission, cacheRequest.Configuration);
534:      cacheRequest.Configuration.Project,          // <- unguarded
538:      evaluationId: cacheRequest.Configuration.Project.EvaluationId,
540:      projectFile: cacheRequest.Configuration.Project.FullPath);
...
560:  lock (configuration)                             // <- NOT _syncLock; a different lock object
572:      configuration.Project.TranslateEntireState = true;

Concrete scenario, no -mt required:

  • PostCacheRequest runs its body on a thread-pool thread (Task.Run, :514).
  • NodeProviderInProc.cs:358 passes the BuildManager's own _componentHost to InProcNode, so the in-proc node's BuildRequestEngine and the BuildManager share one ConfigCache singleton.
  • T=0 pool thread: EvaluateProjectIfNecessary → LoadProjectIntoConfiguration returns; the configuration is now IsLoaded, IsCacheable, not actively building.
  • T=1 engine thread: another request completes → EvaluateRequestStates → CheckMemoryUsage → WriteConfigurationsToDisk → CacheIfPossible(). The new guard at BuildRequestConfiguration.cs:775 passes (count is 0 — nobody acquired), _project.Cache() nulls the collections, IsCached = true.
  • T=2 pool thread: configuration.Project.TranslateEntireState = true (:572) or cacheRequest.Configuration.Project (:534) → Assumed.False(IsCached) → MSB0001: We shouldn't be accessing the ProjectInstance when the configuration is cached.

Note lock (configuration) at :560 locks the configuration object, not _syncLock, so it provides zero mutual exclusion against CacheIfPossible. Reachable on the command line with a global project-cache plugin plus memory pressure; not reachable in devenv.exe, since CheckMemoryUsage early-returns when RunningInVisualStudio.

Pre-existing, so not a regression from this PR — but it's the same root cause you just fixed three instances of, in the same file, and it's the one instance that doesn't need -mt. Recommend wrapping ProcessCacheRequestAsync's prologue in a scope covering :530-540, and replacing lock (configuration) at :560 with an AcquireProjectInstanceUsage() scope around :562-573. If you'd rather not grow the PR, file it — but leave a comment at :534 so it isn't lost.

Related, worth an issue either way: the scopes don't cover consumption of the retrieved instance. BuildRequestEngine.cs:394 hands config.Project to resultToReport.ProjectStateAfterBuild and releases the scope at the end of that block, but the same ProjectInstance object is later serialized on the endpoint write pump, or handed by reference to the BuildManager on an in-proc endpoint. A later sweep calls Cache() on that same object, nulling _globalProperties/_properties/_items in place and gutting a ProjectStateAfterBuild someone else still holds. Same shape at ProjectCacheService.cs:544. Pre-existing; out of scope here.

N2 — MODERATE: the PR description's memory-impact argument doesn't hold for non-MT multi-proc.
RequestBuilder.cs:1243-1251. The description says "In MT mode, the potentially long cross-node results-transfer wait is skipped because all thread nodes share the same results cache" — true, NeedsResultsTransfer returns false in MT. But in non-MT multi-proc it returns true, and await BlockOnTargetInProgress(...) now sits inside the pin. During that wait the configuration has just been evaluated, has no active targets, and IsCacheable is still true — i.e. it's exactly the prime eviction candidate the sweep exists for, and it's now pinned for a full scheduler round trip plus cross-node transfer. Combined with N1's point that the config cache is shared with the BuildManager, this isn't purely theoretical on a worker node under memory pressure.

I'm not asking you to restructure BuildProject; the "avoid disk churn" rationale is sound and the exposure is one configuration. But please either (a) replace that bullet in the description with "the results-transfer wait is a new pin window in non-MT multi-proc; judged acceptable because it's a single configuration and the alternative is a crash", or (b) release and re-acquire around :1243-1251. I'd take (a).

N3 — NIT: BuildRequestEngine.cs:386-387's comment is narrower than the hazard it guards. Align it with the better wording you used at RequestBuilder.cs:1159-1161 ("the configuration cache is shared across the node…") rather than "multiple in-proc request engines".

N4 — NIT: ProjectInstanceUsageScope's ctor (BuildRequestConfiguration.cs:665) is still internal. A nested type can be constructed from a private ctor by its enclosing type, so private costs nothing and closes the "someone constructs one directly and copies it" footgun that the Assumed.NotNull in Dispose only half-closes.

Dimensions re-checked and clean given the new commits: ChangeWave (still not warranted), performance (no allocation or boxing at the three new sites; .Any()/.ToList() forcing inside the scopes is correct and cold-path), string comparison, cross-platform, file I/O, API surface, evaluation model, security, dependencies, build infrastructure. Translation correctly still excludes _projectInstanceUsageCount — node-local transient state must start at 0 on the receiving node.


Servicing / backport

Do not backport. My m3 re-assessment inverts my earlier tentative recommendation: the crash this PR fixes requires two request engines sharing one ConfigCache, which only happens under -mt. -mt is opt-in and not present in servicing branches, so shipping to main only is correct.

The one thing that would have justified servicing — a non-MT-reachable instance of the same race — is N1, and that path is pre-existing, requires a project-cache plugin plus real memory pressure, and is excluded in devenv.exe. Fix it in main; don't service it.

Follow-up issues worth filing: (1) the unprotected .Project accesses in ProjectCacheService (N1); (2) ProjectStateAfterBuild outliving its pin; (3) IsCacheable never restored on the exception path at TargetBuilder.cs:207; (4) your ActivelyBuildingTargets.Clear() concern.

AR-May and others added 3 commits August 13, 2026 10:32
Covers that RequestBuilder holds a ProjectInstance usage scope for the
whole BuildProject operation, so a concurrent memory-pressure sweep of
the configuration cache cannot cache the configuration out from under it.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: b48c6f3f-d2af-474b-b74f-0cbac2330a5e
ProcessCacheRequestAsync evaluated the configuration and then read its
ProjectInstance unpinned, handing the live instance to the plugin for the
duration of the cache query. The in-proc node's BuildRequestEngine shares
the BuildManager's configuration cache, so its memory-pressure sweep could
cache the configuration to disk in that window and gut the instance the
plugin was reading. Hold a ProjectInstance usage scope for the whole
operation.

The existing lock on the configuration object does not help here: it is a
different monitor from the one CacheIfPossible takes. Document that it only
serializes the check-then-act on loading the project.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: b48c6f3f-d2af-474b-b74f-0cbac2330a5e
CacheIfPossible nulls GlobalPropertiesDictionary, PropertiesToBuildWith and
ItemsToBuildWith on the ProjectInstance. Those collections are what post-build
consumers dereference, so assert them directly at the point where a sweep was
refused. Asserting only IsCached would still pass if the usage guard were ever
reordered after the call that gutted the instance.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: b48c6f3f-d2af-474b-b74f-0cbac2330a5e
This was referenced Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants