Skip to content

Cluster migration optimization umbrella #291

Closed

Description

@nockawa

Summary

Started as a perf hunt on DatabaseEngine.ExecuteMigrations (cluster cell-crossing migrations storming AntHill at 28 ms / tick on the TickDriver thread). The investigation surfaced an architectural bug in tick-fence ChangeSet ownership, a profiler observability gap that prevented spotting it, and a missing DI registration in AntHill that silently downgraded it to WAL-less mode. All three were fixed; the migration loop itself also got a focused micro-optimization. Net result on AntHill's storm tick: 28 ms → 2.96 ms (≈9.5×) with the architecture now correct, the profiler showing what's actually happening, and a reusable in-place hashmap update primitive added.

Trigger

User-reported "cluster migration is way too slow." Initial breakdown showed the migration loop body itself was healthy (~3 ms of useful work) but the trailing ChangeSet.SaveChanges() was 22 ms — 88% of the total. That single observation cascaded.

What was actually delivered

A. Tick-fence ChangeSet ownership architectural correction

Per claude/overview/02-execution.md §2.1 the UoW owns the shared ChangeSet for Deferred/GroupCommit modes. Four tick-fence methods each created a private ChangeSet and called SaveChanges themselves, bypassing the UoW lifecycle entirely:

  • ExecuteMigrations
  • ProcessClusterShadowEntries
  • ProcessShadowEntries (per indexed field — N saves per tick)
  • ProcessSpatialEntries

UowRegistry.RecordCommit had the same bug — its WriteEntryFields helper created a private CS and saved it.

In WAL mode this was redundant (WAL records carry durability; pages stay dirty until checkpoint). In WAL-less Deferred mode it duplicated work the UoW.Flush would do centrally. Fix: thread _currentUow.ChangeSet from TyphonRuntime.OnTickEndInternal → WriteTickFence(tickNumber, ChangeSet) → WriteClusterTickFence → all four callees, plus RecordCommit(uowId, maxTSN, externalCs) → WriteEntryFields(externalCs). Test/admin callers that invoke WriteTickFence without a UoW get a one-shot local ChangeSet owned by WriteTickFence itself — preserves the existing public API.

B. Profiler observability — phases as real spans + click-to-detail

The phase track only rendered WriteTickFence because the legacy EmitPhaseStart/EmitPhaseEnd instant pair required both events, and only one of the three phases happened to land both reliably. Worse, child spans started inside a phase (PageCacheFlush, ClusterMigration, etc.) had no parent to attach to, so they appeared as orphan roots on the TickDriver lane.

  • New typed span kind RuntimePhaseSpan = 243 (engine + protocol + workbench decoder). InspectorPhase now opens a real span instead of emitting a Start/End pair.
  • Phase span pushed to both phases[] (tick-wide phase track) AND spans[] (TickDriver swimlane) so children correctly nest.
  • Phase track marker glyphs for UoW Create (down-triangle) and UoW Flush (circle), drawn in the timeline-palette green for visibility on both light and dark themes.
  • New ProfilerSelection variants: 'phase' and 'phase-marker'. Click on a phase span or glyph opens a dedicated DetailPane section.
  • Hit test: glyphs win over phase bars when the cursor is on a marker (±4 px hot zone).

C. Profiler observability — suppression deny-list re-tier

The per-kind suppression array in TyphonEvent's static ctor was over-tiered: it bundled diagnostic-grade kinds (PageCacheFlush, DiskRead/Write, Evicted, AllocatePage, FlushCompleted, DiskRead/WriteCompleted, Backpressure, RecoveryRecord, UoWState, UoWDeadline) with the truly extreme-frequency ones (PageCacheFetch). Result: those 12 kinds were unreachable from JSON config alone — operators had to call UnsuppressKind from C# to enable them, defeating the config tree's purpose.

After the re-tier the deny-list contains only kinds that fire ≥ 10⁵/sec on realistic workloads (PageCacheFetch, DataMvccChainWalk, DataIndexBTreeSearch/NodeCow, QueryExecuteIterate/Filter/Pagination, EcsQueryMaskAnd, EcsViewProcessEntry/Or, DurabilityWalFrame, RuntimeSubscriptionSubscriber/DeltaSerialize). Diagnostic-grade kinds are now gated solely by their JSON category (Storage:PageCache:Enabled, Durability:UoW:Enabled, etc.) like everything else.

D. Profiler observability — DetailPane UX

  • Relative timestamps. All Start / End / Timestamp fields now display ms-since-recording-start (matching the ruler's labels) instead of raw QPC counters. Centralized via a useGlobalStartUs() selector hook.
  • Selectable values. Body-level user-select: none (intentional app-feel default) is overridden via a shared select-text className on every <dl> in the panel so users can copy SpanIds, durations, etc.
  • Kind-specific fields surfaced for PageCacheFlush/FlushCompleted (page count) and PageCacheDiskRead/Write/AllocatePage/Evicted (file page index + page count). The page-count fingerprint was the smoking gun that proved the 1050-page flush was the migration's full dirty page set.

E. The actual perf wins

E.1. AntHill WAL registration fix (the big one)

DatabaseEngine.InitializeWalManager requires both WalWriterOptions AND an IWalFileIO registered in DI. AntHill set the options but didn't register IWalFileIO, so InitializeWalManager silently early-returned and WalManager stayed null. AntHill was therefore running WAL-less Deferred all along. Every UoW.Flush hit the WAL-less branch:

else if (_durabilityMode == DurabilityMode.Deferred)
{
    ChangeSet.SaveChanges();   // ← writes 1050 dirty migration pages synchronously
    _dbe.MMF.FlushToDisk();    // ← fsync of the data file
}

→ blocks TickDriver for ~22 ms per storm.

Single-line fix: .AddSingleton<IWalFileIO, WalFileIO>() in TyphonBridge.Initialize(). UoW.Flush switches to the WAL branch (RequestFlush + WaitForDurable), the WAL writer thread does the I/O asynchronously, and checkpoint thread writes pages later. Migration storm: 28 ms → 3.18 ms.

E.2. EntityMap TryUpdateInPlace primitive

Migration step 9 (update EntityMap with new (chunkId, slot)) was a TryGet + mutate-stack-buffer + Upsert pair — two chain scans, two OLC ops, one full-record memcpy. New primitive on RawValuePagedHashMap:

public bool TryUpdateInPlace<TUpdater>(TKey key, ref TUpdater updater,
    ref ChunkAccessor<TStore> accessor, ChangeSet changeSet)
    where TUpdater : struct, IRawValueUpdater

IRawValueUpdater.Update(byte* valueBytes) callback runs while the bucket holds the OLC write lock and the page is dirty-marked. Struct constraint enables JIT devirtualisation. Migration uses a small ClusterLocationUpdater that writes the 5 bytes that change.

Single chain scan, single OLC critical section. EntityMap stage 1.79 → 1.40 ms (-22%; smaller than projected because most of the cost is page indirection on cold buckets, fundamental to the random access pattern). Storm total: 3.18 → 2.96 ms.

The primitive is generic and reusable for any other in-place hashmap update use case.

Net effect on AntHill storm tick

Metric Before After Speedup
Migration storm total ~28 ms 2.96 ms 9.5×
UoW.Flush phase on TickDriver 22 ms (synchronous SaveChanges) µs-range —
WAL/Checkpoint visibility absent spans appear on dedicated lanes —

Why this is umbrella-shaped

The architectural fix (A) was prerequisite for the proper UoW.ChangeSet plumbing the migration relies on. The observability work (B–D) was prerequisite for diagnosis (without phase spans we couldn't see PageCacheFlush attaching to UoW.Flush; without page-count in DetailPane we couldn't fingerprint the 1050-page flush; without the WAL/Checkpoint kinds reachable from config we couldn't see the WAL writer thread once it appeared). Each piece is independently valuable, but the perf result depended on all of them landing together.

Documentation impact

No design doc updates landed in this work; the changes are all aligned with existing conventions in:

A short note added to claude/design/Observability/ capturing the deny-list re-tier rationale would be reasonable follow-up but not blocking.

Files changed (high level)

  • src/Typhon.Engine/Data/DatabaseEngine.cs — tick-fence ChangeSet plumbing (4 callees), phase span via BeginRuntimePhase, EntityMap → TryUpdateInPlace, ClusterLocationUpdater nested struct
  • src/Typhon.Engine/Runtime/TyphonRuntime.cs — InspectorPhase opens a real span; _currentUow.ChangeSet passed to WriteTickFence
  • src/Typhon.Engine/Execution/UnitOfWork.cs + UowRegistry.cs — RecordCommit accepts externalCs; threaded through WriteEntryFields
  • src/Typhon.Engine/Profiler/TyphonEvent.cs — BeginRuntimePhase, deny-list re-tier
  • src/Typhon.Engine/Profiler/Events/RuntimePhaseSpanEvent.cs (new) + src/Typhon.Profiler/RuntimePhaseSpanEventCodec.cs (new) + TraceEventKind.cs kind 243 + RecordDecoder.cs dispatch
  • src/Typhon.Engine/Collections/RawValueHashMap.cs — IRawValueUpdater interface + TryUpdateInPlace<TUpdater> + UpdateInChainCallback private helper
  • src/Typhon.Engine/Observability/TelemetryConfig.cs — comment refresh on the deny-list rationale
  • tools/Typhon.Workbench/ClientApp/src/libs/profiler/decode/chunkDecoder.ts — RuntimePhaseSpan + RuntimePhaseUoWCreate/Flush decoders
  • tools/Typhon.Workbench/ClientApp/src/libs/profiler/model/types.ts — kind enum, changeCount field
  • tools/Typhon.Workbench/ClientApp/src/libs/profiler/model/traceModel.ts — PhaseMarker + PhaseSpan.spanId, tick builder cases, phase span pushed to spans[]
  • tools/Typhon.Workbench/ClientApp/src/libs/profiler/canvas/timeArea.ts — drawPhaseMarkers glyph pass
  • tools/Typhon.Workbench/ClientApp/src/libs/profiler/canvas/timeAreaHitTest.ts — 'phase-marker' hover variant + finder
  • tools/Typhon.Workbench/ClientApp/src/libs/profiler/canvas/hoverTooltipLines.ts — marker tooltip lines
  • tools/Typhon.Workbench/ClientApp/src/stores/useProfilerSelectionStore.ts — 'phase' + 'phase-marker' selection variants
  • tools/Typhon.Workbench/ClientApp/src/panels/profiler/ProfilerDetail.tsx — useGlobalStartUs hook, select-text DL_CLASS, kind-specific fields, PhaseDetail + PhaseMarkerDetail branches
  • tools/Typhon.Workbench/ClientApp/src/panels/profiler/sections/TimeArea.tsx — routeSelection dispatches phase + phase-marker
  • test/AntHill/Engine/TyphonBridge.cs — .AddSingleton<IWalFileIO, WalFileIO>() (the perf-bug fix)
  • Test fixtures (spanBuilder.ts, timeAreaLayout.test.ts, selectionStats.test.ts) — phaseMarkers: [] field
  • 2 test sites for BeginClusterMigration signature change (componentCount param)

Verification status

  • Engine: 3638/3671 tests pass (one pre-existing flaky concurrent BTree test unrelated to this work).
  • Workbench: 246/246 vitest pass; TypeScript clean.
  • AntHill: builds clean, profiles cleanly, WAL/Checkpoint spans visible.

Out of scope (potential follow-ups)

  • Lead 1 — sort migrations by destCellKey. Would shave ~0.4 ms off the claim stage. Not pursued: at 2.96 ms total, migration is no longer a meaningful contributor.
  • Software prefetch of EntityMap buckets. Would chip into the entityMap stage's residual 1.4 ms. Code complexity vs sub-ms gains — not justified.
  • Brief design note capturing the deny-list re-tiering rationale (where to place a kind: deny-list vs config-only).

Activity

  1. added
    performance
    refactoring
    on Apr 30, 2026
  2. moved this to In Progress in Typhon devon Apr 30, 2026
  3. added a commit that references this issue on Apr 30, 2026
  4. moved this from In Progress to Done in Typhon devon Apr 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancerefactoring

    Type

    No type

    Fields

    Priority

    None yet

    Area

    Workbench

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions