Repository navigation
Description
Status
✅ Shipped. The design doc has been rewritten as claude/design/Profiler/typhon-profiler.md; the original pre-implementation plan has been superseded and its content promoted to the new design reference.
Everything in the original scope is implemented. Scope grew significantly during the work — see Shipped beyond original scope below.
Summary
Replace the pre-existing scheduler-scoped profiler (IRuntimeInspector + TraceEventCaptureBase with worker-only buffer indexing) with a general-purpose typed-event profiler that any thread in the engine can emit to. Every producer thread gets its own SPSC ring-buffer slot; a dedicated consumer thread drains all slots on a fixed timer cadence and fans out to pluggable exporters.
-
Design doc (current):
claude/design/Profiler/typhon-profiler.md— v3 wire format + viewer Phase 4 + cache v8. -
User manual:
claude/design/Profiler/profiler-user-manual.md(also mirrored attools/Typhon.Profiler.Server/doc/readme.md). -
Feature roadmap (next work):
claude/design/Profiler/06-profiler-feature-roadmap.md.
Motivation
The pre-existing profiler had three latent issues that made it unsuitable as a general-purpose profiler:
-
Multi-producer race on
buffer[0]:[ThreadStatic] t_bufferIndexdefaulted to 0 for any thread that hadn't calledEnsureWorkerBuffer(workerId). Any non-worker thread emitting events (thread-pool callback callingTransaction.Commit, background task callingECS.Spawn) wrote tobuffer[0]— also the timer thread's buffer. Two producers on an SPSC buffer → silent corruption. Latent only because AntHill's hot path happened to emit exclusively from scheduler workers. -
WorkerIdfield semantic inconsistency:OnChunkStartwroteWorkerId = workerId(0-indexed raw), whileOnActivityStartedwroteWorkerId = t_bufferIndex(1-indexed slot). Same field carried different meanings depending on emit path. -
Scheduler-scoped by design: only drained during
OnTickEnd. Structurally couldn't capture events from threads running outside the scheduler's tick loop (initialization, teardown, background tasks, async continuations).
Additionally, TyphonActivitySource.StartActivity(...) paid Activity allocation cost (~150–250 ns per span) for data the scheduler already captured at ~25 ns per event — two APIs feeding the same output with very different per-call costs.
Scope
-
Any-thread emission via
TyphonEvent.BeginXxx(...)factories, 25–50 ns per span when profiler is on, 0 ns when off (JIT-eliminated viastatic readonlygate). -
Thread slot registry — fixed 256-slot array; threads claim via scan + CAS; retirement via
[ThreadStatic] SlotReleaserfinalizer. No dependency onManagedThreadIdrecycling. -
Dedicated consumer thread drains all slots on a fixed cadence (default 1 ms), sorts by timestamp, fans out to per-exporter
BlockingCollection<TraceRecordBatch>queues. -
Per-exporter failure isolation — drop-newest at both producer→slot and consumer→exporter points; per-slot and per-exporter drop counters exposed.
-
Activity.Currentcapture at emit time for distributed-trace interop (TraceIdHi/TraceIdLostored in the event), with per-thread opt-out so scheduler workers and the profiler consumer thread skip theAsyncLocallookup. -
Migrate 20+ call sites from
TyphonActivitySource.StartActivitytoTyphonEvent.BeginXxx. -
Delete
IRuntimeInspector+TraceEventCaptureBase+DagScheduler.Inspector.csentirely. No transitional dual API. -
.typhon-tracefile format rewrite — variable-size records, kind-discriminated common header, wire-versioned (Version = 3).
Non-goals
-
ActivityListenercompatibility shim — OTel interop goes through a future OTLP exporter or direct.typhon-traceconsumption. -
Unbounded thread count — hard cap at 256 concurrent live threads.
-
Lossless capture — drop-newest at both backpressure points.
Implementation phasing
All phases complete.
-
Phase 1 — Capture layer skeleton:
ThreadSlot,ThreadSlotRegistry,SlotReleaser,TraceRecordRing. -
Phase 2 — Consumer thread + exporter plumbing:
TraceRecordBatch+ pool,ExporterQueue,ProfilerConsumerThread,IProfilerExporter,TyphonProfiler.Start/Stoplifecycle. -
Phase 3 — Unified
TyphonEventAPI: factory methods (one per typed event), emit helpers,Activity.Currentcapture at emit time. -
Phase 4 — File + TCP exporters (
FileExporter,TcpExporter). -
Phase 5 — 37 typed event kinds with variable-size records (BTree, Transaction, ECS, PageCache + async completions + backpressure + evicted, WAL, Checkpoint, Statistics, ClusterMigration, NamedSpan, scheduler internals, GC tracing, MemoryAllocEvent, PerTickSnapshot, ThreadInfo).
-
Phase 6 — Migrate 25 call sites from
TyphonActivitySource.StartActivitytoTyphonEvent.BeginXxx;SuppressActivityContextOnThisThread()wiring inDagSchedulerworker entry + profiler consumer thread. -
Phase 7 — Delete
IRuntimeInspector+TraceEventCaptureBase+TraceFileInspector+TcpStreamInspector+DagScheduler.Inspector.cs+TelemetryConfig.SchedulerDeepTrace. -
Phase 8 — Tests + benchmarks: multi-producer stress, consumer drain, slot-registry lifecycle, exporter-queue drop-newest balance, AntHill + IOProfileRunner end-to-end.
Shipped beyond original scope
Work that wasn't in the initial plan but landed on this branch:
-
Scalable viewer (Phase 1–4) — Preact SPA with Canvas-based Gantt, sidecar cache (
.typhon-trace-cache), chunk-based lazy loading, binary LZ4 transport, live SSE streaming, FlameGraph tab fed by.nettraceCPU samples. -
Cache v8 — intra-tick chunk splitting —
ChunkerVersion = 8withChunkManifestEntry.Flags(bit 0 =IsContinuation). Pathologically dense ticks (millions of events) are split across multiple chunks; the client merges them transparently viamergeTickDatachain-fold at assembly time. Gold-standard correctness test pins byte-identical merge output to single-pass output. -
GC event tracing — dedicated
GcEventListener+GcIngestionThreademittingGcStart(7),GcEnd(8),GcSuspension(75). Gated byProfilerGcTracingActive. Suspensions pre-computed at/api/trace/openfor stable yMax across LRU churn. -
Gauge snapshot system —
GaugeSnapshotEmitteremitsPerTickSnapshot(kind 76) at end-of-tick, packing a wire-stableGaugeIdregistry covering memory (unmanaged + GC heap), page cache (buckets + pending IO), transient store, WAL (buffer + staging pool), Transactions + UoW (live counts + cumulative throughput). Gated byProfilerGaugesActive. -
Unmanaged allocation tracing —
MemoryAllocEvent(kind 9) emitted fromPinnedMemoryBlocksites. Gated byProfilerMemoryAllocationsActive. Covers 100% of engine NativeMemory traffic through its single funnel. -
Per-slot thread identity —
ThreadInfo(kind 77) records capture managed thread ID + UTF-8 thread name at slot claim time → viewer labels lanes with meaningful names. -
Browser viewer improvements — worker pool (1–4, least-busy dispatch + per-slot failure isolation), OPFS persistent chunk cache (1 GB/trace, 5 GB global, fingerprint-keyed), assembly memoization via
entriesVersion, gauge region with 5 tracks (Memory / Page Cache / WAL / Tx+UoW / GC) with per-sub-row tooltips and collapsible tracks,View → Show gauges / legendstoggles persisted to localStorage. -
Server improvements —
PathGuard.ValidateTracePathfor file-path input validation;ChunkBinaryHeadersconst class as single source of truth for custom response headers + CORS exposed-headers list; chunk binary endpoint switched tochunkIdxidentity (required for continuation chunks sharing a tick range);RecordDecoder.SetCurrentTickForContinuationfor seeding continuation-chunk decoders. -
Client test infrastructure — Vitest +
@preact/preset-vite, including the gold-standard merge correctness test and tick-counter seed invariants. -
Four D2 architecture diagrams — system architecture, wire protocol, engine pipeline, viewer flow (source in
claude/assets/src/, rendered SVGs inclaude/assets/, also mirrored undertools/Typhon.Profiler.Server/doc/assets/). -
User manual — covers enabling, configuration (full
typhon.telemetry.jsonschema +ProfilerOptions), running the viewer, reading the UI, keyboard shortcuts, performance sizing, troubleshooting.
Acceptance criteria
All criteria from the original scope are met:
-
Any engine thread can emit events via
TyphonEvent.BeginXxx/Emit*without race conditions. -
Finalizer-based retirement drains tail events from exiting threads.
-
Per-exporter failure isolation: a blocked exporter cannot stall other exporters or producers (
ExporterQueuedrop-newest + refcount balance verified inExporterQueueTests). -
Scheduler workers opted out of
Activity.Currentcapture viaSuppressActivityContextOnThisThread(). -
.typhon-tracefiles written byFileExporterload in the viewer with full hierarchy (TraceId/ParentSpanId) where set. -
TCP live stream (
TcpExporter) delivers events to the profiler server within ~50 ms of emission (verified inTcpExporterIntegrationTests). -
AntHill end-to-end: systems visible as spans, worker tracks show chunks.
-
Profiler-off overhead on
BeginXxxis indistinguishable from baseline (JIT elimination viaTelemetryConfig.ProfilerActivebeingstatic readonly). -
Profiler-on per-span cost ~25–50 ns (better than the original 100 ns target).
-
All 20 original
TyphonActivitySource.StartActivitycall sites migrated; 5 scheduler-internal sites also migrated. -
IRuntimeInspectorand related old profiler infrastructure deleted.
Open questions — status
-
Per-span-name frequency filter for ultra-high-frequency sites like→ Resolved viaPageCache.FetchSpanNameTable.SeedDefaultSuppressions()(deny-list at kind level;UnsuppressSpan/UnsuppressKindruntime API for opt-in). PageCache kinds default-suppressed. -
Span-name interning wire protocol→ Resolved: optional trailingSpanNameTablesection in the trace file;TraceFileReader.ReadSpanNamestolerates absence. -
Consumer cadence jitter on Windows→ Resolved:ProfilerConsumerThreadderives fromHighResolutionTimerServiceBase(self-calibrating Sleep → Yield → Spin, notimeBeginPerioddependency). -
→ Resolved: wire format has bothTraceEvent.ParentSpanIdbut no self-SpanIdSpanIdandParentSpanIdin the 25 B span-header extension;SpanId = (slotIdx << 56) | counter, never reset across slot reclaims. -
→ Resolved: opt-in rather than opt-out model; scheduler workers + consumer thread explicitly suppress.ExecutionContextpropagation forActivity.Currenton non-opt-out paths -
Remaining: multi-runtime-per-process — current implementation uses a static
TyphonProfilersingleton. Deferred as follow-up. -
Remaining: tick-number wire field — currently derived by decoder counting
TickStartrecords. Adding a nativetickNumberfield in theTickStartpayload would eliminate the reconnect offset. Tracked in design doc §10 follow-ups.
References
-
Design doc (current):
claude/design/Profiler/typhon-profiler.md -
User manual:
claude/design/Profiler/profiler-user-manual.md(also undertools/Typhon.Profiler.Server/doc/) -
Feature roadmap:
claude/design/Profiler/06-profiler-feature-roadmap.md -
Observability architecture:
claude/overview/09-observability.md -
Runtime architecture:
claude/overview/13-runtime.md -
Companion observability design docs:
-
Predecessor profiler reference (archived):
claude/reference/observability/runtime-profiler.md— describes the pre-Typed-Event Profiler — general-purpose capture subsystem #243 32-byte fixed-event profiler (stale; this work replaces it). -
Previous profiler PR: Runtime profiler: trace format, file/live inspectors, viewer UI #238 (Typhon profiler, lib + viewer).
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
Solved #243 and more
[-]Tracy-Style Profiler — general-purpose capture subsystem[/-][+]Typed-Event Profiler — general-purpose capture subsystem[/+]Typhon Profiler (#243) (#245)
GC pauses reach the trace again: the GC suspension's reason is read f…