Skip to content

Occasional crash during gcdump #6048

Closed

Description

@bart-vmware

Our tools run the same logic as the dotnet-gcdump tool. It occasionally crashes on macOS (default GitHub Actions Runner image) with the stack trace below. Related code:

var heapInfo = new DotNetHeapInfo();
var memoryGraph = new MemoryGraph(50_000);

if (EventPipeDotNetHeapDumper.DumpFromEventPipe(cancellationToken, processId, null,
    memoryGraph, logWriter, 30, heapInfo))
{
    memoryGraph.AllowReading();
    GCHeapDump.WriteMemoryGraph(memoryGraph, outputPath, "dotnet-gcdump");
    return true;
}

Stack trace of the crash:

  0.5s: EventPipe Listener dying
  0.5s: [Error] Exception during gcdump: System.AggregateException: One or more errors occurred. (Specified argument was out of the range of valid values.)
 ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
   at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
   at System.IO.StreamWriter.WriteFormatHelper(String format, ReadOnlySpan`1 args, Boolean appendNewLine)
   at System.IO.StreamWriter.WriteLine(String format, Object arg0)
   at Microsoft.Diagnostics.Tools.GCDump.EventPipeDotNetHeapDumper.<>c__DisplayClass3_1.<DumpFromEventPipe>b__5() in /_/src/Tools/dotnet-gcdump/DotNetHeapDump/EventPipeDotNetHeapDumper.cs:line 269
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.WaitAllCore(ReadOnlySpan`1 tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout)
   at Microsoft.Diagnostics.Tools.GCDump.EventPipeDotNetHeapDumper.DumpFromEventPipe(CancellationToken ct, Int32 processId, String diagnosticPort, MemoryGraph memoryGraph, TextWriter log, Int32 timeout, DotNetHeapInfo dotNetInfo) in /_/src/Tools/dotnet-gcdump/DotNetHeapDump/EventPipeDotNetHeapDumper.cs:line 274
[  0.5s: Done Dumping .NET heap success=True]

---- System.ApplicationException : RootIndex not set.

This is nearly impossible to reproduce for us.

Full log at: https://github.com/SteeltoeOSS/Steeltoe/actions/runs/34455238672/job/102799980981.
Full source code at: https://github.com/SteeltoeOSS/Steeltoe/blob/main/src/Management/src/Endpoint/Actuators/HeapDump/HeapDumper.cs#L103

Any thoughts on what could be causing this, or where to look further?

Activity

  1. added
    bug
    on Sep 18, 2026
  2. hoyosjs commented on Sep 19, 2026

    @hoyosjs
    Member

    Gcdump crash investigation

    Conclusion

    The reported failure is a race in EventPipeDotNetHeapDumper logging, followed by a false success result. It is not evidence of macOS GC heap corruption. A fix is needed in diagnostics, and Steeltoe can apply partial mitigations while waiting for a fixed package.

    DumpFromEventPipe writes to the caller-provided TextWriter from multiple threads. Steeltoe passes a plain StreamWriter over a MemoryStream, and StreamWriter is not thread-safe. During session shutdown, the EventPipe reader task and stop task finish at nearly the same time and both call WriteLine on that writer. The resulting corruption of StreamWriter internal buffer state produces the reported ArgumentOutOfRangeException from StreamWriter.Flush.

    The method then catches the exception but returns true because dumpComplete was set when the GC stop event was observed. The exception prevented ConvertHeapDataToGraph() from running, so the graph still has no root. Steeltoe sees true, calls memoryGraph.AllowReading(), and gets RootIndex not set.

    Failure sequence

    1. The EventPipe reader receives the GC stop event, logs .NET GC Complete, and sets dumpComplete = true in src/Tools/dotnet-gcdump/DotNetHeapDump/EventPipeDotNetHeapDumper.cs.
    2. The controlling thread observes dumpComplete and starts stopTask.
    3. stopTask logs Shutting down gcdump EventPipe session and calls EndSession().
    4. Stopping the session triggers rundown events. The reader thread writes many Found Module messages through DotNetHeapDumpGraphReader while stopTask proceeds after EndSession().
    5. stopTask logs gcdump EventPipe session shut down at line 269 while the reader thread is writing a rundown module message.
    6. Both tasks use the same caller-provided TextWriter. In Steeltoe this is an unsynchronized StreamWriter created by CaptureLogOutput.
    7. The job log directly shows a torn interleave: gcdump EventPipeQuic.dll ID ... combines text from gcdump EventPipe session shut down and Found Module System.Net.Quic.dll ID .... The line 269 write then throws from StreamWriter.Flush.
    8. Task.WaitAll surfaces the task exception as AggregateException. The outer catch logs it and continues.
    9. Execution never reaches dumper.ConvertHeapDataToGraph(), which builds the graph root and assigns m_graph.RootIndex in DotNetHeapDumpGraphReader.cs.
    10. DumpFromEventPipe returns the already-true dumpComplete. Steeltoe calls AllowReading(), and Graph.AllowReading() throws because RootIndex is still invalid.

    The timestamps from the failing job reinforce the race:

    0.2s: .NET GC Complete.
    0.3s: Shutting down gcdump EventPipe session
    0.5s: gcdump EventPipeQuic.dll ID 0x10eaa7b90
    0.5s: EventPipe Listener dying
    0.5s: ArgumentOutOfRangeException at the stop-task WriteLine
    0.5s: Done Dumping .NET heap success=True
    RootIndex not set
    

    There are many Found Module messages immediately before shutdown. This leaves the StreamWriter buffer active and makes a concurrent write or flush more likely to expose the race.

    Why this affects the Steeltoe integration

    The original dotnet-gcdump CLI passes either Console.Out or TextWriter.Null. Console.Out is synchronized by the runtime, and TextWriter.Null has no mutable stream buffer. During review of the original dotnet-gcdump pull request, the thread-safety risk was explicitly raised. The response was that the CLI writers were already safe.

    That assumption does not hold when another component directly references the tool assembly and passes a plain StreamWriter, as Steeltoe does with dotnet-gcdump 9.0.652701. The assembly is packaged as a tool rather than as a supported library API, so Steeltoe's direct assembly reference is an unsupported consumption pattern. However, diagnostics still needs a fix because the false-success behavior also affects the shipped CLI whenever any exception occurs after the GC stop event but before graph conversion completes.

    The failed Steeltoe workflow attempt failed only for the net10.0 gcdump case on macOS. The same unchanged commit passed on rerun. That is consistent with a scheduling-sensitive race rather than deterministic graph corruption.

    Additional defect: process-wide completion state

    eventPipeDataPresent and dumpComplete are static volatile fields. They are never reset at the start of either DumpFromEventPipe or DumpFromEventPipeFile.

    This creates a separate reentrancy problem:

    • A successful collection leaves dumpComplete = true for every later collection in the process.
    • A later collection can break out of its wait loop before its own dump completes.
    • eventPipeDataPresent can also remain true, causing conversion to be attempted with partial or unrelated event data.
    • Concurrent calls can observe and modify each other's state.
    • File conversion and live collection share the same fields.

    This static-state issue is not required to explain the specific first-call Steeltoe failure, because the current GC stop event set dumpComplete before shutdown. It can, however, cause additional intermittent failures for a long-lived endpoint that collects more than one gcdump.

    Diagnostics fix

    The diagnostics change:

    1. Replaces the process-wide completion fields with state owned by each live collection or file conversion invocation.
    2. Tracks operation success separately from observing GCStop and returns true only after ConvertHeapDataToGraph() completes.
    3. Documents that the live collection log writer must support concurrent writes because logging occurs from multiple tasks.

    The regression coverage uses the real self-gcdump path to verify that an exception during shutdown logging returns false.

    Caller-side mitigation

    Steeltoe must provide a writer that supports concurrent writes when it calls DumpFromEventPipe directly. It can use a synchronized writer:

    using TextWriter logWriter = TextWriter.Synchronized(
        new StreamWriter(logStream, leaveOpen: true));

    Until Steeltoe consumes a diagnostics build with the false-success fix, it should check memoryGraph.RootIndex != NodeIndex.Invalid before calling AllowReading().

    Verification

    The initial diagnosis was independently confirmed with Claude Opus 5 by review of the complete failing job log, the exact Steeltoe source and dependency versions at the failing commit, the consumed v9.0.652701 diagnostics source, current diagnostics source, the original dotnet-gcdump pull request discussion, and the .NET StreamWriter implementation.

    A local regression repro was then run against the unmodified production implementation. The real self-gcdump test failed with:

    Detected 82 concurrent writes to the supplied TextWriter.
    

    After the narrowed fix, the targeted test passes in Debug and Release. The complete test outputs were preserved as session artifacts.

    Relevant references:

  3. hoyosjs commented on Sep 19, 2026

    @hoyosjs
    Member

    @bart-vmware - I had looked a bit at this and say a few issues. I set and agent and it got to even reply before I did. The answer is pretty thorough. Essentially there's 3 issues:

    • global static state being used, so it would be an issue if you ran analysis from the same daemon.
    • We use a synchronized writer (Console) but Steeltoe doesn't.
    • Bad error state handling that returned from the method reporting success prior to parsing the graph.
  4. bart-vmware commented on Sep 21, 2026

    @bart-vmware
    ContributorAuthor

    @hoyosjs Thanks for the analysis, this is immensely helpful! In Steeltoe, we can:

    • Guard concurrent dumps with a lock (I'm surprised this wasn't already in place)
    • Check for NodeIndex.Invalid
    • Reset the two static fields using reflection (temporary workaround)
    • Use a thread-safe TextWriter

    I did some benchmarking on alternatives for TextWriter.Synchronized; will add a suggestion in #6051.

  5. added a commit that references this issue on Sep 24, 2026
    2a16a62
  6. added a commit that references this issue on Sep 30, 2026
    ef62f35
  7. locked and limited conversation to collaborators on Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions