Skip to content

Don't let a skipped target overwrite a result from a re-entrant request - #14561

Merged
AlesProkop merged 8 commits into
dotnet:mainfrom
AlesProkop:fix/skipped-target-overwrites-reentrant-result
Sep 30, 2026
Merged

AlesProkop merged 8 commits into
dotnet:mainfrom
AlesProkop:fix/skipped-target-overwrites-reentrant-result

Conversation

@AlesProkop

@AlesProkop AlesProkop commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

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.

Component What it does What is shared?
TargetBuilder Coordinates target execution and waits for other work. Each request has its own coordinator.
Lookup Holds build-time properties and items used by target conditions. The configuration's build-time data is shared.
BuildResult / TargetResult Records whether a target succeeded, failed, or was skipped. Requests share the recorded target outcomes.

The 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:

  1. Request A finds no recorded result for the target. Its condition is false, so A plans to skip it.
  2. A pauses to wait for other work.
  3. Build inputs change. Request B runs the same target and records success or failure.
  4. A resumes and tries to record its earlier skip.

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 arranging AfterTargets, before condition evaluation but after the existing-result check. The fix handles either case when recording the skip.

Changes Made

  • Preserved an already-recorded success or failure when BuildResult receives a skipped result from TargetBuilder. The check and update are atomic, so another request cannot write into a gap between them.
  • Used the retained result in TargetBuilder when deciding how to process dependent targets.
  • Kept legacy CallTarget ContinueOnError handling local to the current request, including failure propagation through AfterTargets.
  • Preserved existing behavior for incoming non-skipped results, including the existing collision assertion.
  • Added regression coverage for both suspension windows and updated MockTaskBuilder to await CallTarget and forward ContinueOnError.

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.

  • Repository build with MSBUILDFORCEMULTITHREADED=1 and .\build.cmd -v quiet: 0 warnings, 0 errors.
  • BuildResult_Tests, TargetBuilder_Tests, TargetEntry_Tests, and TaskBuilder_Tests on net11.0 and net472: 265 passed, 2 existing skips, 0 failed.
  • End-to-end reproductions: the non-re-entrant CallTarget ContinueOnError control, the re-entrant failure case, and a transitive AfterTargets variant 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 earlier AfterTargets suspension, records another request's success, and verifies that success survives the local skip.
  • FailedTargetPreservedFromReentrantRequestUsesCurrentRequestFailureSemantics: covers the later BeforeTargets suspension with ordinary failure propagation and the earlier suspension with legacy CallTarget ContinueOnError plus transitive AfterTargets. 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.

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
@AlesProkop
AlesProkop marked this pull request as ready for review August 18, 2026 07:30
Copilot AI lite review requested due to automatic review settings August 18, 2026 07:30

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

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.ProcessTargetStack so a Skipped TargetResult will not overwrite an existing non-skipped result for the same target in shared BuildResult state.
  • 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-in BlockOnTargetInProgress handler 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 partialBuildResult parameter 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.

@AlesProkop

Copy link
Copy Markdown
Member Author

Review — PR #14561 · 2 files, +114/−4

Methodology: portable core + dotnet/msbuild expert-reviewer · 24/24 dimensions evaluated
Mode: Deep
Conversation: Considered 1 existing inline bot comment; it is not applicable to this path because PushTargets passes null as partialBuildResult.

Verdict: 🔴 REQUEST CHANGES — 1 blocking, 0 major, 0 moderate, 0 nit · 21 of 24 evaluated dimensions clean

⚠️ Needs attention (1)

🔴 BLOCKING · Concurrency, Correctness & Test Coverage — The skipped-result check and insertion are not atomic, so the same MSB0001 crash remains possible in a narrower interleaving. · src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs:539

  • Scenario: thread interleaving —
    T=0 Request A: TryGetResultsForTarget("Victim") returns false.
    T=1 Request B: publishes a successful Victim result to the shared ConcurrentDictionary.
    T=2 Request A: calls AddResultsForTarget("Victim", skipped).
    T=3 AddResultsForTarget observes B's non-skipped result and throws MSB0001: Items already exist for target Victim.
  • Why it matters: the PR mitigates the feedback's observed ordering, but does not guarantee that a skipped result can never race a real result; /m or multithreaded scheduling can still hit the check-to-add window.
  • Confidence: High · traced the shared _resultsByTarget ConcurrentDictionary, the new TryGetResultsForTarget branch, and the non-atomic AddResultsForTarget implementation.
  • Fix: move this policy into an atomic BuildResult operation implemented with a TryGetValue/TryAdd/TryUpdate retry loop. It should return the effective result: preserve an existing non-skipped result when the incoming result is skipped, replace an existing skipped result, and retain the real-over-real assertion. Use that returned result for dependency processing and add coverage for a real result winning between the initial absence check and insertion.

✅ Clean (21)

✅ Backwards Compatibility Vigilance — the change is internal and preserves successful target-result semantics.
✅ ChangeWave Discipline — a targeted crash fix does not require an opt-in behavior wave.
✅ Performance & Allocation Awareness — the normal completed-target path adds no allocations or expensive work.
✅ Error Message Quality — no user-facing errors or resource strings are introduced.
✅ Logging & Diagnostics Rigor — existing logging behavior is unchanged.
✅ String Comparison Correctness — target-name comparison remains governed by the existing result dictionary comparer.
✅ API Surface Discipline — no public API or serialization contract changes.
✅ MSBuild Target Authoring Conventions — no target-file behavior is changed.
✅ Design Before Implementation — the winning real result is correctly used for downstream failure processing.
✅ Cross-Platform Correctness — the logic and tests contain no platform-specific behavior.
✅ Code Simplification — the change is localized to result selection and its test seam.
✅ Naming Precision — new identifiers describe their roles clearly.
✅ SDK Integration Boundaries — no SDK or common-target boundary changes.
✅ Idiomatic C# Patterns — constructs match the surrounding nullable-disabled code style.
✅ File I/O & Path Handling — unaffected.
✅ Documentation Accuracy — the PR description states the mitigation scope and validation evidence.
✅ Build Infrastructure Care — no build, CI, or dependency configuration changes.
✅ Scope & PR Discipline — product change and regression coverage remain focused on the reported crash.
✅ Evaluation Model Integrity — lookup isolation and evaluation ordering are intentionally left unchanged.
✅ Dependency Management — no dependencies added or updated.
✅ Security Awareness — no trust-boundary or input-processing changes.

☑️ Fix checklist

  • 🔴 Concurrency — make preserve-real-result/add-skipped an atomic BuildResult operation and test the check-to-add race (BLOCKING)

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
@AlesProkop

Copy link
Copy Markdown
Member Author

Review — PR #14561 · 4 files, +213/−8

Methodology: portable core + dotnet/msbuild expert-reviewer · 24/24 dimensions evaluated
Mode: Deep
Conversation: Considered the existing issue comments, submitted bot review, and inline thread. The prior atomicity blocker is addressed in 5a245c93a0; the inline suggestion to use partialBuildResult does not apply because this test blocks through PushTargets, which passes null.

Verdict: ✅ COMMENT — LGTM · 24 of 24 evaluated dimensions clean

✅ Clean (24)

✅ Backwards Compatibility Vigilance — public AddResultsForTarget behavior is preserved: skipped results remain replaceable and real-over-real collisions still assert.
✅ ChangeWave Discipline — this is a narrow correctness fix for an internal crash path, not a behavior rollout requiring an opt-out wave.
✅ Performance & Allocation Awareness — the hot path uses allocation-free ConcurrentDictionary primitives and only retries on contention.
✅ Test Coverage & Completeness — success, failure, replacement, collision, and concurrent publication paths are covered.
✅ Error Message Quality — the existing searchable Items already exist for target assertion remains unchanged for genuine collisions.
✅ Logging & Diagnostics Rigor — no logging events, levels, or correlation data are removed or altered.
✅ String Comparison Correctness — target keys continue to use the existing ordinal-ignore-case result dictionary.
✅ API Surface Discipline — no new public API or wire-format surface is introduced.
✅ MSBuild Target Authoring Conventions — no target files or build-language semantics are modified.
✅ Design Before Implementation — result arbitration now belongs to BuildResult, the owner of the shared dictionary and its collision contract.
✅ Cross-Platform Correctness — implementation and tests are independent of OS, path, locale, and filesystem behavior.
✅ Code Simplification — TargetBuilder consumes a single returned effective result instead of duplicating result-race policy.
✅ Concurrency & Thread Safety — TryGetValue / TryAdd / TryUpdate retry semantics cover both publication orders and N-way contention.
✅ Naming Precision — the helper name explicitly states when an existing result is preserved.
✅ SDK Integration Boundaries — no SDK assets, common targets, or project-system contracts are affected.
✅ Idiomatic C# Patterns — the retry loop and collection expressions match repository conventions.
✅ File I/O & Path Handling — unaffected.
✅ Documentation Accuracy — the PR description accurately documents the atomic implementation, mitigation scope, and validation.
✅ Build Infrastructure Care — no CI, toolset, packaging, or dependency configuration changed.
✅ Scope & PR Discipline — all changes directly support the reported re-entrant target-result crash and its regression coverage.
✅ Evaluation Model Integrity — cloned lookup semantics remain unchanged; only shared result publication is arbitrated.
✅ Correctness & Edge Cases — successful and failed winning results drive the correct downstream dependency behavior.
✅ Dependency Management — no package or tool dependency changes.
✅ Security Awareness — no new input, execution, serialization, or trust-boundary exposure.

@JanProvaznik JanProvaznik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 BuildResult target-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:1257 passes _requestEntry.RequestConfiguration.BaseLookup.
  • BuildRequestConfiguration.cs:683-688 memoizes it — _baseLookup ??= new Lookup(...) — so it is one Lookup per configuration, handed to every re-entrant request.
  • TargetBuilder.cs:123-125 does clone it, with a comment specifically about re-entrancy isolation — but TargetBuilder.cs:167 pushes the target stack with the un-cloned parameter. _baseLookup is read in exactly one other place (:259, legacy CallTarget scoping).

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 &gt; 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 &quot;while (-not (Test-Path '$(StallFile)')) { Start-Sleep -Milliseconds 50 }&quot;" />
    <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 AddResultsForTarget real-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
@AlesProkop

Copy link
Copy Markdown
Member Author

Resolved the requested changes in 60fa2e24b3:

  1. Corrected the lookup model: top-level re-entrant requests use the configuration's shared BaseLookup; the clone provides a private scope stack for legacy CallTarget.
  2. Covered both suspension windows: AfterTargets before condition evaluation and BeforeTargets after a skipped result is created.
  3. Preserved CallTarget ContinueOnError as request-local policy when a skipped result loses to another request's failure, including transitive after-target processing, without mutating the shared winning TargetResult.
  4. Limited the CAS loop to incoming skipped results, leaving existing non-skipped and real-over-real behavior unchanged.
  5. Kept atomic publication as the state-machine backstop rather than adding a second non-atomic check in Completed.

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 JanProvaznik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

  1. B starts Gate and suspends. Its property change is still target-local.
  2. A evaluates Victim's condition as false, producing Skipped / Continue. It still arranges the before-targets. Because PushTargets processes that list in reverse, it encounters the active Gate and waits before executing BeforeVictim.
  3. B completes Gate, committing RunVictim=true. BeforeVictim therefore condition-skips. Victim executes successfully, resets RunVictim=false, and publishes Success / Continue.
  4. 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.
  5. 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.

@JanProvaznik JanProvaznik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@JanProvaznik
JanProvaznik enabled auto-merge (squash) September 30, 2026 11:44
@AlesProkop
AlesProkop enabled auto-merge (squash) September 30, 2026 13:15
@AlesProkop
AlesProkop merged commit 3e93e1b into dotnet:main Sep 30, 2026
14 checks passed
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.

3 participants