Skip to content

CPU Sampling Integration — in-process EventPipe capture + Call Tree view #351

Closed

Description

@nockawa

Umbrella issue for the CPU sampling profiling feature.

Design doc: claude/design/Profiler/11-cpu-sampling-integration.md (in the claude/ design repo — nockawa/typhon-claude; pending commit).

Summary

Add statistical CPU call-stack profiling to Typhon, surfaced in the Workbench as a dotTrace-style Call Tree. Replaces the dead EventPipeSampler (which shelled out to the dotnet-trace global tool) with an in-process EventPipe session (Microsoft.Diagnostics.NETCore.Client). Samples are parsed + symbol-resolved against portable PDBs and embedded as a trailer section of the .typhon-trace file — no .nettrace artifact is persisted. Go-to-source reuses the #302 source-attribution infrastructure verbatim.

Key decisions

  • Capture — in-process EventPipe Microsoft-DotNETCore-SampleProfiler; configured via typhon.telemetry.json (Typhon:Profiler:CpuSampling:Enabled), same mechanism as GcTracing. Fixed 1 kHz. No global tool, no special CLR launch.
  • No .nettrace — parsed at TyphonProfiler.Stop, embedded as a .typhon-trace trailer section with an interned stack table.
  • Symbol resolution reuses SystemSourceResolver (Profiler Source Attribution (v2) — file:line for every span, with editor handoff #302, portable-PDB sequence points); go-to-source reuses the entire Profiler Source Attribution (v2) — file:line for every span, with editor handoff #302 Workbench last mile.
  • Complements (does not duplicate) the existing kernel-ETW ThreadScheduling off-CPU timing.
  • Viewer — dotTrace-style Call Tree, scoped by (time-windows) ∩ (frame-root) ∩ (view-mode); server-side fold; the Data API exposes folded trees + density, never raw samples. Correlation = qpc-sorted index + interval queries.
  • Category breakdown ("Subsystems") — per-scope self-time split across engine categories (Ecs/Storage/Querying/…), derived from resolved file paths.
  • v1 = file mode only (live/TCP sampling deferred).

Implementation phases (~8 dev-days)

  • Phase 1 — Capture. CpuSamplerSession (in-process EventPipe self-session), typhon.telemetry.json config + TelemetryConfig fields, ProfilerLauncher wiring, delete EventPipeSampler.cs.
  • Phase 2 — Parse + resolve. EventPipe-stream parser (TraceLog), SystemSourceResolver (module, token) extension, thread-id → slot mapping.
  • Phase 3 — Wire format. .typhon-trace CPU-sample trailer section (interned stack table), header/writer/reader/cache.
  • Phase 4 — Call Tree view + Data API (standalone). Server-side sample index + fold, POST .../profiler/calltree, CallTree panel (dotTrace-style), on-CPU/wall-clock view modes, category breakdown.
  • Phase 5 — Correlation scoping & cross-panel commanding. Scope resolver (span/system/phase → time-windows), sample-density endpoint, Thread Track + catalogs as scope commanders.

Activity

  1. self-assigned this
    on May 16, 2026
  2. moved this to Backlog in Typhon devon May 16, 2026
  3. moved this from Backlog to In Progress in Typhon devon May 16, 2026
  4. nockawa commented on May 16, 2026

    @nockawa
    CollaboratorAuthor

    Phase 2 — Parse + Resolve — complete ✅

    All 10 acceptance criteria met. Library phase: the Phase-1 .nettrace is now parsed into a typed, symbol-resolved CpuSample list. Exercised by unit tests; wire-format integration is Phase 3.

    New files

    • src/Typhon.Engine/Profiler/internals/CpuSample.cs — CpuSample / CpuSampleFrame model types.
    • src/Typhon.Engine/Profiler/internals/CpuSampleParser.cs — TraceLog-based .nettrace parser.
    • test/Typhon.Engine.Tests/Profiler/CpuSampleParserTests.cs (9 tests), SystemSourceResolverByTokenTests.cs (5 tests).

    Modified

    • SystemSourceResolver.cs — ResolveByToken(Module, int token, int ilOffset) + IL-offset → covering sequence point; shared ResolveCore extracted.

    AC evidence

    • AC1 CpuSampleParser.Parse via TraceLog.CreateFromEventPipeDataFile, enumerates SampleProfilerTraceEventParser.ThreadSample, drops Error samples — Parse_ProducesSamples.
    • AC2 model types — compile + used throughout.
    • AC3 OS-tid → slot via ThreadSlotRegistry.TryGetSlotByOsThreadId, non-Typhon kept at -1 — Parse_MapsTyphonThreadToItsSlot, Parse_KeepsNonTyphonThreadsUnslotted.
    • AC4/AC5 ResolveByToken + IL-offset covering SP — ResolveByToken_KnownMethod_ResolvesToSource, ResolveByToken_WithIlOffset_PicksCoveringSequencePoint.
    • AC6 engine frame → real file:line, BCL/native → name-only — Parse_ResolvesEngineFrameToSource, Parse_ResolvesUnknownModuleFramesNameOnly.
    • AC7 graceful degrade — Parse_NonExistentFile/NullOrEmptyPath/CorruptFile_ReturnsEmpty.
    • AC8 no Phase-3 surface touched (TraceFileHeader/FileExporter/TyphonProfiler/cache unchanged); no new NuGet — git diff confirmed.
    • AC9 14 new tests pass, stable across 11 full-suite runs.
    • AC10 full Typhon.Engine.Tests suite green (3695 passed / 34 skipped). One intermittent failure observed in 1/11 runs — WAL_Commit_DurableLsnAdvances, a pre-existing ArchetypeRegistry cascade-diamond flake from parallel-fixture shared-static contention, unrelated to this change.

    Research note: design §9 risk 8 resolved — ClrThreadSampleTraceData.ThreadID is the OS thread id; no managed↔OS bridge needed.

    Ready for review + commit (not committed — per convention).

  5. nockawa commented on May 16, 2026

    @nockawa
    CollaboratorAuthor

    Phase 3 — Wire Format / Trailer Section — complete ✅

    All 11 acceptance criteria met. CPU samples are now persisted into the .typhon-trace as a v10 trailer section; the transient .nettrace is parsed and deleted.

    New files

    • src/Typhon.Profiler/CpuSampleSection.cs — CpuSampleRecord / CpuFrameSymbol wire types.
    • src/Typhon.Engine/Profiler/internals/CpuSampleSectionEncoder.cs — interns stacks + frame symbols into the shared FileTable.

    Modified

    • TraceFileHeader — CurrentVersion 9 → 10; new CpuSampleSectionOffset (v10 header = 87 bytes).
    • TraceFileWriter — CpuSampleSectionMagic + WriteCpuSampleSection.
    • TraceFileReader — version-conditional header read (v8/v9/v10) + TryReadCpuSampleSection.
    • FileExporter — SetCpuSamples + close-path encode/write (CPU frames share the source-location FileTable).
    • ProfilerLauncher.StopCpuSampler — stop → parse → hand to FileExporter → delete .nettrace; CpuSamplerSession.NetTracePath exposed.
    • AntHill.ProfileRunner/Program.cs — StopCpuSampler() ordered before bridge.Dispose().

    End-to-end verified — AntHill.ProfileRunner --trace with CPU sampling on: header CpuSampleSectionOffset != 0; TryReadCpuSampleSection reads back 147,244 samples / 900 interned stacks / 1042 frame symbols (811 resolved to real file:line); thread slots -1 + 0..22; .nettrace deleted. With sampling off: CpuSampleSectionOffset == 0, no .nettrace.

    Tests — CpuSampleSectionRoundTripTests (3), CpuSampleSectionEncoderTests (5), FileExporterIntegrationTests (+1). Full Typhon.Engine.Tests suite green (3703 passed / 34 skipped); v9 traces still read under the v10 reader.

    Approved deviations (confirmed before implementation): orchestration in ProfilerLauncher (not TyphonProfiler.Stop — TyphonProfiler untouched); cache propagation deferred to Phase 4.

    Design clarification — design §6.5 says a name-only frame uses fileId 0; the .typhon-trace FileTable reserves no 0-sentinel (index 0 is a real file), so CpuFrameSymbol.HasSource keys on line == 0 instead. Documented in the struct.

    Pre-existing bug surfaced (not Phase 3, not blocking): AntHill.ProfileRunner calls bridge.Dispose() before TyphonProfiler.Stop(); bridge.Dispose() tears down the engine resource tree the exporters live under, so the subsequent TyphonProfiler.Stop() throws ObjectDisposedException on the disposed exporter queue. The .typhon-trace is fully written before the throw (verified). Reproduces with sampling on and off, and predates Phase 3 — flagged for a separate host-shutdown fix.

    Ready for review + commit (not committed — per convention).

  6. nockawa commented on May 16, 2026

    @nockawa
    CollaboratorAuthor

    Follow-up — the shutdown-ordering crash is fixed (not deferred)

    The ObjectDisposedException flagged above was an ownership bug: FileExporter / TcpExporter are ResourceNodes parented under the engine's Profiler node, and ResourceNode.Dispose() unconditionally cascade-disposes children — so bridge.Dispose() closed the exporter's trace file mid-teardown, before TyphonProfiler.Stop() could drain the engine-teardown events into it.

    Fix — decouple tree membership from lifecycle:

    • ResourceNode — new public virtual bool DisposeWithParent => true; the Dispose(bool) cascade skips children where it is false.
    • FileExporter / TcpExporter — override DisposeWithParent => false (lifecycle owned by TyphonProfiler, not the resource tree). They stay registered for display but are disposed only by TyphonProfiler.Stop().
    • AntHill.ProfileRunner — StopCpuSampler() runs after bridge.Dispose(), before TyphonProfiler.Stop().

    Now bridge.Dispose() emits engine-teardown events into the producer rings and tears down the engine tree, but the exporters survive; TyphonProfiler.Stop() then runs the final drain — capturing those teardown events — and disposes the exporters, writing the trailers. No crash; teardown events preserved.

    Verified: AntHill.ProfileRunner --trace with sampling on completes cleanly (no exception), header CpuSampleSectionOffset != 0, .nettrace deleted; full Typhon.Engine.Tests suite green (3703 passed) across repeated runs.

  7. nockawa commented on May 17, 2026

    @nockawa
    CollaboratorAuthor

    Phase 5 — Correlation scoping & cross-panel commanding — accepted plan

    Phase 5 makes the Phase-4 Call Tree commandable: scope the folded CPU-sample tree by a system invocation, a phase, a span kind, or a clicked span instance — each resolving to a set of time-windows server-side — plus the §8.2 non-stationarity sparkline.

    Design: claude/design/Profiler/11-cpu-sampling-integration.md §8.2–§8.5 + §10 Phase 5. Scope confirmed: span-kind included; catalog surface = toolbar selectors in the Call Tree panel.

    Acceptance Criteria

    • AC1 — CallTreeRequestDto gains nullable SystemIndex/Phase/SpanKind; scope precedence span-kind ▸ system ▸ phase ▸ range ▸ whole-session; FrameRoot composes.
    • AC2 — ScopeResolver → sorted/merged/disjoint (qpc,qpc)[] interval set (system tick-relative+offset, phase union, span-kind, range, session sentinel).
    • AC3 — SpanInstanceIndex — per-session lazy chunk-walk, span instances grouped by TraceEventKind.
    • AC4 — CallTreeFolder.Fold filters samples against the interval set (binary search).
    • AC5 — POST calltree resolves scope server-side.
    • AC6 — POST sample-density — binned in-scope sample counts.
    • AC7 — Orval regen.
    • AC8/AC9 — useCallTreeScopeStore, extended useCallTree, new useSampleDensity.
    • AC10/AC11 — Call Tree toolbar System/Phase selectors + scope chip + density sparkline.
    • AC12 — ProfilerDetail "Scope Call Tree to this" action.
    • AC13 — ScopeResolverTests, SampleDensityTests, extended folder/controller tests, Playwright canary.
    • AC14 — build + suites + tsc + vitest green.

    Deviations (approved): sample-density is POST not GET (composite scope, same reasoning as calltree); cross-panel commanding routed via an explicit Detail-panel action rather than hijacking raw timeline clicks (preserves click = select). Phase-4's no-ChunkerVersion-bump deviation carries forward.

  8. added a commit that references this issue on May 17, 2026
  9. moved this from In Progress to Done in Typhon devon May 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Fields

Priority

None yet

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions