Repository navigation
Description
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:
ExecuteMigrationsProcessClusterShadowEntriesProcessShadowEntries(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).InspectorPhasenow opens a real span instead of emitting a Start/End pair. - Phase span pushed to both
phases[](tick-wide phase track) ANDspans[](TickDriver swimlane) so children correctly nest. - Phase track marker glyphs for
UoW Create(down-triangle) andUoW Flush(circle), drawn in the timeline-palette green for visibility on both light and dark themes. - New
ProfilerSelectionvariants:'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/Timestampfields now display ms-since-recording-start (matching the ruler's labels) instead of raw QPC counters. Centralized via auseGlobalStartUs()selector hook. - Selectable values. Body-level
user-select: none(intentional app-feel default) is overridden via a sharedselect-textclassName on every<dl>in the panel so users can copy SpanIds, durations, etc. - Kind-specific fields surfaced for
PageCacheFlush/FlushCompleted(page count) andPageCacheDiskRead/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, IRawValueUpdaterIRawValueUpdater.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:
claude/overview/02-execution.md§2.1 (UoW lifecycle), §2.3 (durability modes) — followedclaude/overview/06-durability.md— followedclaude/design/Spatial/SpatialTiers/01-spatial-clusters.mdQ1 (migration durability via WriteTickFence-then-UoW.Flush ordering) — preserved
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 viaBeginRuntimePhase, EntityMap →TryUpdateInPlace,ClusterLocationUpdaternested structsrc/Typhon.Engine/Runtime/TyphonRuntime.cs—InspectorPhaseopens a real span;_currentUow.ChangeSetpassed toWriteTickFencesrc/Typhon.Engine/Execution/UnitOfWork.cs+UowRegistry.cs—RecordCommitacceptsexternalCs; threaded throughWriteEntryFieldssrc/Typhon.Engine/Profiler/TyphonEvent.cs—BeginRuntimePhase, deny-list re-tiersrc/Typhon.Engine/Profiler/Events/RuntimePhaseSpanEvent.cs(new) +src/Typhon.Profiler/RuntimePhaseSpanEventCodec.cs(new) +TraceEventKind.cskind 243 +RecordDecoder.csdispatchsrc/Typhon.Engine/Collections/RawValueHashMap.cs—IRawValueUpdaterinterface +TryUpdateInPlace<TUpdater>+UpdateInChainCallbackprivate helpersrc/Typhon.Engine/Observability/TelemetryConfig.cs— comment refresh on the deny-list rationaletools/Typhon.Workbench/ClientApp/src/libs/profiler/decode/chunkDecoder.ts—RuntimePhaseSpan+RuntimePhaseUoWCreate/Flushdecoderstools/Typhon.Workbench/ClientApp/src/libs/profiler/model/types.ts— kind enum,changeCountfieldtools/Typhon.Workbench/ClientApp/src/libs/profiler/model/traceModel.ts—PhaseMarker+PhaseSpan.spanId, tick builder cases, phase span pushed tospans[]tools/Typhon.Workbench/ClientApp/src/libs/profiler/canvas/timeArea.ts—drawPhaseMarkersglyph passtools/Typhon.Workbench/ClientApp/src/libs/profiler/canvas/timeAreaHitTest.ts—'phase-marker'hover variant + findertools/Typhon.Workbench/ClientApp/src/libs/profiler/canvas/hoverTooltipLines.ts— marker tooltip linestools/Typhon.Workbench/ClientApp/src/stores/useProfilerSelectionStore.ts—'phase'+'phase-marker'selection variantstools/Typhon.Workbench/ClientApp/src/panels/profiler/ProfilerDetail.tsx—useGlobalStartUshook,select-textDL_CLASS, kind-specific fields,PhaseDetail+PhaseMarkerDetailbranchestools/Typhon.Workbench/ClientApp/src/panels/profiler/sections/TimeArea.tsx—routeSelectiondispatches phase + phase-markertest/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
BeginClusterMigrationsignature 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
claimstage. 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).
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Area
Activity
Fix CI: refresh stale OpenAPI schema for #291 PR
Cluster migration optimization (#291) (#292)