Skip to content

Add async-profiler support to TraceEvent. - #2517

Open
Johan Lorensson (lateralusX) wants to merge 23 commits into
microsoft:mainfrom
lateralusX:lateralusX/async-profiler-trace-event-support-rebased-squashed
Open

Johan Lorensson (lateralusX) wants to merge 23 commits into
microsoft:mainfrom
lateralusX:lateralusX/async-profiler-trace-event-support-rebased-squashed

Conversation

@lateralusX

Copy link
Copy Markdown
Member

Summary

When async code resumes after an await, a CPU sample shows the runtime dispatcher at the bottom of the stack; the async methods waiting on the resumed work are gone. The .NET runtime's async profiler records those waiting async callers each time async code resumes on a thread. This PR teaches TraceEvent to decode those events and combine them with physical
stacks, so stack views show who the work was done for:

Physical stack:      Thread -> Runtime dispatch -> ReadResponse -> ParseResponse
Reconstructed stack: Thread -> HandleRequest -> FetchDocument -> ReadResponse -> ParseResponse

Both classic state-machine async (V1) and runtime async (V2) are supported, including traces that contain both. The feature is opt-in: nothing changes unless stitching is enabled. Sample counts, timestamps and weights are never changed; stitching only adds the waiting callers.

The design is described in documentation/TraceEvent/AsyncProfiler.md.

What's included

Decoding and indexing

  • Parser for the AsyncEvents batch format and its sub-events.
  • A per-thread index of the async call stacks active over time, built during ETLX conversion and persisted in the ETLX. Raw AsyncEvents records are not kept in the ETLX by default.
  • Instruction pointers are mapped to TraceLog code addresses so frames resolve through the normal symbol path.

Stitching and presentation

  • A stitcher that merges the physical stack with the active async call stacks, using runtime dispatch boundaries and recorded completion progress.
  • Optional transforms: infrastructure cleanup, frame annotations, and historical parent contexts.

Public API

  • ThreadTimeStackComputer and SampleProfilerThreadTimeComputer: EnableAsyncCallStacks, AsyncCallStackTransforms, AsyncCallStacksActive.
  • AsyncProfilerCallStackSourceBuilder: stitch individual stacks.
  • AsyncProfilerCallStackComputer: query the recorded async call stacks active on a thread at a timestamp, innermost first.
  • SpeedScopeStackSourceWriter.WriteAsyncCallStacksAsJson: export recorded async call stacks as a Speedscope timeline, by exact events or on a fixed sampling grid.

Supporting changes outside the feature folder

  • TraceLog: records when user-mode stacks were captured, so ETW samples are matched against the async state at that time (TryGetCallStackIndex / TryGetBlockingStackIndex overloads with userModeTimeStampQPC).
  • FastSerialization: DeferedRegion can be reloaded (ReadReloadable, ResetRead, CanReload), so the async index can be released and reloaded.
  • Stacks: derived frames can carry a display prefix (used for annotated async frames).
  • TraceLoadedModule lookup by module kind.
  • Speedscope and Chromium writers: an opt-in preserveSampleGaps overload of WriteStackViewAsJson; existing overloads keep their current behaviour.

Limitations

  • V1 frames resolve to the method start, not the await location, but async frames carry state, so possible to do IL -> Source mapping, but not yet implemented, but could be implemented by consumers of the API's.

Testing

Tests added

About 530 new [Fact]/[Theory] methods, most in TraceEvent.Tests\AsyncProfiler\. Inputs are synthetic: unit tests feed hand-built payloads, and integration tests generate .nettrace files into a temp folder. No trace files are checked in.

Area Test classes Covers
Parsing AsyncProfilerParsingTests, AsyncProfilerMethodNamesTests Decoding each sub-event (context lifecycle, call stacks with per-frame state, unwind, metadata, clock sync, reset), bad headers, method-name normalization for V1/V2 and state machines
Indexing AsyncProfilerIndexBuilderTests, AsyncProfilerTraceLogTests Recovery from malformed payloads, reset/metadata ordering, resume/suspend/complete intervals, leaf-to-root queries before and after reload, dispatcher and parent lookup, opt-in via KeepAsyncProfilerEvents
Stitching AsyncProfilerCallStackStitcherTests (state-machine, runtime-async, dispatch, completion tail, nested, parent contexts, incomplete roots), AsyncProfilerCallStackStitchBoundaryTests, AsyncProfilerStitchedFrameTests Joining physical and async frames for each async model, plus boundary cases and frame identity
Runtime support AsyncProfilerRuntimeSupportTests, AsyncProfilerRuntimeSupportExtensibilityTests, AsyncProfilerRuntimeSequenceTests Choosing support for the captured runtime, boundary and infrastructure classification, module ownership checks, custom supports, frame-sequence matching
Transforms AsyncProfilerCallStackTransformPipelineTests, AsyncProfilerCallStackDiagnosticsTests Default conservative transforms, opt-in async infrastructure cleanup, context-boundary preservation, bounded diagnostics
End to end AsyncProfilerStitchIntegrationTests (resumption bridge, completed unwind, profiler ownership, registration, runtime versioning, public API, ...), AsyncProfilerEndToEndFixtureTests Synthetic trace to TraceLog to stitched stacks through the public API
Async timeline export AsyncCallStackExporterTests Nested contexts, recorded progress, zero-IP frames, virtual sampling on the trace QPC grid, export from a persisted index

Additions to existing areas:

  • SpeedScopeExporterTests: preserveSampleGaps overloads.
  • StackUserModeTimeTests (new): TryGetCallStackIndex/TryGetBlockingStackIndex user-mode timestamps.
  • LoadedModuleTests (new): GetLoadedModule(fileName, time, kind) and TraceLoadedModuleKind.
  • Helpers: EventPipeTestWriter (moved out of EventPipeParsing.cs, then extended) and SyntheticEtwSource.

Benchmarks were added in TraceEvent.Benchmarks\AsyncProfiler\ for the stitcher, transform pipeline, call-stacks index, index build, parent contexts, end to end, and conversion peak memory.

Decode the .NET runtime's async-profiler events and use them to rebuild
the logical async callers of sampled code. Both state-machine async (V1)
and runtime async (V2) are supported, including traces that contain both.

- Parse async-profiler event batches and build a per-thread index of the
  async call stacks active over time; persist the index in ETLX.
- Stitch each physical stack with its active async call stacks, with
  optional transforms: infrastructure cleanup, frame annotations and
  historical parent contexts.
- Add EnableAsyncCallStacks to ThreadTimeStackComputer and
  SampleProfilerThreadTimeComputer.
- Add public APIs: AsyncProfilerCallStackSourceBuilder to stitch
  individual stacks, and AsyncProfilerCallStackComputer to query the
  recorded async call stacks.
- Add SpeedScopeStackSourceWriter.WriteAsyncCallStacksAsJson to export
  recorded async call stacks as a Speedscope timeline.
- Record when user-mode stacks were captured, so ETW samples are matched
  against the correct async state.
- Add tests, benchmarks, and documentation (AsyncProfiler.md).

Sample counts, timestamps and weights are unchanged; stitching only adds
the waiting async callers to stacks.

@brianrob Brian Robbins (brianrob) 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.

Recommendation

Changes Recommended; Human Review Required

Reviewed commit 380b1d1f.

PR: #2517

Base: 8ba00fcc2ab6706850b5eb45464b91b83d7c39e7; Head: 380b1d1f19a03aa289e2b56c89b9e25d7138aad1

Areas Reviewed

  • Runtime batch decoding, stream recovery, captured-stack indexing, symbols and ETLX persistence.
  • V1/V2 physical-stack stitching, runtime ownership, transforms, parent contexts and thread-time integration.
  • Frame/source identity, exact and sampled timeline exports, synthetic tests, fixtures, benchmarks and documentation.
  • Material architecture extension: persistent async evidence, public lifetimes and attribution contracts; existing assembly boundaries remain and no external dependency changes occur.

Areas Requiring Human Review

  • [HR-1] Accept automatic async indexing and default raw-batch omission. - This changes TraceLog's persistent evidence ownership and retention policy independently of whether a consumer requests reconstructed stacks. src/TraceEvent/TraceLog.cs:2225-2251 (RIGHT), src/TraceEvent/TraceLog.cs:2256-2323 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerIndexBuilder.cs:316-415 (RIGHT)

    Explanation

    Opening a captured trace builds async intervals even if stitching remains disabled. Ordinary ETLX output omits the binary batches; KeepAllEvents preserves them. Omitted unknown records and appended fields cannot later be redecoded from that standalone ETLX. Damaged evidence leaves gaps until the required recovery records arrive.

    Origin: Introduced by this PR. Adds a persistent continuation-evidence index alongside TraceLog's existing derived tables, with process-scoped decoding state and conservative recovery.

    Decision needed: Accept unconditional conversion-time indexing, metadata/reset trust gating, and derived-evidence-only retention by default.

    Evidence: TraceLog creates the builder during conversion, registers captured addresses before rundown, and retains the finished index. Its parser callback removes raw batches unless preservation is requested. Index recovery requires metadata and thread resets and invalidates affected open state without deleting recorded intervals. src/TraceEvent/TraceLog.cs:2225-2251 (RIGHT), src/TraceEvent/TraceLog.cs:2256-2323 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerIndexBuilder.cs:316-415 (RIGHT)

  • [HR-2] Choose the ETLX format-transition and reloadable-index contract. - The change extends the processed-trace binary contract and introduces releasable, reloadable derived state. src/TraceEvent/TraceLog.cs:4218-4235 (RIGHT), src/TraceEvent/TraceLog.cs:4439-4497 (RIGHT), src/FastSerialization/FastSerialization.cs:2243-2300 (RIGHT)

    Explanation

    Async evidence loads on demand from ETLX and can be released and loaded again without replaying raw events. Previously returned stacks can retain frame data, so releasing the index does not guarantee reclaiming all its memory. Symbol resolution still depends on the open TraceLog.

    Origin: Partly existing behavior that this PR changes. Extends existing deferred serialization with two mandatory regions and reusable read state.

    Decision needed: Approve the reloadable ownership model and choose versioned cache invalidation or explicit backward reading, after fixing the incompatible layouts sharing version 78.

    Evidence: TraceLog appends async-index and stack-capture-time regions. Its lock serializes index loading and release; release drops the log's reference while retained results remain usable. FastSerialization adds public reloadable-region operations. The format-version finding below identifies the current format-version collision. src/TraceEvent/TraceLog.cs:4218-4235 (RIGHT), src/TraceEvent/TraceLog.cs:4439-4497 (RIGHT), src/FastSerialization/FastSerialization.cs:2243-2300 (RIGHT)

  • [HR-3] Accept the public API ownership, callback and generation lifecycle contracts. - The PR adds public query/building surfaces and presentation extensibility, with deliberately different stable-result and borrowed-view lifetimes. src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackComputer.cs:26-79 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackSourceBuilder.cs:11-112 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackTransformContext.cs:11-81 (RIGHT), src/TraceEvent/Computers/SampleProfilerThreadTimeComputer.cs:90-101 (RIGHT)

    Explanation

    Ordinary query results can be retained, but callback contexts, collections and referenced stacks cannot. Callbacks edit presentation only, run after built-ins, and propagate exceptions. Building is non-concurrent and non-reentrant, stops at output finalization, and requires owner-correct inputs. The sample-profiler computer now permits only one generation per instance.

    Origin: Partly existing behavior that this PR changes. Introduces public reconstruction and callback APIs and makes an existing stateful computer explicitly single-generation.

    Decision needed: Accept these lifetime, exception, ownership and single-generation restrictions as supported public behavior.

    Evidence: Query results survive later queries and index release; events are checked against the owning log. The builder owns neither the log nor samples, rejects finalized output and reentrancy, and cannot detect cross-owner integer indices by range checking. Callback state is cleared in finally. SampleProfilerThreadTimeComputer now rejects a second generation regardless of the async toggle. src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackComputer.cs:26-79 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackSourceBuilder.cs:11-112 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackTransformContext.cs:11-81 (RIGHT), src/TraceEvent/Computers/SampleProfilerThreadTimeComputer.cs:90-101 (RIGHT)

  • [HR-4] Accept continuation-based attribution and separate user-stack capture time. - This introduces a second ancestry model alongside ActivityComputer and changes how reconstructed frames represent causality, execution and identity. src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackSourceBuilderCore.cs:103-185 (RIGHT), src/TraceEvent/Computers/ThreadTimeComputer.cs:940-1010 (RIGHT), src/TraceEvent/TraceLog.cs:12020-12040 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackSourceBuilderCore.cs:545-612 (RIGHT)

    Explanation

    With opt-in stitching, recorded waiting callers replace scheduling-derived ancestry when usable. A borrowed user stack is matched at its capture time, while the sample retains its event timestamp and weight. Pending targets, executing bodies, completion-return work and historical creation parents remain different roles even with identical display names. Normalization defaults on; cleanup and historical parents default off.

    Origin: Partly existing behavior that this PR changes. Adds continuation-based attribution, capture-time provenance and role-sensitive generated-frame interning without replacing stored physical stacks.

    Decision needed: Accept these attribution semantics, defaults and the separation between execution evidence, historical causality and sample metrics.

    Evidence: ActivityComputer.cs:23-114 follows TPL scheduling relationships. The new core queries recorded intervals, stitches, expands optional parents, transforms, and interns output. Successful host reconstruction bypasses legacy stack construction while retaining host roots. Borrowed user frames have a separate persisted QPC. Generated frame identities preserve captured state and origin even when names match. src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackSourceBuilderCore.cs:103-185 (RIGHT), src/TraceEvent/Computers/ThreadTimeComputer.cs:940-1010 (RIGHT), src/TraceEvent/TraceLog.cs:12020-12040 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerCallStackSourceBuilderCore.cs:545-612 (RIGHT)

  • [HR-5] Accept or narrow the runtime forward-compatibility assumptions. - The consumer assumes append-only evolution for known record schemas and reuses the latest runtime baseline for later CoreCLR versions. src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:83-91 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:318-415 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerRuntimeSupport.cs:36-67 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerRuntimeResolver.cs:108-180 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:90-94 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:320-336 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTypes.cs:174-197 (RIGHT)

    Explanation

    Known record IDs retain their existing decoder even when metadata advertises another version. Appended fields are skipped, but reordered fields would still be interpreted using the old layout. CoreCLR 11 and later select the 11 baseline; unknown or conflicting metadata selects Common, currently sharing the same rules. Sequence acceptance separately verifies captured runtime ownership.

    Origin: Introduced by this PR. Adds local protocol decoding and captured-runtime policy selection rather than depending on the analysis host's runtime.

    Decision needed: Accept these forward-reuse assumptions, or restrict known-schema decoding and runtime selection to explicitly supported versions.

    Evidence: The parser documents append-only known schemas and dispatches by event ID rather than advertised version. Manifest retains versions; parsing tests explicitly exercise permissive decoding of known IDs. RuntimeSupport.Select chooses CoreClr11 for major versions >=11; Common and CoreClr11 currently instantiate the same implementation. At dotnet/runtime@9bd4983:src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncProfiler.cs:52-57, a version bump signals any schema change, not only appended fields; lines 115-139 currently advertise only schema version 1. No current-producer incompatibility was found. src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:83-91 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:318-415 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerRuntimeSupport.cs:36-67 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerRuntimeResolver.cs:108-180 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:90-94 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTraceEventParser.cs:320-336 (RIGHT), src/TraceEvent/AsyncProfiler/AsyncProfilerTypes.cs:174-197 (RIGHT)

  • [HR-6] Accept async occupancy export as a distinct public timeline contract. - The new exporter measures recorded active-context occupancy, unlike existing sample-weight-based stack exports. src/TraceEvent/Stacks/SpeedScopeStackSourceWriter.cs:43-96 (RIGHT), src/TraceEvent/Stacks/SpeedScopeStackSourceWriter.cs:253-379 (RIGHT), src/TraceEvent/Stacks/SpeedScopeStackSourceWriter.cs:386-418 (RIGHT), src/TraceEvent/Stacks/StackSourceWriterHelper.cs:142-180 (RIGHT)

    Explanation

    Widths represent elapsed active-context time, not CPU consumption or whole method lifetimes. Later V1 appends are displayed from the context's resume. Missing completion progress is not inferred from wrapper resets. Virtual snapshots persist until the next grid point, so short contexts between points can disappear. Existing sample exporters change gap handling only when explicitly requested.

    Origin: Partly existing behavior that this PR changes. Adds exact-transition and virtually sampled async timelines plus opt-in sample-coverage gap preservation.

    Decision needed: Accept these distinct occupancy and approximation semantics while preserving legacy export defaults.

    Evidence: SpeedScopeStackSourceWriter adds direct TraceLog export without physical samples. It opens finalized captured stacks, applies recorded completion/unwind deltas, and clips intervals. Virtual export uses a trace-start grid. Existing Speedscope and Chromium APIs retain legacy behavior; additive overloads request exact sample-gap preservation through StackSourceWriterHelper. src/TraceEvent/Stacks/SpeedScopeStackSourceWriter.cs:43-96 (RIGHT), src/TraceEvent/Stacks/SpeedScopeStackSourceWriter.cs:253-379 (RIGHT), src/TraceEvent/Stacks/SpeedScopeStackSourceWriter.cs:386-418 (RIGHT), src/TraceEvent/Stacks/StackSourceWriterHelper.cs:142-180 (RIGHT)

Code Review Feedback


Written by Robert Bobby (Brianrob's Code Review Bot).

Comment thread src/TraceEvent/TraceLog.cs Resolved
The async-profiler change appended two deferred regions (async call
stacks index and stack user-mode timestamps) to the TraceLog layout
without bumping the format version. Version 78 files from main were
accepted and then misread ("Undefined forward reference index"), and
older readers asserted on the new layout.

Bumping to 79 makes both directions fail with a clean version
mismatch, so OpenOrConvert regenerates stale ETLX files.
Unwind frame counts are decoded as compressed UInt32 but stored as
Int32 completion deltas. Counts >= 0x80000000 became negative deltas
that were persisted to the ETLX and later made the Speedscope async
export throw. Treat them as a malformed payload so the existing
parse-error recovery handles them.
…ords

Each thread's CallStackRecordCollection allocated a full 4,096-record chunk
(~160 KB, LOH) on its first call stack, so traces with many short-lived
threads reserved large amounts of mostly unused memory. The first chunk now
starts at 4 records and doubles up to the chunk size; later chunks are
unchanged, so indexing stays the same.
Callbacks still run while processing is disabled for the SkipMSec prefix.
The AsyncEvents removal callback set removeFromStream on a skipped batch,
and the skip path returned without clearing it, so the next event inside
the requested window was dropped along with its stack. Clear the flag on
every skipped-event exit.
For spellings such as ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter[System.Int64],
the nested awaiter carries type arguments without an arity marker, so
GetTypeNameWithoutArity kept "[System.Int64]" and the explicit-interface
AwaitUnsafeOnCompleted frame was not classified as V1AwaiterRegistration.
Strip at the first arity marker or type-argument list.

Also remove a duplicated summary on IsNativeRuntimeModule.
…rows

SampleProfilerThreadTimeComputer and ThreadTimeStackComputer now clear the
async call-stack builder and thread state in a finally block, so a failing
custom transform or callback no longer leaves reconstruction buffers alive.
- Drop the unused AsyncProfilerCallStack Write/Read serialization path;
  the index owns persistence.
- Drop the unreachable late frame-state initialization in AddFrames.
- Append parent frames directly to the insertion buffer instead of an
  intermediate list.
- Suppress CS0618 on the exact-QPC read in the SkipMSec test.
- Stitching keeps sampled application frames but can replace verified
  handoff frames, even with normalization and cleanup off.
- The common and CoreCLR 11 rule sets are currently identical; the
  common rules are not more conservative.
The region shared the TraceLog deserializer with the reloadable async index
but was deserialized lazily and without synchronization, so concurrent first
lookups or an async-index reload could interleave reads. Finish it in
FromStream like the other event-to-stack tables.
A process+IP cache kept the first CodeAddressIndex for an IP, so after a
method unload the same address reused by other code stayed bound to the
unloaded method. Bind each frame when its resume/append event is accepted,
as physical stacks do, and include those bindings in frame-list interning.
Key the index builder's per-thread nesting state by OS thread and
AsyncThreadContextId so a late buffer from a dead thread cannot close
or extend call stacks of a replacement thread reusing the same OS id.
…tion epoch

Mark method-completion and exception-unwind availability using the open
call stack's start (or the thread's last reset) instead of the event
timestamp, matching how consumers look up a call stack's epoch. Metadata
emitted by another thread mid-stack no longer hides recorded completions.
The reentrant handoff pass removed every same-runtime frame between a
nested call stack and the enclosing async method, including ordinary
CoreLib calls such as List<T>.ForEach or timer callbacks. Remove only
the classified helpers (or stitch boundaries) next to the nested call
stack and keep the frame that completed the nested work, plus
everything root-ward of it.
Raw AsyncEvents batches are now always dropped from ETLX after
indexing unless TraceLogOptions.KeepAllEvents is set. The internal
option was only reachable from tests and benchmarks, which now use
KeepAllEvents.
Release/reload was only used by tests and benchmarks and required new
public DeferedRegion APIs, while retained results limited what it could
reclaim. Revert the FastSerialization changes and load the async index
as a plain lazy deferred region. Remove the internal loaded flag; tests
inspect the deferred region instead.
Remove EnableAsyncCallStacks; thread-time computers now use async-profiler
data when UseTasks is set and the trace contains it, falling back to TPL and
then physical stacks per sample. Add an internal opt-out for tests and
benchmarks, rename AsyncCallStacksActive/AsyncCallStackTransforms to
AsyncProfilerCallStacksActive/AsyncProfilerCallStackTransforms, and document
the precedence.
Known records whose advertised version is newer than TraceEvent supports
are skipped and reported as parse errors instead of being decoded with
the V1 layout. Only the thread where such a record appears loses its
async call stacks, until its next reset. Appending fields keeps the
version; incompatible metadata or framing changes use the buffer version.
Remove the raw async timeline export (WriteAsyncCallStacksAsJson, exact
and grid-sampled) and the opt-in preserveSampleGaps overloads, restoring
SpeedScope/Chromium writers and StackSourceWriterHelper to upstream
behavior. Stitched async stacks in sample-based stack views still export
through the existing writers. The timeline export can be reintroduced in
a separate PR.
Add UseAsyncProfiler to ThreadTimeStackComputer and
SampleProfilerThreadTimeComputer. It enables async-profiler call stacks
and the same Task handling as UseTasks internally, without changing
UseTasks. UseTasks alone keeps TPL-only stacks, so PerfView views and
the SampleProfilerThreadTimeComputer default are unchanged. Remove the
internal DisableAsyncProfilerCallStacks opt-out.
Threads and GetCallStacks(thread) on AsyncProfilerCallStacksIndex were
only used by the removed Speedscope async export. Remove them along with
their ThreadCallStackList helper, and drop the benchmark and test
assertions that relied on them.
@lateralusX

Copy link
Copy Markdown
Member Author

Here are the responses to the six "Areas Requiring Human Review" items:

HR-1: Conversion-time async indexing and raw AsyncEvents retention.

Accepted as designed. Indexing at conversion time costs nothing when the provider is absent, follows how TraceLog already handles stack events, and the ETL stays the source of truth. To simplify, we removed the internal KeepAsyncProfilerEvents option. Raw batches are now kept only with KeepAllEvents.

HR-2: ETLX format transition and reloadable index.

Format: the version collision was fixed earlier, and the format is now 79. We're keeping TraceLog's existing policy of no backward reading. Old ETLX files fail to open, and OpenOrConvert regenerates them from the ETL.

Reloadable index: dropped. Only tests and benchmarks called release, and retained results kept parts of the index alive anyway, so it saved little memory for the added DeferedRegion API. The FastSerialization changes are reverted. The async index is now a plain lazy deferred region, loaded under a lock on first query. If releasing derived data becomes a real need, it should be a broader TraceLog concept, not something specific to async stacks.

HR-3: Public API lifetimes, callbacks, and single-generation computer.

Lifetimes: we're keeping these contracts as documented:

  • Query results and their captured frames can be retained.
  • Events must come from the owning TraceLog.
  • The builder is not concurrent or reentrant, and throws if its output is already finalized.
  • Indices are range-checked. An index from a different log can't be detected, so that is documented as the caller's responsibility, like the rest of TraceLog.

Custom transforms: made internal. The only consumers were tests. The main expected scenario is filtering, such as Just My Code in VS or folding CoreLib frames. Wrapping the computer's stack source in FilterStackSource (fold, group, include, and exclude patterns) already covers that, and it works the same for all samples, not only the ones with async context. These are now internal:

  • AddCustomTransform, ClearCustomTransforms, and AsyncProfilerCallStackTransformContext.
  • The synthetic-label frame constructor.
  • Frame properties that only made sense inside a callback: IsPhysical, IsCurrent, IsParentContext, IsParentContextCurrent, IsDispatchTarget, DisplayName, and CallStack.

Public frames keep CodeAddress, CapturedInstructionPointer, and CapturedState. The callback contracts you listed (reused context, valid only during the call, exceptions propagate) still hold internally. We can make the API public later if a real async-specific need comes up.

Single generation: SampleProfilerThreadTimeComputer already failed on a second GenerateThreadTimeStacks call in main, with a NullReferenceException because m_threadState is cleared. The PR only turns that into an explicit InvalidOperationException; it doesn't add a new restriction.

HR-4: Continuation-based attribution and separate user-stack capture time.

Accepting the semantics. Changed how the feature is turned on.

Two models, side by side: ActivityComputer and StartStopActivityComputer are unchanged. The async-profiler data is only read through its own builder. The two models answer the question differently:

  • TPL follows scheduling (Task.Run, work items, timers, await events).
  • The async profiler records the actual waiting callers, including runtime-async (V2), which TPL doesn't cover.

Neither replaces the other.

Turning it on: replaced the separate EnableAsyncCallStacks switch with an opt-in UseAsyncProfiler on both computers, off by default. It turns on the same Task handling as UseTasks internally, without changing UseTasks, so there is a single precedence order. Each sample uses the first that applies:

  1. The async-profiler stack, if the sample has an async context.
  2. The TPL stack.
  3. The physical stack.

Details:

  • UseTasks alone keeps TPL-only stacks, as before.
  • Request grouping (StartStop/ASP.NET) stays on top.
  • AWAIT_TIME samples always come from TPL.
  • Nothing changes unless UseAsyncProfiler is set. That includes PerfView's existing UseTasks views and EventPipe's SampleProfilerThreadTimeComputer default. Exposing it in PerfView is left for a follow-up.
  • The index is lazy, so there's no cost when the option is off or the trace has no async-profiler data.

Renames, so the names say where the data comes from:

  • AsyncCallStacksActive is now AsyncProfilerCallStacksActive.
  • AsyncCallStackTransforms (both the class and the property) is now AsyncProfilerCallStackTransforms.

AsyncProfiler.md documents the precedence above.

Capture-time QPC: when an ETW sample borrows its user-mode stack from a later kernel-exit event, the async lookup uses the time that stack was captured. That keeps the async frames consistent with the displayed user frames. The sample keeps its own timestamp and weight. The table is sparse, holding only borrowed stacks, at about 12 bytes each in the ETLX.

Frame roles: generated frames stay distinct by role (pending target, executing body, completion return, parent context) even when they have the same name. That keeps the data correct for consumers that care. Call-tree views still merge them by name, so what users see is unchanged.

Defaults: normalization is on; cleanup, frame annotations, and parent contexts are off; parent depth is 1.

Follow-up (separate issue): merge TPL and async-profiler ancestry. For example, put the TPL originating activity (Task.Run, work item, timer) above the root of the async chain, and extend the TPL view with runtime-async (V2) data. This needs de-duplication rules and real mixed traces, so it's out of scope here.

HR-5: Runtime forward-compatibility assumptions.

Agreed. The parser now checks advertised versions instead of always decoding known IDs with the V1 layout. The contract has three levels:

  • Append a field to a record: no version bump. Older readers read the fields they know and skip the rest using the length prefix.
  • Incompatible change to one record type: bump that record's version in the metadata manifest. TraceEvent skips each record with an unsupported version and reports a parse error. Only the thread where such a record appears loses its async call stacks, and only until its next reset record. Metadata that only advertises a bumped version, with no matching records, has no effect.
  • Incompatible change to the metadata record itself or to framing: bump the batch-header version. TraceEvent already ignores async-profiler data from batches with an unsupported header version.

Parse errors are counted and logged as TraceLog warnings, so a mismatch is visible instead of producing silently wrong stacks. The forward-compatibility tests cover appended fields, unknown record types, and unsupported record versions.

The runtime comment in AsyncProfiler.cs currently says a version bump signals "any schema change". We'll update it to match this contract:

  • Appended fields don't bump the version.
  • A version bump means an incompatible change.
  • Metadata and framing changes bump the batch-header version.
  • New record types must be listed in the metadata manifest so older readers can frame and skip them.

Runtime selection: accepted as-is. CoreCLR 11 and later use the CoreCLR 11 rules. Common and CoreClr11 are identical today; the split lets a future runtime get its own rules without affecting older traces. This is documented in AsyncProfiler.md.

HR-6: Async occupancy export as a distinct public timeline contract.

Removed from this PR to reduce scope:

  • The raw async timeline export (WriteAsyncCallStacksAsJson, exact and grid-sampled) and the opt-in preserveSampleGaps overloads are gone.
  • SpeedScopeStackSourceWriter, ChromiumStackSourceWriter, and StackSourceWriterHelper are back to upstream behavior.
  • The internal index enumeration API that only the export used is also removed.

Stitched async-profiler stacks can still be exported to Speedscope/Chromium. The writers export whatever stack source they're given, so a stack source built by ThreadTimeStackComputer or SampleProfilerThreadTimeComputer with UseAsyncProfiler set includes them. Only the separate async timeline export, which had no samples, was removed. It can come back in a follow-up PR if there's demand.

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.

2 participants