Repository navigation
Don't let a skipped target overwrite a result from a re-entrant request - #14561
AlesProkop merged 8 commits into
Conversation
Re-entrant build requests for the same configuration share the same BuildResult target-results dictionary, but each gets its own cloned lookup. A target entry can therefore reach TargetEntryState.Completed without ever executing - for instance when its condition evaluated false because the items a previously-skipped target would have produced are not visible in this request's lookup. If the request then blocks (e.g. while pushing before-targets that the other request is actively building), the other request can run that target for real and store a Success result. When the blocked request resumes, the Completed branch of ProcessTargetStack stored its Skipped result unconditionally, which tripped the assert in BuildResult.AddResultsForTarget: MSB0001: Internal MSBuild Error: Items already exist for target X. Keep the real result in that case. A real-over-real collision still asserts, so genuine double-execution bugs are still caught. Co-authored-by: Copilot <[email protected]> Copilot-Session: 13b1bd86-4eb4-4d12-a6d1-7f5e20462f46
When a skipped target loses to a real result from another request, use the winning result for dependency failure processing as well as the shared cache. Co-authored-by: Copilot <[email protected]> Copilot-Session: f5bb470d-e5a6-4f84-8ec6-ec54a965336f
There was a problem hiding this comment.
Pull request overview
Fixes a re-entrancy edge case in MSBuild’s TargetBuilder where a target that completed as skipped (without executing) could later overwrite a real result produced by another re-entrant request sharing the same BuildResult, triggering MSB0001: Internal MSBuild Error: Items already exist for target ....
Changes:
- Guarded
TargetBuilder.ProcessTargetStackso aSkippedTargetResultwill not overwrite an existing non-skipped result for the same target in sharedBuildResultstate. - Ensured dependency-failure propagation follows whichever result “wins” (the existing non-skipped result vs. the would-be overwritten skip).
- Added deterministic regression coverage in
TargetBuilder_Tests, including an opt-inBlockOnTargetInProgresshandler to simulate the re-entrant scenario.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs | Prevents skipped results from overwriting real results in shared per-configuration BuildResult during re-entrant builds; aligns failure propagation with the preserved result. |
| src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs | Adds a regression test for the crash scenario and introduces an opt-in callback handler to simulate a target being blocked while another request completes and records results. |
Suppressed comments (1)
src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs:1552
- Same as above: prefer using the
partialBuildResultparameter instead of reaching into ResultsCache, so the test stays coupled only to the BlockOnTargetInProgress contract.
resultsCache.GetResultsForConfiguration(entry.Request.ConfigurationId)
.AddResultsForTarget("Victim", BuildResultUtilities.GetEmptyFailingTargetResult());
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
Review — PR #14561 · 2 files, +114/−4Methodology: portable core + dotnet/msbuild expert-reviewer · 24/24 dimensions evaluated Verdict: 🔴 REQUEST CHANGES — 1 blocking, 0 major, 0 moderate, 0 nit · 21 of 24 evaluated dimensions clean
|
Add skipped results through a retrying ConcurrentDictionary operation so a real result published between lookup and insertion is preserved. Keep real-over-real collisions asserted and use the stored result for dependency processing. Co-authored-by: Copilot <[email protected]> Copilot-Session: f5bb470d-e5a6-4f84-8ec6-ec54a965336f
Review — PR #14561 · 4 files, +213/−8Methodology: portable core + dotnet/msbuild expert-reviewer · 24/24 dimensions evaluated Verdict: ✅ COMMENT — LGTM · 24 of 24 evaluated dimensions clean ✅ Clean (24)✅ Backwards Compatibility Vigilance — public |
JanProvaznik
left a comment
There was a problem hiding this comment.
Note
This comment was generated by GitHub Copilot CLI.
The core policy here is right — a Skipped result must never overwrite a real one, and publication should be atomic — and I'd like to see this land. Requesting changes on three points: the stated mechanism doesn't match the code, the fix leaves a per-request concern attached to the discarded result (user-visible wrong build outcome, repro below), and the CAS loop silently widens where MSB0001 can fire.
1. The stated mechanism doesn't hold
Re-entrant build requests for the same configuration share the same
BuildResulttarget-results dictionary [...] but each request gets its own cloned lookup.
The first half is correct (BuildResult.cs:252 aliases existingResults._resultsByTarget; TargetBuilder.cs:141). The second half isn't, on the path that matters:
RequestBuilder.cs:1257passes_requestEntry.RequestConfiguration.BaseLookup.BuildRequestConfiguration.cs:683-688memoizes it —_baseLookup ??= new Lookup(...)— so it is one Lookup per configuration, handed to every re-entrant request.TargetBuilder.cs:123-125does clone it, with a comment specifically about re-entrancy isolation — butTargetBuilder.cs:167pushes the target stack with the un-cloned parameter._baseLookupis read in exactly one other place (:259, legacyCallTargetscoping).
This changes what the bug is, which is why it matters. The defect does not require two disagreeing views of the world; it requires one view read at two different times. @(SuggestedBindingRedirects) is empty until the target producing it collapses its scope, so the same condition legitimately evaluates false at T1 and true at T2. That is a much larger and more reachable set of scenarios than "the lookups diverged", and it's what the comment and tests should describe.
(Separately: either that .Clone() is dead and should go, or the clone is what should be threaded into PushTargets. Worth a look on its own.)
2. The window is wider than "pushing before-targets"
Order in ProcessTargetStack's Dependencies case:
CheckSkipTarget <- runs once, here, and never again
PushTargets(afterTargets) <- await; condition NOT yet evaluated
GetDependencies() <- condition evaluated; false => Skipped + state = Completed
PushTargets(beforeTargets) <- await (the window the description cites)
PushTargets(dependencies) <- empty list when the condition was false
The after-targets push suspends before the condition is evaluated, and CheckSkipTarget has already run. So a victim with only AfterTargets hits the identical clobber. Confirmed end-to-end — the repro below reaches MSB0001 through that path, not the before-targets one. The current tests only cover the narrower case.
Suggested framing for both the comment and the tests: any suspension between the decision and the publication — not a specific call site.
Also: neither BeforeTargets nor AfterTargets referencing GenerateBindingRedirects exists anywhere in this repo. Whatever opens the window for the reported target comes from SDK/NuGet targets, not MSBuild. That's worth confirming, because it bears directly on whether this is an 18.8 regression at all — and the PR's own "same stack as #9129 and #1853" suggests a long-standing latent defect rather than a new one.
3. Blocking: a per-request concern is stamped on the discarded result
ProcessTargetStack sets TargetFailureDoesntCauseBuildFailure (from _legacyCallTargetContinueOnError) and TargetLocation on the local targetResult, then may discard it in the preserve path. But BuildResult.OverallResult (BuildResult.cs:392-394) and ComputeAfterTargetFailures (TargetBuilder.cs:809-810) read that flag off the surviving result. So CallTarget ContinueOnError="true" stops masking a failure whenever the target's result came from a re-entrant request.
End-to-end repro, with a control that isolates the single variable.
shared.proj
<Project>
<PropertyGroup>
<TriggerFile>$(MSBuildThisFileDirectory)trigger.txt</TriggerFile>
<StallFile>$(MSBuildThisFileDirectory)stalling.txt</StallFile>
</PropertyGroup>
<Target Name="Build">
<CallTarget Targets="Victim" ContinueOnError="true" />
<Message Text="MARK: Build completed" Importance="high" />
</Target>
<Target Name="Victim" Condition="Exists('$(TriggerFile)')">
<Delete Files="$(TriggerFile)" />
<Error Text="Victim failed on purpose" />
</Target>
<!-- Holds ActivelyBuildingTargets["AfterVictim"] while yielding the node. -->
<Target Name="AfterVictim" AfterTargets="Victim">
<WriteLinesToFile File="$(StallFile)" Lines="stalling" Overwrite="true" />
<Exec Command="ping 127.0.0.1 -n 9 > nul" YieldDuringToolExecution="true" />
</Target>
</Project>p1.proj — request 1, stalls in AfterVictim, then really runs Victim:
<Project DefaultTargets="Go">
<Target Name="Go">
<MSBuild Projects="$(MSBuildThisFileDirectory)shared.proj" Targets="AfterVictim;Victim" ContinueOnError="true" />
</Target>
</Project>p2.proj — request 2, waits until request 1 is provably stalled, then enters the same configuration:
<Project DefaultTargets="Go">
<PropertyGroup>
<StallFile>$(MSBuildThisFileDirectory)stalling.txt</StallFile>
</PropertyGroup>
<Target Name="Go">
<Exec Command="powershell -NoProfile -Command "while (-not (Test-Path '$(StallFile)')) { Start-Sleep -Milliseconds 50 }"" />
<MSBuild Projects="$(MSBuildThisFileDirectory)shared.proj" Targets="Build" />
</Target>
</Project>root.proj
<Project DefaultTargets="Go">
<Target Name="Go">
<Delete Files="$(MSBuildThisFileDirectory)stalling.txt" />
<WriteLinesToFile File="$(MSBuildThisFileDirectory)trigger.txt" Lines="x" Overwrite="true" />
<MSBuild Projects="$(MSBuildThisFileDirectory)p1.proj;$(MSBuildThisFileDirectory)p2.proj" BuildInParallel="true" />
</Target>
</Project>control.proj — same CallTarget / ContinueOnError / failing-victim shape, no re-entrancy:
<Project DefaultTargets="Build">
<Target Name="Build">
<CallTarget Targets="Victim" ContinueOnError="true" />
<Message Text="MARK: Build completed" Importance="high" />
</Target>
<Target Name="Victim">
<Error Text="Victim failed on purpose" />
</Target>
</Project>Run with -m:4 -nr:false. Results with this PR applied:
| outcome | |
|---|---|
control.proj (no re-entrancy) |
Done Building Project "control.proj" — masked, exit 0 |
root.proj (victim's result from a re-entrant request) |
Done Building Project "shared.proj" (Build target(s)) -- FAILED |
The log even prints Build continuing because "ContinueOnError" on the task "CallTarget" is set to "true" immediately before reporting the request failed. Only one variable differs between the two runs.
Two notes on the repro, both non-obvious and both required:
YieldDuringToolExecution="true"— without it request 1 owns the node for the whole stall and no re-entrancy happens at all. A nested<MSBuild>call yields the same way, which is how this arises in real builds.- the sentinel handshake — without it the two requests serialize and the run silently proves nothing. Any test for this area needs to assert that the interleaving actually occurred, otherwise it can pass vacuously.
Requested fix: apply the flag and TargetLocation to the result returned by the publish call rather than the local one. Better still, see §5.
4. The CAS loop widens where MSB0001 can fire
closing the check-to-add race while preserving the
AddResultsForTargetreal-over-real assertion
It doesn't preserve it, it strengthens it:
| two threads, real results, key absent | |
|---|---|
| before | both TryGetValue -> false, both skip the assert, both write; last wins, no throw |
| after | T1 TryAdd wins; T2 TryAdd fails -> loop -> sees T1's real result -> Assumed.Equal(Success, Skipped) -> MSB0001 |
Defensible as a deliberate choice, but it means a fix for MSB0001 can itself introduce MSB0001 in builds that previously worked. Given the no-new-errors policy I'd keep the lenient behaviour and add telemetry, or call the change out explicitly.
5. Suggestion: put the guard at the state-machine hole
CheckSkipTarget runs on entry to Dependencies, Execution and ErrorExecution, but there is no equivalent check before publication in Completed — that asymmetry is the actual hole. Re-checking at the top of Completed, conditional on our own result being Skipped, is roughly the same diff size, covers the whole class rather than one instance, and makes the BuildResult merge policy a backstop instead of the primary mechanism. It also gives a natural place to reconcile the entry's own result, the flags, and the logging together, rather than threading one return value into one branch.
Unrelated bug found while investigating
TargetEntry.cs:371 guards the condition-was-false TargetSkippedEventArgs with MinimumRequiredMessageImportance > MessageImportance.Low. Low is 2, the highest value the enum has and the maximum that property ever returns (LoggingService.cs:858), so the guard is never true and the event is never logged. TaskBuilder.cs got the same treatment in the same commit (d383f82, #12226). Condition-false target and task skips have been silently absent from binlogs since. Not this PR's problem — filing separately — but it's why the "adopt the other request's result" path currently has no log trail at all.
Keep skipped-result publication atomic without changing real-result collision behavior. Preserve legacy CallTarget ContinueOnError for the affected request without mutating shared target results, including transitive after-target failure processing. Co-authored-by: Copilot <[email protected]> Copilot-Session: 65a8d8a6-bc0d-47b7-824c-eca301eaf973
|
Resolved the requested changes in
The original control, re-entrant reproduction, and transitive AfterTargets reproduction all complete with exit code 0. The unrelated condition-false skip logging issue remains out of scope. |
Qualify the AddResultsForTarget overload so XML documentation generation does not emit CS0419 under CI warnings-as-errors. Co-authored-by: Copilot <[email protected]> Copilot-Session: 65a8d8a6-bc0d-47b7-824c-eca301eaf973
JanProvaznik
left a comment
There was a problem hiding this comment.
Request changes: keep the shared result, but preserve the current request's Stop
I support the atomic "an execution result wins over a stale skip" rule in BuildResult. That is the right abstraction level, and keeping the legacy failure exception request-local avoids modifying another request's result. I would keep that design.
There is one remaining control-flow issue at TargetBuilder.cs:555: the result that should remain in the shared cache is not necessarily the result that should decide whether this request continues.
What gets lost
A target result has both an outcome and a next action. A locally skipped target can carry Skipped / Stop, not just Skipped / Continue.
This is intentional. When a before-target fails and its parent was already condition-skipped, failure propagation calls MarkForStop(). That method means: "the target itself was skipped, but its child failed, so do not execute the remaining work."
If publication retains another request's Success / Continue, the new code passes only that retained result to PopDependencyTargetsOnTargetFailure. The unwinder examines its action code, sees Continue, and loses the local Stop.
How this can happen
Consider this target graph, with RunVictim initially false:
| Target | Behavior |
|---|---|
Build |
Depends on Victim;MustNotRun, then executes its own body. |
Victim |
Runs only when RunVictim=true; its body resets the property to false. |
BeforeVictim |
Runs before Victim; fails when RunVictim is false. |
Gate |
Also runs before Victim; sets RunVictim=true, then waits for an independent project. |
Declare BeforeVictim before Gate. Two requests share the configuration: B requests Gate;Victim, and A requests Build.
- B starts Gate and suspends. Its property change is still target-local.
- A evaluates Victim's condition as false, producing Skipped / Continue. It still arranges the before-targets. Because
PushTargetsprocesses that list in reverse, it encounters the active Gate and waits before executing BeforeVictim. - B completes Gate, committing
RunVictim=true. BeforeVictim therefore condition-skips. Victim executes successfully, resetsRunVictim=false, and publishes Success / Continue. - A resumes. BeforeVictim's cached Skipped result allows reevaluation; its condition is now true, so it fails. This changes A's local Victim result to Skipped / Stop.
- Victim's publication correctly retains B's Success / Continue, but line 555 then uses that Continue for A's stack unwinding. MustNotRun and Build's body can execute despite the local before-target failure.
No successfully executed target needs to execute twice: BeforeVictim was only skipped in B.
This interleaving is source-traced, rather than an executed repro. It is a correctness gap in the newly recovered path: before this PR, this exact skip-versus-success collision throws MSB0001. I am not claiming that it regresses a previously successful build. The overall result can still be Failure; executing work that should have been stopped is the issue.
Smallest requested correction
Keep the shared winner and the request-local legacy bookkeeping unchanged. For the single call to the unwinder:
- Use the local result if it already requires Stop.
- Otherwise, use the retained result.
In other words, either result requiring Stop must stop this request. Do not mutate the shared winner or add another result/policy abstraction.
Please add a focused regression using the existing blocking callback: publish Victim Success from the simulated other request, then let a local before-target fail. Assert that the cached Victim remains Success, MustNotRun and Build's body do not execute, and the parent fails.
That is the change I would hold for. A scheduler, lookup-isolation, or general failure-aggregation rewrite would widen the scope unnecessarily.
Co-authored-by: Copilot App <[email protected]>
JanProvaznik
left a comment
There was a problem hiding this comment.
Re-reviewed 1cc7815. The local Stop is now preserved while a retained Stop still propagates, with one unwinder invocation and no mutation of the shared result. This addresses the issue raised in my previous review; no further code changes are requested for that finding.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/3036658
Context
MSBuild can fail with
MSB0001: Items already exist for target <name>when two build requests enter the same project configuration and one resumes after the other has recorded a target result. The resumed request tries to record "I skipped this target" even though the shared results already say the target succeeded or failed. This change keeps the execution result instead of treating that stale skip as an internal error.Which components are involved?
A re-entrant request enters the same project configuration while another request is waiting.
TargetBuilderLookupBuildResult/TargetResultThe reported failure involved
GenerateBindingRedirects, whose condition depends on@(SuggestedBindingRedirects). As shared build-time data changes, the same condition can be false at one point and true later.How does the stale skip happen?
For example:
Before: MSBuild reports an internal error because a result already exists.
After: MSBuild keeps B's execution result and uses it to decide what happens next.
This example pauses while arranging
BeforeTargets. A related conflict can occur while arrangingAfterTargets, before condition evaluation but after the existing-result check. The fix handles either case when recording the skip.Changes Made
BuildResultreceives a skipped result fromTargetBuilder. The check and update are atomic, so another request cannot write into a gap between them.TargetBuilderwhen deciding how to process dependent targets.CallTarget ContinueOnErrorhandling local to the current request, including failure propagation throughAfterTargets.MockTaskBuilderto awaitCallTargetand forwardContinueOnError.Why does failure handling need special care?
If the retained result is a failure,
CallTarget ContinueOnError="true"may still allow the current request to continue. That permission must not change the shared failure or make other requests ignore it. The fix keeps the outcome shared and the exception request-local.This exception only applies when a local skip loses to another request's failure. Failures already visible at the earlier result checks retain their existing behavior.
Testing
The existing validation results for this PR are retained below; no build or tests were rerun for this description update.
MSBUILDFORCEMULTITHREADED=1and.\build.cmd -v quiet: 0 warnings, 0 errors.BuildResult_Tests,TargetBuilder_Tests,TargetEntry_Tests, andTaskBuilder_Testsonnet11.0andnet472: 265 passed, 2 existing skips, 0 failed.CallTarget ContinueOnErrorcontrol, the re-entrant failure case, and a transitiveAfterTargetsvariant all exited with code 0. The re-entrant case reached the marker after the intentionally failing target.Regression tests and what they establish
In
TargetBuilder_Tests:SkippedTargetDoesNotOverwriteResultFromReentrantRequest: forces the earlierAfterTargetssuspension, records another request's success, and verifies that success survives the local skip.FailedTargetPreservedFromReentrantRequestUsesCurrentRequestFailureSemantics: covers the laterBeforeTargetssuspension with ordinary failure propagation and the earlier suspension with legacyCallTarget ContinueOnErrorplus transitiveAfterTargets. Verifies the request's outcome while the shared target result remains a failure.Both tests assert that the blocking callback was reached, so they cannot pass merely because the intended interleaving never happened.
In
BuildResult_Tests:AddResultsForTargetOrPreserveExistingNonSkippedResult_ExistingNonSkippedResult_PreservesExistingResult: retains either an existing success or an existing failure.AddResultsForTargetOrPreserveExistingNonSkippedResult_ConcurrentRealAndSkippedResults_PreservesRealResult: races success and skip publication and verifies that success remains.AddResultsForTarget_ExistingSkippedResult_ReplacesSkippedResult: preserves replacement of an earlier skip.AddResultsForTarget_ExistingNonSkippedResult_Throws: preserves the existing non-skipped-result collision assertion.FilteredResultCanIgnoreUnrequestedLegacyCallTargetFailure: allows the request-local exception without modifying the shared failure or hiding failure when that target itself is explicitly requested.