Repository navigation
Keep project active through post-build telemetry - #14679
Conversation
Co-authored-by: Copilot <[email protected]> Copilot-Session: bd117dd2-4173-4f41-8d99-21ef024bf8ad
|
/azp run |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
Validation of the caching guardSetup
$env:MSBUILDDEBUGFORCECACHING='1'
dotnet build MSBuild.slnx --no-restore -mt -v:q
Results
Unpatched engines also failed in ad-hoc runs (stock SDK engine: 4x Observed failure — note this is a different call site than the one originally reported: Both this and |
There was a problem hiding this comment.
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
ProjectInstanceusage counter (AcquireProjectInstanceUsage) to keep a configuration’sProjectInstancein-memory and blockCacheIfPossible()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.
Code reviewVerdict: approve-with-comments. The core fix is correct — the increment ( The race being fixed, for the record: Worth calling out in the commit message: hoisting the retrieval to the top of MajorM1 — The same root-cause race remains at three sibling call sites, and one documents an invariant this PR disproves.
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 Suggest applying M2 — No regression test for the bug that was actually fixed. The new test covers the primitive well, but nothing covers the fix: delete the Also, inside the scope the test only asserts using (configuration.AcquireProjectInstanceUsage())
{
configuration.IsCached.ShouldBeFalse();
instance.PropertiesToBuildWith.ShouldNotBeNull(); // the invariant telemetry depends on
instance.ItemsToBuildWith.ShouldNotBeNull();Minorm1 — A leaked usage count is unrecoverable. End-of-build cleanup deliberately clears the analogous transient state ( m2 — Acquisition can throw before any project logging context exists. The scope constructor does disk I/O ( m3 — The comment is narrower than the bug.
The race isn't MT-specific: in classic single-process mode the sweep already runs on the // 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
Notes on the areas I looked at specificallyLifetime/refcount — Memory — negligible impact. During 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 Perf — clean. The struct scope avoids an allocation and doesn't box (consumed as a concrete-typed Test cleanup — the |
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
|
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
m2: fixed! nits mostly accepted for fixing. |
Follow-up reviewVerdict: 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 Status of every prior item
M1 — verified fixedAll three sites now hold the scope across the whole
Lock ordering unchanged: 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 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.
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 The epoch-stamped-scope alternative isn't worth it: a field per scope and per configuration to fix a leak On 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.
Add a hook to [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:
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 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 (b) Still open, and independent of (a). instance.PropertiesToBuildWith.ShouldNotBeNull();
instance.ItemsToBuildWith.ShouldNotBeNull();Cheap, and it makes the test fail if the guard is ever reordered relative to the actual m2 — verified fixed, correctly
m3 — comment fixed; my re-assessment reverses the servicing conclusion
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:
With New findingsN1 — MAJOR: a fourth sibling site with the identical check-then-act, still unprotected, and this one is not MT-only. Concrete scenario, no
Note 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 Related, worth an issue either way: the scopes don't cover consumption of the retrieved instance. N2 — MODERATE: the PR description's memory-impact argument doesn't hold for non-MT multi-proc. I'm not asking you to restructure N3 — NIT: N4 — NIT: Dimensions re-checked and clean given the new commits: ChangeWave (still not warranted), performance (no allocation or boxing at the three new sites; Servicing / backportDo not backport. My m3 re-assessment inverts my earlier tentative recommendation: the crash this PR fixes requires two request engines sharing one 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 |
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
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 accessedRequestConfiguration.Project, which fails 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
ProjectInstanceusage counter toBuildRequestConfiguration:CacheIfPossible()skips configurations with active project 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:
IsCacheable = false, so the long-running portion ofBuildProject()was already protected from caching.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.