Skip to content

Typed-Event Profiler — general-purpose capture subsystem #243

Closed

Description

@nockawa

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.

Motivation

The pre-existing profiler had three latent issues that made it unsuitable as a general-purpose profiler:

  1. Multi-producer race on buffer[0]: [ThreadStatic] t_bufferIndex defaulted to 0 for any thread that hadn't called EnsureWorkerBuffer(workerId). Any non-worker thread emitting events (thread-pool callback calling Transaction.Commit, background task calling ECS.Spawn) wrote to buffer[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.

  2. WorkerId field semantic inconsistency: OnChunkStart wrote WorkerId = workerId (0-indexed raw), while OnActivityStarted wrote WorkerId = t_bufferIndex (1-indexed slot). Same field carried different meanings depending on emit path.

  3. 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 via static readonly gate).

  • Thread slot registry — fixed 256-slot array; threads claim via scan + CAS; retirement via [ThreadStatic] SlotReleaser finalizer. No dependency on ManagedThreadId recycling.

  • 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.Current capture at emit time for distributed-trace interop (TraceIdHi/TraceIdLo stored in the event), with per-thread opt-out so scheduler workers and the profiler consumer thread skip the AsyncLocal lookup.

  • Migrate 20+ call sites from TyphonActivitySource.StartActivity to TyphonEvent.BeginXxx.

  • Delete IRuntimeInspector + TraceEventCaptureBase + DagScheduler.Inspector.cs entirely. No transitional dual API.

  • .typhon-trace file format rewrite — variable-size records, kind-discriminated common header, wire-versioned (Version = 3).

Non-goals

  • ActivityListener compatibility shim — OTel interop goes through a future OTLP exporter or direct .typhon-trace consumption.

  • 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/Stop lifecycle.

  • Phase 3 — Unified TyphonEvent API: factory methods (one per typed event), emit helpers, Activity.Current capture 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.StartActivity to TyphonEvent.BeginXxx; SuppressActivityContextOnThisThread() wiring in DagScheduler worker 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 .nettrace CPU samples.

  • Cache v8 — intra-tick chunk splitting — ChunkerVersion = 8 with ChunkManifestEntry.Flags (bit 0 = IsContinuation). Pathologically dense ticks (millions of events) are split across multiple chunks; the client merges them transparently via mergeTickData chain-fold at assembly time. Gold-standard correctness test pins byte-identical merge output to single-pass output.

  • GC event tracing — dedicated GcEventListener + GcIngestionThread emitting GcStart (7), GcEnd (8), GcSuspension (75). Gated by ProfilerGcTracingActive. Suspensions pre-computed at /api/trace/open for stable yMax across LRU churn.

  • Gauge snapshot system — GaugeSnapshotEmitter emits PerTickSnapshot (kind 76) at end-of-tick, packing a wire-stable GaugeId registry covering memory (unmanaged + GC heap), page cache (buckets + pending IO), transient store, WAL (buffer + staging pool), Transactions + UoW (live counts + cumulative throughput). Gated by ProfilerGaugesActive.

  • Unmanaged allocation tracing — MemoryAllocEvent (kind 9) emitted from PinnedMemoryBlock sites. Gated by ProfilerMemoryAllocationsActive. 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 / legends toggles persisted to localStorage.

  • Server improvements — PathGuard.ValidateTracePath for file-path input validation; ChunkBinaryHeaders const class as single source of truth for custom response headers + CORS exposed-headers list; chunk binary endpoint switched to chunkIdx identity (required for continuation chunks sharing a tick range); RecordDecoder.SetCurrentTickForContinuation for 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 in claude/assets/, also mirrored under tools/Typhon.Profiler.Server/doc/assets/).

  • User manual — covers enabling, configuration (full typhon.telemetry.json schema + 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 (ExporterQueue drop-newest + refcount balance verified in ExporterQueueTests).

  • Scheduler workers opted out of Activity.Current capture via SuppressActivityContextOnThisThread().

  • .typhon-trace files written by FileExporter load 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 in TcpExporterIntegrationTests).

  • AntHill end-to-end: systems visible as spans, worker tracks show chunks.

  • Profiler-off overhead on BeginXxx is indistinguishable from baseline (JIT elimination via TelemetryConfig.ProfilerActive being static readonly).

  • Profiler-on per-span cost ~25–50 ns (better than the original 100 ns target).

  • All 20 original TyphonActivitySource.StartActivity call sites migrated; 5 scheduler-internal sites also migrated.

  • IRuntimeInspector and related old profiler infrastructure deleted.

Open questions — status

  • Per-span-name frequency filter for ultra-high-frequency sites like PageCache.Fetch → Resolved via SpanNameTable.SeedDefaultSuppressions() (deny-list at kind level; UnsuppressSpan/UnsuppressKind runtime API for opt-in). PageCache kinds default-suppressed.

  • Span-name interning wire protocol → Resolved: optional trailing SpanNameTable section in the trace file; TraceFileReader.ReadSpanNames tolerates absence.

  • Consumer cadence jitter on Windows → Resolved: ProfilerConsumerThread derives from HighResolutionTimerServiceBase (self-calibrating Sleep → Yield → Spin, no timeBeginPeriod dependency).

  • TraceEvent.ParentSpanId but no self-SpanId → Resolved: wire format has both SpanId and ParentSpanId in the 25 B span-header extension; SpanId = (slotIdx << 56) | counter, never reset across slot reclaims.

  • ExecutionContext propagation for Activity.Current on non-opt-out paths → Resolved: opt-in rather than opt-out model; scheduler workers + consumer thread explicitly suppress.

  • Remaining: multi-runtime-per-process — current implementation uses a static TyphonProfiler singleton. Deferred as follow-up.

  • Remaining: tick-number wire field — currently derived by decoder counting TickStart records. Adding a native tickNumber field in the TickStart payload would eliminate the reconnect offset. Tracked in design doc §10 follow-ups.

References

Activity

  1. self-assigned this
    on Apr 13, 2026
  2. moved this to Ready in Typhon devon Apr 13, 2026
  3. moved this from Ready to In Progress in Typhon devon Apr 13, 2026
  4. added a commit that references this issue on Apr 19, 2026
  5. changed the title [-]Tracy-Style Profiler — general-purpose capture subsystem[/-] [+]Typed-Event Profiler — general-purpose capture subsystem[/+] on Apr 19, 2026
  6. added a commit that references this issue on Apr 19, 2026
  7. moved this from In Progress to Done in Typhon devon Apr 19, 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