Repository navigation
Closed
Description
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 viatyphon.telemetry.json(Typhon:Profiler:CpuSampling:Enabled), same mechanism asGcTracing. Fixed 1 kHz. No global tool, no special CLR launch. - No
.nettrace— parsed atTyphonProfiler.Stop, embedded as a.typhon-tracetrailer 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
ThreadSchedulingoff-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.jsonconfig +TelemetryConfigfields,ProfilerLauncherwiring, deleteEventPipeSampler.cs. - Phase 2 — Parse + resolve. EventPipe-stream parser (
TraceLog),SystemSourceResolver(module, token)extension, thread-id → slot mapping. - Phase 3 — Wire format.
.typhon-traceCPU-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,CallTreepanel (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-densityendpoint, Thread Track + catalogs as scope commanders.
Metadata
Metadata
Assignees
Labels
No labels
Type
Fields
Priority
None yet
Activity
nockawa commentedon May 16, 2026
Phase 2 — Parse + Resolve — complete ✅
All 10 acceptance criteria met. Library phase: the Phase-1
.nettraceis now parsed into a typed, symbol-resolvedCpuSamplelist. Exercised by unit tests; wire-format integration is Phase 3.New files
src/Typhon.Engine/Profiler/internals/CpuSample.cs—CpuSample/CpuSampleFramemodel types.src/Typhon.Engine/Profiler/internals/CpuSampleParser.cs—TraceLog-based.nettraceparser.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; sharedResolveCoreextracted.AC evidence
CpuSampleParser.ParseviaTraceLog.CreateFromEventPipeDataFile, enumeratesSampleProfilerTraceEventParser.ThreadSample, dropsErrorsamples —Parse_ProducesSamples.ThreadSlotRegistry.TryGetSlotByOsThreadId, non-Typhon kept at-1—Parse_MapsTyphonThreadToItsSlot,Parse_KeepsNonTyphonThreadsUnslotted.ResolveByToken+ IL-offset covering SP —ResolveByToken_KnownMethod_ResolvesToSource,ResolveByToken_WithIlOffset_PicksCoveringSequencePoint.file:line, BCL/native → name-only —Parse_ResolvesEngineFrameToSource,Parse_ResolvesUnknownModuleFramesNameOnly.Parse_NonExistentFile/NullOrEmptyPath/CorruptFile_ReturnsEmpty.TraceFileHeader/FileExporter/TyphonProfiler/cache unchanged); no new NuGet —git diffconfirmed.Typhon.Engine.Testssuite green (3695 passed / 34 skipped). One intermittent failure observed in 1/11 runs —WAL_Commit_DurableLsnAdvances, a pre-existingArchetypeRegistrycascade-diamond flake from parallel-fixture shared-static contention, unrelated to this change.Research note: design §9 risk 8 resolved —
ClrThreadSampleTraceData.ThreadIDis the OS thread id; no managed↔OS bridge needed.Ready for review + commit (not committed — per convention).
nockawa commentedon May 16, 2026
Phase 3 — Wire Format / Trailer Section — complete ✅
All 11 acceptance criteria met. CPU samples are now persisted into the
.typhon-traceas a v10 trailer section; the transient.nettraceis parsed and deleted.New files
src/Typhon.Profiler/CpuSampleSection.cs—CpuSampleRecord/CpuFrameSymbolwire types.src/Typhon.Engine/Profiler/internals/CpuSampleSectionEncoder.cs— interns stacks + frame symbols into the shared FileTable.Modified
TraceFileHeader—CurrentVersion9 → 10; newCpuSampleSectionOffset(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.NetTracePathexposed.AntHill.ProfileRunner/Program.cs—StopCpuSampler()ordered beforebridge.Dispose().End-to-end verified —
AntHill.ProfileRunner --tracewith CPU sampling on: headerCpuSampleSectionOffset != 0;TryReadCpuSampleSectionreads back 147,244 samples / 900 interned stacks / 1042 frame symbols (811 resolved to realfile:line); thread slots-1+0..22;.nettracedeleted. With sampling off:CpuSampleSectionOffset == 0, no.nettrace.Tests —
CpuSampleSectionRoundTripTests(3),CpuSampleSectionEncoderTests(5),FileExporterIntegrationTests(+1). FullTyphon.Engine.Testssuite green (3703 passed / 34 skipped); v9 traces still read under the v10 reader.Approved deviations (confirmed before implementation): orchestration in
ProfilerLauncher(notTyphonProfiler.Stop—TyphonProfileruntouched); cache propagation deferred to Phase 4.Design clarification — design §6.5 says a name-only frame uses
fileId 0; the.typhon-traceFileTable reserves no 0-sentinel (index 0 is a real file), soCpuFrameSymbol.HasSourcekeys online == 0instead. Documented in the struct.Pre-existing bug surfaced (not Phase 3, not blocking):
AntHill.ProfileRunnercallsbridge.Dispose()beforeTyphonProfiler.Stop();bridge.Dispose()tears down the engine resource tree the exporters live under, so the subsequentTyphonProfiler.Stop()throwsObjectDisposedExceptionon the disposed exporter queue. The.typhon-traceis 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).
nockawa commentedon May 16, 2026
Follow-up — the shutdown-ordering crash is fixed (not deferred)
The
ObjectDisposedExceptionflagged above was an ownership bug:FileExporter/TcpExporterareResourceNodes parented under the engine'sProfilernode, andResourceNode.Dispose()unconditionally cascade-disposes children — sobridge.Dispose()closed the exporter's trace file mid-teardown, beforeTyphonProfiler.Stop()could drain the engine-teardown events into it.Fix — decouple tree membership from lifecycle:
ResourceNode— newpublic virtual bool DisposeWithParent => true; theDispose(bool)cascade skips children where it isfalse.FileExporter/TcpExporter— overrideDisposeWithParent => false(lifecycle owned byTyphonProfiler, not the resource tree). They stay registered for display but are disposed only byTyphonProfiler.Stop().AntHill.ProfileRunner—StopCpuSampler()runs afterbridge.Dispose(), beforeTyphonProfiler.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 --tracewith sampling on completes cleanly (no exception), headerCpuSampleSectionOffset != 0,.nettracedeleted; fullTyphon.Engine.Testssuite green (3703 passed) across repeated runs.nockawa commentedon May 17, 2026
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
CallTreeRequestDtogains nullableSystemIndex/Phase/SpanKind; scope precedence span-kind ▸ system ▸ phase ▸ range ▸ whole-session;FrameRootcomposes.ScopeResolver→ sorted/merged/disjoint(qpc,qpc)[]interval set (system tick-relative+offset, phase union, span-kind, range, session sentinel).SpanInstanceIndex— per-session lazy chunk-walk, span instances grouped byTraceEventKind.CallTreeFolder.Foldfilters samples against the interval set (binary search).POST calltreeresolves scope server-side.POST sample-density— binned in-scope sample counts.useCallTreeScopeStore, extendeduseCallTree, newuseSampleDensity.ProfilerDetail"Scope Call Tree to this" action.ScopeResolverTests,SampleDensityTests, extended folder/controller tests, Playwright canary.Deviations (approved):
sample-densityis POST not GET (composite scope, same reasoning ascalltree); 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.CPU Sampling Integration (#351) + AntHill refactoring (#352) (#355)
GC pauses reach the trace again: the GC suspension's reason is read f…