msbuild icon indicating copy to clipboard operation
msbuild copied to clipboard

Fix ObjectDisposedException race in ProjectItemInstance.TaskItem.EnumerateMetadata

Open lewing opened this issue 5 months ago • 10 comments

Summary

Materialize IMetadataContainer.EnumerateMetadata eagerly in both Microsoft.Build.Execution.ProjectItemInstance.TaskItem and Microsoft.Build.Utilities.TaskItem, replacing the yield return ... over ImmutableDictionary<string, string> with a single pre-sized array.

Evidence

A dump captured by arcade#16715's MSBuild-crash dump-on-fail logging from public CI build 1472222 produced a stack trace of ObjectDisposedException thrown from ProjectItemInstance.TaskItem.EnumerateMetadata's compiler-generated iterator while Microsoft.Build.Logging.BuildEventArgsWriter.Write(ITaskItem) was serializing a TaskParameterEventArgs on the binary-logger thread. The crash surfaces upstream as MSB4166 "child node exited prematurely". This is the long-standing umbrella tracked as dotnet/runtime#92290.

What the fix does

Both implementations of IMetadataContainer.EnumerateMetadata() previously had two code paths:

  • An eager path (returned a KeyValuePair<string, string>[]) used only inside #if FEATURE_APPDOMAIN when crossing an AppDomain boundary.
  • A lazy path (foreach (...) { yield return ...; }) used in the mainline case.

This PR removes the lazy path on both types and makes the eager path unconditional. The existing EnumerateMetadataEager is lifted out of #if FEATURE_APPDOMAIN and tightened from new List<>(count) + .ToArray() (two collections) to a single pre-sized KeyValuePair<string, string>[] with an empty-case short-circuit returning [] (no allocation).

Net per call:

Before (lazy mainline) After (eager)
Heap allocations 1 state-machine box 1 array (or Array.Empty<>)
Captures pooled ImmutableDictionary.Enumerator across yield boundaries yes no
Cross-AppDomain serializable no yes

Why eager removes the hazard (and what we are not claiming)

ImmutableDictionary<K, V>.Enumerator is a struct whose traversal stack is rented from a BCL-internal SecureObjectPool (SortedInt32KeyNode.Enumerator.ThrowIfDisposed is the throw site in the dump). The previous yield return form parked a copy of that struct in the compiler-generated state machine's heap fields, so the pooled stack's lifetime was effectively tied to the iterator's, not to a single stack frame. The exact interleaving under which the pool slot gets reclaimed while the binary-logger thread is mid-MoveNext is not fully proven — and per @rainersigwald's review the pool's [ThreadStatic] design rules out the original "two threads share a slot" framing. What this fix demonstrates is that eager materialization confines the ImmutableDictionary enumeration to a single stack frame on the caller's thread and hands the consumer back an ordinary KeyValuePair<string, string>[] whose lifetime has no relationship to the BCL enumerator pool. That removes the entire class of issues without depending on the exact trigger.

Historical context

This is a generalisation of #6382 / ac7dd0f3 (Kirill Osenkov, Apr 2021), which introduced the eager-when-crossing-AppDomain path to fix #6379 — a customer crash where the same yield return ... iterator captured a cross-AppDomain proxy that outlived the AppDomain it pointed into, producing AppDomainUnloadedException mid-MoveNext on the same TaskParameterEventArgs.WriteMetadata path. The hazard pattern is structurally the same; only the captured state and its lifetime owner differ. The 2021 PR explicitly preserved the lazy path because "in the general case we want to stream metadata directly to consumers without allocating a collection." Five years later, the BCL-pool variant of the same hazard has surfaced via #92290, and the consumers of EnumerateMetadata (BuildEventArgsWriter.Write, LogMessagePacket.WriteMetadata, console-logger walks, RAR test scaffolds) all fully enumerate to the end before doing anything else — no caller realises a streaming benefit. Removing the lazy path is therefore not paying for safety.

Pattern audit (re-done)

After the github-actions automated review correctly flagged that I had missed src/Utilities/TaskItem.cs, I re-audited src/Build, src/Framework, src/Tasks, and src/Utilities for the same yield return ... ImmutableDictionary shape. Findings:

  • src/Build/Instance/ProjectItemInstance.cs — fixed here.
  • src/Utilities/TaskItem.cs — fixed here.
  • src/Shared/TaskParameter.cs has an EnumerateMetadataLazy but it iterates a plain Dictionary<string, string> (not ImmutableDictionary) and is intentionally out of scope.

No other matches.

Tests

Added structural regression tests on both TaskItem types (EnumerateMetadata_ReturnsMaterializedSnapshot_NotYieldIterator) asserting two invariants:

  1. result.ShouldBeOfType<KeyValuePair<string, string>[]>() — the caller gets a materialized array, not a generated iterator state machine.
  2. Snapshot semantics: mutate the item after EnumerateMetadata() returns, then assert the returned sequence still reflects the pre-mutation state. A streaming iterator over the underlying dictionary would have observed the mutation.

Both tests fail against the pre-fix source on both TaskItem types (verified by reverting the two source files to the parent commit while keeping the new tests in place). I deliberately did not add a behavioural test attempting to provoke the ObjectDisposedException itself — given the mechanism uncertainty above, any timing-based repro would be flaky on CI, which is strictly worse than no test.

Local test runs after the revision:

Test class Passed Skipped
Microsoft.Build.UnitTests.OM.Instance.TaskItem_Tests 14/14 0
Microsoft.Build.UnitTests.TaskItemTests (Utilities) 24/24 1 (Windows-only)
Microsoft.Build.UnitTests.BinaryLoggerTests 80/80 1
Microsoft.Build.UnitTests.TaskParameter_Tests 45/45 0

Notes

  • The mechanism-explanation comment in ProjectItemInstance.cs is intentionally hedged after @rainersigwald's review pointed out that pool slots are [ThreadStatic]. The XML doc on EnumerateMetadataEager describes what the fix achieves (lifetime confinement) rather than overclaiming the exact disposing interleaving.
  • Tightened eager path allocates fewer collections than the historical AppDomain-crossing eager path it replaces.

[!NOTE] AI-assisted PR draft (Copilot CLI). Triple-check before relying on it.

lewing avatar Jun 19 '26 21:06 lewing

Review findings — PR #14115

The core fix (eager materialization of ImmutableDictionary in ProjectItemInstance.TaskItem.EnumerateMetadata) is correct and well-explained. Three issues need attention before merge.


🔴 MAJOR — Same race left unfixed in Utilities/TaskItem.cs

Microsoft.Build.Utilities.TaskItem.EnumerateMetadataLazy() (lines 589–601) contains the identical pattern this PR fixes:

private IEnumerable<KeyValuePair<string, string>> EnumerateMetadataLazy()
{
    if (_metadata == null) { yield break; }
    foreach (var kvp in _metadata)
    {
        var unescaped = new KeyValuePair<string, string>(kvp.Key, EscapingUtilities.UnescapeAll(kvp.Value));
        yield return unescaped;   // ← parks ImmutableDictionary.Enumerator across yield boundary
    }
}

_metadata is ImmutableDictionary<string, string> (line 52). The same SecurePooledObject pool-slot race applies. Every user-authored task that produces output items goes through this path. The fix from ProjectItemInstance.TaskItem should be applied here too.


🟡 MAJOR — No regression test

The PR description mentions that existing tests pass, but no new test covers the race scenario. The bug is hard to reproduce deterministically, but a test that validates the structural invariant (return type is a materialized array, not a lazy iterator) would prevent silent reversion:

[Fact]
public void EnumerateMetadata_ReturnsMaterializedArray_NotLazyIterator()
{
    var item = new ProjectItemInstance(...);
    // Verify that IMetadataContainer.EnumerateMetadata() returns
    // a KVP[] (or at minimum completes enumeration without ObjectDisposedException
    // when called concurrently from multiple threads).
    var result = ((IMetadataContainer)taskItem).EnumerateMetadata();
    result.ShouldBeOfType<KeyValuePair<string, string>[]>();
}

A concurrent stress test (N threads iterating the same item simultaneously) would directly prove the fix holds.


🔵 MODERATE — Stale call-site comment (ProjectItemInstance.cs lines 1129–1131)

The public EnumerateMetadata() method's comment now says:

// Mainline scenario, returns an iterator to avoid allocating an array
// to store the results. With the iterator, results can stream to the
// consumer (e.g. binlog writer) without allocations.

After this PR, EnumerateMetadata(list) unconditionally allocates a KeyValuePair[]. The comment is factually wrong and actively misleads future maintainers — it provides a rationale for reverting the fix. Please update it, e.g.:

// Mainline scenario — eagerly materializes into an array to avoid the
// ImmutableDictionary.Enumerator pool-sharing race (see method body).

NIT — EnumerateMetadataEager (AppDomain path) now slightly less efficient

EnumerateMetadataEager (lines 1202–1213) still uses new List<T>(count) + .ToArray() (two allocations), while the new EnumerateMetadata uses a pre-sized array (one allocation). Both are correct; this is a minor inconsistency worth aligning in a follow-up.

Generated by Expert Code Review (on open) for issue #14115 · 827.9 AIC · ⊞ 30K ambient context · ◷

github-actions[bot] avatar Jun 19 '26 21:06 github-actions[bot]

Pushed cdd66681 addressing all four review findings (two from @rainersigwald, two MAJOR from the automated review):

Mechanism overclaim (rainer #1). Softened the source comment and PR rationale: pool slots are [ThreadStatic], so the original "two threads share a pool slot via the same dict" framing was wrong. What the fix actually proves out is that eager materialization ends the pooled-enumerator lifetime inside a single stack frame on the caller's thread, which removes the class of issues the dumps from arcade#16715 surfaced.

Use existing helper (rainer #2). Dropped the new EnumerateMetadata(ImmutableDictionary) wrapper. EnumerateMetadataEager is lifted out of #if FEATURE_APPDOMAIN and tightened to a single pre-sized array allocation (was List<> + ToArray() = 2 allocs).

Missed identical pattern in Microsoft.Build.Utilities.TaskItem (automated, MAJOR). Removed EnumerateMetadataLazy (which was the same yield return _metadata over the same ImmutableDictionary type). IMetadataContainer.EnumerateMetadata now always calls the eager path. My original audit excluded src/Utilities — that was wrong.

No regression test (automated, MAJOR). Added structural tests on both TaskItem types asserting that EnumerateMetadata() returns a non-iterator type (no <EnumerateMetadata> in the runtime type name). A future revert of the fix becomes observable without having to reproduce the race itself.

Local runs after the revision:

  • Microsoft.Build.UnitTests.OM.Instance.TaskItem_Tests: 14/14
  • Microsoft.Build.UnitTests.TaskItemTests (Utilities): 24/24 (+1 skipped, Windows-only)
  • Microsoft.Build.UnitTests.BinaryLoggerTests: 80/80 (+1 skipped)
  • Microsoft.Build.UnitTests.TaskParameter_Tests: 45/45
  • New EnumerateMetadata_ReturnsMaterializedSnapshot_NotYieldIterator test on both types: 1/1 each

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 19 '26 22:06 lewing

Followup on the regression test — verified it fails against the pre-fix source. Reverted just the two source files to the parent commit (e775a976) while keeping the new tests:

Build.UnitTests — EnumerateMetadata_ReturnsMaterializedSnapshot_NotYieldIterator:
  Expected: result.GetType().FullName should not contain "<EnumerateMetadata"
  Actual:   "Microsoft.Build.Execution.ProjectItemInstance+TaskItem+<EnumerateMetadata>d__49"
  Result:   FAILED (1/1)

Utilities.UnitTests — EnumerateMetadata_ReturnsMaterializedSnapshot_NotYieldIterator:
  Expected: result.GetType().FullName should not contain "<EnumerateMetadata"
  Actual:   "Microsoft.Build.Utilities.TaskItem+<EnumerateMetadataLazy>d__39"
  Result:   FAILED (1/1)

After restoring the fix both tests pass. So a future revert of either site is observable without having to reproduce the ODE race itself.

I intentionally did not add a behavioral test that tries to provoke the ObjectDisposedException — because the exact race mechanism is uncertain (per your earlier comment), any such test would be timing-dependent and likely flaky on CI, which is strictly worse than no test. The structural test pins what the fix is about (no yield-iterator over ImmutableDictionary) rather than what it nondeterministically prevents.

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 19 '26 23:06 lewing

Pulled the history on why the eager/lazy split exists in the first place — it's directly relevant to this PR's direction:

ac7dd0f3 (Apr 2021, #6382, @KirillOsenkov) introduced the split to fix #6379:

Caused by #6155 … We have a situation where we are in a worker node and a task runs in a separate AppDomain and logs a TaskParameterEventArgs. Since logging is asynchronous there's a risk that by the time the node packet translator accesses the TaskParameterEventArgs.Items the AppDomain is already unloaded and we crash when trying to enumerate item metadata.

Customer stack trace was AppDomainUnloadedException thrown from inside IMetadataContainer.EnumerateMetadata → TaskParameterEventArgs.WriteMetadata. The fix was: eager-snapshot when crossing AppDomain, keep yield return for the mainline because "in the general case we want to stream metadata directly to consumers without allocating a collection to store the results."

The hazard pattern is structurally the same as what we're fixing now:

2021 (#6379) 2026 (#92290)
Yield iterator captures a cross-AppDomain proxy a copy of the pooled ImmutableDictionary.Enumerator struct
…whose lifetime ends when the worker AppDomain unloads when its pooled traversal stack is returned to the BCL pool
…mid-serialization on the logger thread, surfacing as AppDomainUnloadedException ObjectDisposedException (SortedInt32KeyNode.Enumerator.ThrowIfDisposed)

So this PR is really a generalization of Kirill's 2021 fix: instead of "no yield-iterator across AppDomain boundaries", make it "no yield-iterator over volatile/pooled state, period."

The 2021 "we want to stream without allocating a collection" rationale doesn't hold up well in 2026 either:

  • The only real consumers (TaskParameterEventArgs.WriteMetadata, the RAR test paths) fully enumerate to the end before they care about anything else — there's no streaming benefit being realized.
  • The tightened EnumerateMetadataEager in this PR allocates less than the original eager path: one pre-sized KeyValuePair[] vs. List<> + .ToArray() = 2 collections, with an empty-case short-circuit returning [].

Happy to fold any of this into the PR description if it'd help future readers.

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 19 '26 23:06 lewing

Pushed 8fbc83ee strengthening the regression tests per a self-rubber-duck pass:

  • Replaced FullName.ShouldNotContain("<EnumerateMetadata") with ShouldBeOfType<KeyValuePair<string, string>[]>() — asserts the actual invariant the fix is about (caller gets a materialized array), not the absence of a particular compiler-generated iterator name.
  • Added a behavioural snapshot assertion: mutate the item after EnumerateMetadata returns, then assert the returned sequence still reflects the pre-mutation state. A streaming iterator over the underlying dictionary would have observed the mutation.

Both strengthened tests still fail against the pre-fix source on both TaskItem types (re-verified).

Also refreshed the PR description to match 8fbc83ee: removed stale references to the now-deleted EnumerateMetadata(ImmutableDictionary) wrapper, removed the over-confident original mechanism prose, expanded the historical-context section, and noted that src/Shared/TaskParameter.cs's EnumerateMetadataLazy was audited and is intentionally out of scope (iterates a plain Dictionary<string, string>, not ImmutableDictionary).

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 19 '26 23:06 lewing

Followup — went back to read the IL <EnumerateMetadata>d__49 actually produces and the BCL SecureObjectPool / AllocFreeConcurrentStack source. The mechanism is more precise than I'd originally written but also more precise than "uncertain":

What the state machine actually parks (IL from current MSBuild build of Microsoft.Build.dll):

.class nested private '<EnumerateMetadata>d__49' ...
  .field private valuetype [System.Collections.Immutable]ImmutableDictionary`2/Enumerator<string, string> '<>7__wrap1'
  ...
  // MoveNext:
  IL_0023: callvirt ImmutableDictionary`2::GetEnumerator()       // rents pool slot S, sets S.Owner = T1.PoolUserId
  IL_0028: stfld '<>7__wrap1'                                    // COPIES the Enumerator struct (incl. S reference + _poolUserId snapshot) into the heap-allocated state machine

So the heap state-machine object embeds a value-type copy of the Enumerator. That struct carries (a) a reference to SecurePooledObject<Stack<...>> S (a shared heap object) and (b) the renting thread's _poolUserId captured at GetEnumerator() time.

What SecureObjectPool actually does (System.Collections.Immutable/SecureObjectPool.cs + AllocFreeConcurrentStack.cs):

[ThreadStatic] applies to the outer Stack<> container, not to the SecurePooledObject instances. AllocFreeConcurrentStack<T>.TryAdd explicitly pushes onto the current thread's TLS stack (with the BCL comment "Just in case we're in a scenario where an object is continually requested on one thread and returned on another, avoid unbounded growth" — they knew about cross-thread migration but only guarded against unbounded growth).

So the pool slot S migrates between TLS stacks every time Free() and TryTake() run on different threads.

The race:

  1. T1 (task thread) runs MoveNext first transition → GetEnumerator() rents S from T1's TLS, stfld copies Enumerator into state-machine heap. T1 enqueues TaskParameterEventArgs on the logging queue and continues task execution.
  2. T2 (logger thread) dequeues and iterates the state machine to completion. <>m__Finally1 calls Dispose on the embedded struct → SecureObjectPool.TryAdd sees caller.PoolUserId (T1) == item.Owner (T1) so it accepts the return → sets S.Owner = UnassignedId and pushes S onto T2's TLS stack (because Free always pushes onto the current thread).
  3. T2 begins serializing the next queued event from T1 → its state machine's first MoveNext calls GetEnumerator() → TryTake from T2's TLS returns S, sets S.Owner = T2.PoolUserId.
  4. Meanwhile T1 (or T2 on a still-queued earlier state machine) iterates a parked state machine that captured S before step 2. S.Use(ref this) checks caller.PoolUserId (T1) == _owner (T2) → mismatch → ObjectDisposedException out of SortedInt32KeyNode.Enumerator.ThrowIfDisposed. That's exactly the dump captured via arcade#16715 on build 1472222.

The earlier comment "two threads share a pool slot via the same dict" was indeed wrong — it's not the dict that's shared, it's the pool slot S that migrates between thread-local stacks via the state-machine handoff. Reads of the embedded Enumerator on a thread whose PoolUserId no longer matches S.Owner throw ODE. That makes Rainer's [ThreadStatic] observation correct (where the stack lives) and the mechanism specific (what the pool slot actually does once it's been pushed onto the consumer's TLS).

Why eager materialization fixes it deterministically: the entire GetEnumerator() → MoveNext()* → Dispose() lifecycle now happens within a single stack frame on T1 before the state-machine box ever escapes. S is rented and returned on T1; all uses see _owner = T1.PoolUserId. The returned KeyValuePair[] carries no reference to anything pooled.

I'll fold a tightened version of the above into the EnumerateMetadataEager XML doc comment in the next push — the current comment is honestly under-claiming now that we have IL + BCL source confirming the chain. Happy to skip the mechanism detail in the PR description and just link this comment instead if you'd prefer to keep the rationale prose short there.

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 19 '26 23:06 lewing

Better still — the BCL documents this exact anti-pattern on the enumerator struct itself, and predicts the symptoms.

From SortedInt32KeyNode.Enumerator.cs lines 14-23 (the actual <remarks> on the public Enumerator struct that backs ImmutableDictionary, ImmutableList, ImmutableSortedDictionary, ImmutableSortedSet):

CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data corruption and/or exceptions.

The C# compiler's yield return over this struct does exactly what the caution forbids — stfld '<>7__wrap1' copies the value-type Enumerator into the state machine's heap field (IL excerpt below). Cross-thread state-machine handoff makes the copy be in use by the consumer thread after the producer thread's iterator path has disposed it. The dump symptom (ODE out of ThrowIfDisposed) is one of the two outcomes the BCL author called out ahead of time.

// <EnumerateMetadata>d__49 state machine, MoveNext (pre-fix MSBuild)
.field private valuetype ImmutableDictionary`2/Enumerator<string,string> '<>7__wrap1'
...
IL_0023: callvirt instance Enumerator ImmutableDictionary`2::GetEnumerator()
IL_0028: stfld    Enumerator '<EnumerateMetadata>d__49'::'<>7__wrap1'   // ← the forbidden copy

So the framing simplifies: this isn't a thread-safety bug in ImmutableDictionary.Enumerator; the BCL has an explicit, long-standing caution against copying it. foreach (... in ImmutableDictionary) yield return ... violates that caution structurally, regardless of whether the iteration ever escapes a thread. Removing the iterator stops doing the forbidden thing.

I'll fold this into the next push (likely tomorrow morning) as the canonical rationale on EnumerateMetadataEager, replacing the softer "lifetime is harder to reason about" prose. It's also a nice complement to the structural test, which now reads as: "assert we don't structurally violate the documented BCL caution."

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 19 '26 23:06 lewing

Correction to my earlier mechanism walk-through — @lewing pinned me on it and I was over-confident.

Re-reading the IL: GetEnumerator() is called from inside the first MoveNext(), not at iterator construction. Every subsequent MoveNext/Current/Dispose operates on the heap field <>7__wrap1 by address (ldflda), so there is no second live copy of the Enumerator struct. Whichever thread first calls MoveNext is the thread that rents S from its own TLS, mutates the field in place to completion, and disposes — all on one thread. The transient CIL-stack value between callvirt GetEnumerator() and stfld is never independently used or Disposed.

That collapses the scenarios:

Scenario Safety
Single-thread iteration of a state-machine iterator Safe — only one live copy of the struct
Producer thread T1 enqueues the boxed IEnumerable, logger thread T2 iterates start→finish Safe — entire rent/use/dispose lifecycle is on T2
T1 calls MoveNext once (populating <>7__wrap1 on T1), then hands the IEnumerator to T2 to continue Unsafe — S was rented on T1, T2's Dispose pushes to T2's TLS, mis-resolution becomes possible
Reentrant / aliased enumeration where two state machines simultaneously hold references to S (one finishes/disposes while the other is mid-MoveNext) Unsafe — this is exactly the BCL CAUTION's "two copies in use"

The MSBuild logger queue pattern is "T1 enqueues IEnumerable, T2 iterates fully" — which by the table above is safe in isolation. So my earlier "S migrates from T1's TLS to T2's TLS via the state-machine handoff" story doesn't actually fit the simplest reading of the IL; T1 never rents S in that flow.

What does happen, and remains a defensible justification for the fix:

  1. The BCL CAUTION is a categorical statement about the value-type enumerator's copy semantics. The yield return foreach (… in <ImmutableThing>) pattern produces a state-machine field copy; whether that specific copy triggers the documented hazard depends on the surrounding iteration pattern, but the pattern itself is exactly the kind the CAUTION warns about.
  2. The crash in arcade#16715's dump from build 1472222 does land in EnumerateMetadata's iterator inside BuildEventArgsWriter.Write. The exact trigger most likely involves some additional aliasing/reentrancy condition (e.g. a Message formatting path enumerating the same item before/while the logger does, or two events sharing the same underlying _directMetadata reference) that I haven't traced concretely from the dump yet.
  3. Eager materialization removes the categorical hazard regardless of which specific trigger fired in any given dump.

I'm going to try to pull the dump and read the actual frames to confirm the precise trigger — will post a follow-up. In the meantime, please mentally discount the cross-thread-migration walkthrough I posted earlier; the BCL CAUTION + IL-shape arguments stand on their own.

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 22 '26 14:06 lewing

Got the dump-equivalent — pulled the Helix console log for the WBT work item that triggered KBE #92290 on this build. The exact stack from the failing run:

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Collections.Immutable.SortedInt32KeyNode`1+Enumerator[
                [System.Collections.Immutable.ImmutableDictionary`2+HashBucket[string, string], ...]]'.
   at System.Collections.Immutable.Requires.FailObjectDisposed[TDisposed](TDisposed)
   at System.Collections.Immutable.SortedInt32KeyNode`1.Enumerator.MoveNext()
   at System.Collections.Immutable.ImmutableDictionary`2.Enumerator.MoveNext()
   at Microsoft.Build.Execution.ProjectItemInstance.TaskItem.EnumerateMetadata(ImmutableDictionary`2 list)+MoveNext()
   at Microsoft.Build.Logging.BuildEventArgsWriter.Write(ITaskItem item, bool writeMetadata)
   at Microsoft.Build.Logging.BuildEventArgsWriter.WriteTaskItemList(IEnumerable items, bool writeMetadata)
   at Microsoft.Build.Logging.BuildEventArgsWriter.Write(TargetFinishedEventArgs e)
   at Microsoft.Build.Logging.BuildEventArgsWriter.Write(BuildEventArgs e)
   at Microsoft.Build.Logging.BinaryLogger.Write(BuildEventArgs e)
   at Microsoft.Build.BackEnd.Logging.EventSourceSink.RaiseAnyEvent(BuildEventArgs)
   at Microsoft.Build.BackEnd.Logging.LoggingService.RouteBuildEvent(BuildEventArgs)
   at Microsoft.Build.BackEnd.Logging.LoggingService.RouteBuildEvent(object loggingEvent)
   at Microsoft.Build.BackEnd.Logging.LoggingService.LoggingEventProcessor(object loggingEvent)

What this concretely confirms:

  1. The throw site is the +MoveNext() of EnumerateMetadata(ImmutableDictionary list) — exactly the state-machine method this PR removes.
  2. **The disposed object is SortedInt32KeyNode1+EnumeratoroverImmutableDictionary<HashBucket<string,string>>** — i.e. the pool-backed enumerator that backs TaskItem._directMetadata`.
  3. The call comes via LoggingEventProcessor → RouteBuildEvent → RaiseAnyEvent — that's the asynchronous logging queue's consumer thread pump (LoggingService._eventQueue).
  4. The serialized event is TargetFinishedEventArgs and the iteration is over e.Items → per-item EnumerateMetadata.

So the producer/consumer split exists and the failure is in MoveNext on the consumer pump. What I still cannot prove from this stack alone is the precise interleaving by which S becomes disposed during a single MoveNext loop on the consumer thread (per the IL analysis above, the consumer is normally both renter and disposer). The likeliest mechanism is two state-machine instances simultaneously aliasing the same SecurePooledObject S because their backing ImmutableDictionary._roots share structure (ImmutableDictionary uses copy-on-write so unrelated TaskItems can share the same hash-trie nodes). T2 iterates state-machine A to completion → S is returned to T2's TLS → T2 starts iterating state-machine B → TryTake returns the same S → S.Owner is reset to B's _poolUserId → any still-live read of A's embedded <>7__wrap1 (e.g. a finalizer-ordering or JIT-reordering race around the initobj/fault path in MoveNext's try) sees a stale _poolUserId and throws.

The honest framing for the PR rationale is therefore:

  • The crash site is proven, exactly the iterator this PR removes.
  • The hazard the iterator violates is documented: the BCL <remarks> on SortedInt32KeyNode<T>.Enumerator explicitly forbids copying the value-type enumerator, which is what yield return foreach (... in ImmutableDictionary) does via stfld <>7__wrap1.
  • The exact interleaving that disposes S mid-MoveNext requires more state than this stack alone exposes — probably the locals/thread-list from the actual MSBuild crash dump (MSBuild_*.failure.txt in MSBuildTempAnuNWq/ on the Helix machine, no longer reachable). The most likely candidate is enumerator-aliasing across structurally-shared ImmutableDictionary roots — the same shape of race the BCL caution warns about, just realised through the async-queue topology rather than two-local-variable assignment.
  • The fix removes the iterator and so removes the entire category, regardless of which exact dispose-window happened to fire.

So the bottom-line summary on this PR is now: dump-confirmed crash site, documented BCL anti-pattern, fix removes the anti-pattern; precise interleaving plausibly identified but not exhaustively traced from the available data.

[!NOTE] AI-generated content by Copilot CLI. Triple-check before relying on it.

lewing avatar Jun 22 '26 14:06 lewing

MSBuild triage: @lewing Is this ready for review? There is a lot of text. Update the description please.

AlesProkop avatar Jun 23 '26 12:06 AlesProkop

MSBuild triage: @lewing Is this ready for review? There is a lot of text. Update the description please.

Sorry for all the noise, the volume of text is from me pushing the session to find the root cause and as Jan indicates it hasn't yet done so convincingly.

lewing avatar Jun 25 '26 22:06 lewing

@lewing This is still hitting dotnet/sdk CI, we got pinged on sdk issue: https://github.com/dotnet/sdk/issues/55076

I would like to ask if you think you will pursue this PR still?

AlesProkop avatar Jul 31 '26 08:07 AlesProkop