Files
hakmem/docs/PHASE_E2_REGRESSION_ANALYSIS.md
Moe Charm (CI) 72b38bc994 Phase E3-FINAL: Fix Box API offset bugs - ALL classes now use correct offsets
## Root Cause Analysis (GPT5)

**Physical Layout Constraints**:
- Class 0: 8B = [1B header][7B payload] → offset 1 = 9B needed =  IMPOSSIBLE
- Class 1-6: >=16B = [1B header][15B+ payload] → offset 1 =  POSSIBLE
- Class 7: 1KB → offset 0 (compatibility)

**Correct Specification**:
- HAKMEM_TINY_HEADER_CLASSIDX != 0:
  - Class 0, 7: next at offset 0 (overwrites header when on freelist)
  - Class 1-6: next at offset 1 (after header)
- HAKMEM_TINY_HEADER_CLASSIDX == 0:
  - All classes: next at offset 0

**Previous Bug**:
- Attempted "ALL classes offset 1" unification
- Class 0 with offset 1 caused immediate SEGV (9B > 8B block size)
- Mixed 2-arg/3-arg API caused confusion

## Fixes Applied

### 1. Restored 3-Argument Box API (core/box/tiny_next_ptr_box.h)
```c
// Correct signatures
void tiny_next_write(int class_idx, void* base, void* next_value)
void* tiny_next_read(int class_idx, const void* base)

// Correct offset calculation
size_t offset = (class_idx == 0 || class_idx == 7) ? 0 : 1;
```

### 2. Updated 123+ Call Sites Across 34 Files
- hakmem_tiny_hot_pop_v4.inc.h (4 locations)
- hakmem_tiny_fastcache.inc.h (3 locations)
- hakmem_tiny_tls_list.h (12 locations)
- superslab_inline.h (5 locations)
- tiny_fastcache.h (3 locations)
- ptr_trace.h (macro definitions)
- tls_sll_box.h (2 locations)
- + 27 additional files

Pattern: `tiny_next_read(base)` → `tiny_next_read(class_idx, base)`
Pattern: `tiny_next_write(base, next)` → `tiny_next_write(class_idx, base, next)`

### 3. Added Sentinel Detection Guards
- tiny_fast_push(): Block nodes with sentinel in ptr or ptr->next
- tls_list_push(): Block nodes with sentinel in ptr or ptr->next
- Defense-in-depth against remote free sentinel leakage

## Verification (GPT5 Report)

**Test Command**: `./out/release/bench_random_mixed_hakmem --iterations=70000`

**Results**:
-  Main loop completed successfully
-  Drain phase completed successfully
-  NO SEGV (previous crash at iteration 66151 is FIXED)
- ℹ️ Final log: "tiny_alloc(1024) failed" is normal fallback to Mid/ACE layers

**Analysis**:
- Class 0 immediate SEGV:  RESOLVED (correct offset 0 now used)
- 66K iteration crash:  RESOLVED (offset consistency fixed)
- Box API conflicts:  RESOLVED (unified 3-arg API)

## Technical Details

### Offset Logic Justification
```
Class 0:  8B block → next pointer (8B) fits ONLY at offset 0
Class 1: 16B block → next pointer (8B) fits at offset 1 (after 1B header)
Class 2: 32B block → next pointer (8B) fits at offset 1
...
Class 6: 512B block → next pointer (8B) fits at offset 1
Class 7: 1024B block → offset 0 for legacy compatibility
```

### Files Modified (Summary)
- Core API: `box/tiny_next_ptr_box.h`
- Hot paths: `hakmem_tiny_hot_pop*.inc.h`, `tiny_fastcache.h`
- TLS layers: `hakmem_tiny_tls_list.h`, `hakmem_tiny_tls_ops.h`
- SuperSlab: `superslab_inline.h`, `tiny_superslab_*.inc.h`
- Refill: `hakmem_tiny_refill.inc.h`, `tiny_refill_opt.h`
- Free paths: `tiny_free_magazine.inc.h`, `tiny_superslab_free.inc.h`
- Documentation: Multiple Phase E3 reports

## Remaining Work

None for Box API offset bugs - all structural issues resolved.

Future enhancements (non-critical):
- Periodic `grep -R '*(void**)' core/` to detect direct pointer access violations
- Enforce Box API usage via static analysis
- Document offset rationale in architecture docs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-13 06:50:20 +09:00

16 KiB

Phase E2: Performance Regression Root Cause Analysis

Date: 2025-11-12 Status: COMPLETE Target: Restore Phase 7 performance (4.8M → 59-70M ops/s, +1125-1358%)


Executive Summary

Performance Regression Identified

Metric Phase 7 (Peak) Current (Phase E1+) Regression
128B 59M ops/s 9.2M ops/s -84% 😱
256B 70M ops/s 9.4M ops/s -87% 😱
512B 68M ops/s 8.4M ops/s -88% 😱
1024B 65M ops/s 8.4M ops/s -87% 😱

Root Cause: Unnecessary Registry Lookup in Fast Path

Commit: 5eabb89ad9 ("WIP: 150K SEGV investigation") Date: 2025-11-12 15:59:31 Impact: Added 50-100 cycle SuperSlab lookup on EVERY free operation

Critical Issue: The fix was applied AFTER Phase E1 had already solved the underlying problem by adding headers to C7!


Timeline: Phase 7 Success → Regression

Phase 7-1.3 (Nov 8, 2025) - Peak Performance

Commit: 498335281 (Hybrid mincore + Macro fix) Performance: 59-70M ops/s Key Achievement: Ultra-fast free path (5-10 cycles)

Architecture:

// core/tiny_free_fast_v2.inc.h (Phase 7-1.3)
static inline int hak_tiny_free_fast_v2(void* ptr) {
    if (!ptr) return 0;

    // FAST: 1KB alignment heuristic (1-2 cycles)
    if (((uintptr_t)ptr & 0x3FF) == 0) {
        return 0;  // C7 likely, use slow path
    }

    // FAST: Page boundary check (1-2 cycles)
    if (((uintptr_t)ptr & 0xFFF) == 0) {
        if (!hak_is_memory_readable(ptr-1)) return 0;
    }

    // FAST: Read header (2-3 cycles)
    int class_idx = tiny_region_id_read_header(ptr);
    if (class_idx < 0) return 0;

    // FAST: Push to TLS freelist (3-5 cycles)
    void* base = (char*)ptr - 1;
    *(void**)base = g_tls_sll_head[class_idx];
    g_tls_sll_head[class_idx] = base;
    g_tls_sll_count[class_idx]++;

    return 1;  // Total: 5-10 cycles ✅
}

Result: 59-70M ops/s (+180-280% vs baseline)


Phase E1 (Nov 12, 2025) - C7 Header Added

Commit: baaf815c9 (Add 1-byte header to C7) Purpose: Eliminate C7 special cases + fix 150K SEGV Key Change: ALL classes (C0-C7) now have 1-byte header

Impact:

  • C7 false positive rate: 6.25% → 0%
  • SEGV eliminated at 150K+ iterations
  • 33 C7 special cases removed across 20 files
  • Performance: 8.6-9.4M ops/s (good, but not Phase 7 peak)

Architecture Change:

// core/tiny_region_id.h (Phase E1)
static inline void* tiny_region_id_write_header(void* base, int class_idx) {
    // Phase E1: ALL classes (C0-C7) now have header
    uint8_t* header_ptr = (uint8_t*)base;
    *header_ptr = HEADER_MAGIC | (class_idx & HEADER_CLASS_MASK);
    return header_ptr + 1;  // C7 included!
}

Commit 5eabb89ad9 (Nov 12, 2025) - THE REGRESSION

Commit: 5eabb89ad9 ("WIP: 150K SEGV investigation") Time: 2025-11-12 15:59:31 (3 hours AFTER Phase E1) Impact: Added Registry lookup on EVERY free (50-100 cycles overhead)

The Mistake:

// core/tiny_free_fast_v2.inc.h (Commit 5eabb89ad9) - SLOW!
static inline int hak_tiny_free_fast_v2(void* ptr) {
    if (!ptr) return 0;

    // ❌ SLOW: Registry lookup (50-100 cycles, O(log N) RB-tree)
    extern struct SuperSlab* hak_super_lookup(void* ptr);
    struct SuperSlab* ss = hak_super_lookup(ptr);
    if (ss && ss->size_class == 7) {
        return 0;  // C7 detected → slow path
    }

    // FAST: Page boundary check (1-2 cycles)
    void* header_addr = (char*)ptr - 1;
    if (((uintptr_t)ptr & 0xFFF) == 0) {
        if (!hak_is_memory_readable(header_addr)) return 0;
    }

    // FAST: Read header (2-3 cycles)
    int class_idx = tiny_region_id_read_header(ptr);
    if (class_idx < 0) return 0;

    // ... rest of fast path ...

    return 1;  // Total: 50-110 cycles (10x slower!) ❌
}

Why This Is Wrong:

  1. Phase E1 already fixed the problem: C7 now has headers!
  2. Registry lookup is unnecessary: Header magic validation (2-3 cycles) is sufficient
  3. Performance impact: 50-100 cycles added to EVERY free operation
  4. Cost breakdown:
    • Phase 7: 5-10 cycles per free
    • Current: 55-110 cycles per free (11x slower)
    • Result: 59M → 9M ops/s (-85% regression)

Additional Bottleneck: Registry-First Classification

File: core/box/hak_free_api.inc.h Commit: a97005f50 (Front Gate: registry-first classification) Date: 2025-11-11

The Problem:

// core/box/hak_free_api.inc.h (line 117) - SLOW!
void hak_free_at(void* ptr, size_t size, hak_callsite_t site) {
    if (!ptr) return;

    // Try ultra-fast free first (good!)
    if (hak_tiny_free_fast_v2(ptr)) {
        goto done;
    }

    // ❌ SLOW: Registry lookup AGAIN (50-100 cycles)
    ptr_classification_t classification = classify_ptr(ptr);

    // ... route based on classification ...
}

Current classify_ptr() Implementation:

// core/box/front_gate_classifier.h (line 192) - SLOW!
static inline ptr_classification_t classify_ptr(void* ptr) {
    // ❌ Registry lookup FIRST (50-100 cycles)
    result = registry_lookup(ptr);
    if (result.kind == PTR_KIND_TINY_HEADER) {
        return result;
    }

    // Header probe only as fallback
    // ...
}

Phase 7 Approach (Fast):

// Phase 7: Header-first classification (5-10 cycles)
static inline ptr_classification_t classify_ptr(void* ptr) {
    // ✅ Try header probe FIRST (2-3 cycles)
    int class_idx = safe_header_probe(ptr);
    if (class_idx >= 0) {
        result.kind = PTR_KIND_TINY_HEADER;
        result.class_idx = class_idx;
        return result;  // Fast path: 2-3 cycles!
    }

    // Fallback to Registry (rare)
    return registry_lookup(ptr);
}

Performance Analysis

Cycle Breakdown

Operation Phase 7 Current Delta
Fast path check (alignment) 1-2 0 -1
Registry lookup 0 50-100 +50-100
Page boundary check 1-2 1-2 0
Header read 2-3 2-3 0
TLS freelist push 3-5 3-5 0
TOTAL (fast path) 5-10 55-110 +50-100

Throughput Impact

Assumptions:

  • CPU: 3.0 GHz (3 cycles/ns)
  • Cache: L1 hit rate 95%
  • Allocation pattern: 50% alloc, 50% free

Phase 7:

Free cost: 10 cycles → 3.3 ns
Throughput: 1 / 3.3 ns = 300M frees/s per core
Mixed workload (50% alloc/free): ~150M ops/s per core
Observed (4 cores, 50% efficiency): 59-70M ops/s ✅

Current:

Free cost: 100 cycles → 33 ns (10x slower)
Throughput: 1 / 33 ns = 30M frees/s per core
Mixed workload: ~15M ops/s per core
Observed (4 cores, 50% efficiency): 8-9M ops/s ❌

Regression Confirmed: 10x slowdown in free path → 6-7x slower overall throughput


Root Cause Summary

Primary Cause: Unnecessary Registry Lookup

File: core/tiny_free_fast_v2.inc.h Lines: 54-63 Commit: 5eabb89ad9

Problem:

// ❌ UNNECESSARY: C7 now has header (Phase E1)!
extern struct SuperSlab* hak_super_lookup(void* ptr);
struct SuperSlab* ss = hak_super_lookup(ptr);
if (ss && ss->size_class == 7) {
    return 0;  // C7 detected → slow path
}

Why It's Wrong:

  1. Phase E1 added headers to C7 - header validation is sufficient
  2. Registry lookup costs 50-100 cycles - O(log N) RB-tree search
  3. Called on EVERY free - no early exit for common case
  4. Redundant: Header magic validation already distinguishes C7 from non-Tiny

Secondary Cause: Registry-First Classification

File: core/box/front_gate_classifier.h Lines: 192-206 Commit: a97005f50

Problem: Slow path classification uses Registry-first instead of Header-first


Fix Strategy for Phase E3

Fix 1: Remove Unnecessary Registry Lookup (Primary)

File: core/tiny_free_fast_v2.inc.h Lines: 54-63 Priority: P0 - CRITICAL

Before (Current - SLOW):

static inline int hak_tiny_free_fast_v2(void* ptr) {
    if (!ptr) return 0;

    // ❌ SLOW: Registry lookup (50-100 cycles)
    extern struct SuperSlab* hak_super_lookup(void* ptr);
    struct SuperSlab* ss = hak_super_lookup(ptr);
    if (ss && ss->size_class == 7) {
        return 0;
    }

    void* header_addr = (char*)ptr - 1;

    // Page boundary check...
    // Header read...
    // TLS push...
}

After (Phase 7 style - FAST):

static inline int hak_tiny_free_fast_v2(void* ptr) {
    if (!ptr) return 0;

    // ✅ FAST: Page boundary check (1-2 cycles)
    void* header_addr = (char*)ptr - 1;
    if (((uintptr_t)ptr & 0xFFF) == 0) {
        extern int hak_is_memory_readable(void* addr);
        if (!hak_is_memory_readable(header_addr)) {
            return 0;  // Page boundary allocation
        }
    }

    // ✅ FAST: Read header with magic validation (2-3 cycles)
    int class_idx = tiny_region_id_read_header(ptr);
    if (class_idx < 0) {
        return 0;  // Invalid header (non-Tiny, Pool TLS, or Mid/Large)
    }

    // ✅ Phase E1: C7 now has header, no special case needed!
    // Header magic (0xA0) distinguishes Tiny from Pool TLS (0xB0)

    // ✅ FAST: TLS capacity check (1 cycle)
    uint32_t cap = (uint32_t)TINY_TLS_MAG_CAP;
    if (g_tls_sll_count[class_idx] >= cap) {
        return 0;  // Route to slow path for spill
    }

    // ✅ FAST: Push to TLS freelist (3-5 cycles)
    void* base = (char*)ptr - 1;
    if (!tls_sll_push(class_idx, base, UINT32_MAX)) {
        return 0;  // TLS push failed
    }

    return 1;  // Total: 5-10 cycles ✅
}

Expected Impact: 55-110 cycles → 5-10 cycles (-91% latency, +1100% throughput)


Fix 2: Header-First Classification (Secondary)

File: core/box/front_gate_classifier.h Lines: 166-234 Priority: P1 - HIGH

Before (Current - Registry-First):

static inline ptr_classification_t classify_ptr(void* ptr) {
    if (!ptr) return result;

#ifdef HAKMEM_POOL_TLS_PHASE1
    if (is_pool_tls_reg(ptr)) {
        result.kind = PTR_KIND_POOL_TLS;
        return result;
    }
#endif

    // ❌ SLOW: Registry lookup FIRST (50-100 cycles)
    result = registry_lookup(ptr);
    if (result.kind == PTR_KIND_TINY_HEADER) {
        return result;
    }

    // Header probe only as fallback
    // ...
}

After (Phase 7 style - Header-First):

static inline ptr_classification_t classify_ptr(void* ptr) {
    if (!ptr) return result;

    // ✅ FAST: Try header probe FIRST (2-3 cycles, 95-99% hit rate)
    int class_idx = safe_header_probe(ptr);
    if (class_idx >= 0) {
        // Valid Tiny header found
        result.kind = PTR_KIND_TINY_HEADER;
        result.class_idx = class_idx;
        return result;  // Fast path: 2-3 cycles!
    }

#ifdef HAKMEM_POOL_TLS_PHASE1
    // Check Pool TLS registry (fallback for header probe failure)
    if (is_pool_tls_reg(ptr)) {
        result.kind = PTR_KIND_POOL_TLS;
        return result;
    }
#endif

    // ❌ SLOW: Registry lookup as last resort (rare, <1%)
    result = registry_lookup(ptr);
    if (result.kind != PTR_KIND_UNKNOWN) {
        return result;
    }

    // Check 16-byte AllocHeader (Mid/Large)
    // ...
}

Expected Impact: 50-100 cycles → 2-3 cycles for 95-99% of slow path frees


Fix 3: Remove C7 Special Cases (Cleanup)

Files: Multiple (see Phase E1 commit) Priority: P2 - MEDIUM

Legacy C7 special cases remain in:

  • core/hakmem_tiny_free.inc (lines 32-34, 124, 145, 158, 195, 211, 233, 241, 253, 348, 384, 445)
  • core/hakmem_tiny_alloc.inc (lines 252, 281, 292)
  • core/hakmem_tiny_slow.inc (line 25)

Action: Remove all if (class_idx == 7) conditionals since C7 now has header

Expected Impact: Code simplification, -10% branching overhead


Expected Results After Phase E3

Performance Targets

Size Current Phase E3 Target Improvement
128B 9.2M 59M ops/s +541% 🎯
256B 9.4M 70M ops/s +645% 🎯
512B 8.4M 68M ops/s +710% 🎯
1024B 8.4M 65M ops/s +674% 🎯

Cycle Budget Restoration

Operation Current Phase E3 Improvement
Registry lookup 50-100 0 -100%
Page boundary check 1-2 1-2 0%
Header read 2-3 2-3 0%
TLS freelist push 3-5 3-5 0%
TOTAL 55-110 5-10 -91%

Implementation Plan for Phase E3

Phase E3-1: Remove Registry Lookup from Fast Path

Priority: P0 - CRITICAL Estimated Time: 10 minutes Risk: LOW (revert to Phase 7-1.3 code)

Steps:

  1. Edit core/tiny_free_fast_v2.inc.h (lines 54-63)
  2. Remove SuperSlab registry lookup (revert to Phase 7-1.3)
  3. Keep page boundary check + header read + TLS push
  4. Build: ./build.sh bench_random_mixed_hakmem
  5. Test: ./out/release/bench_random_mixed_hakmem 100000 128 42
  6. Expected: 9M → 30-40M ops/s (+226-335%)

Phase E3-2: Header-First Classification

Priority: P1 - HIGH Estimated Time: 15 minutes Risk: MEDIUM (requires careful header probe safety)

Steps:

  1. Edit core/box/front_gate_classifier.h (lines 166-234)
  2. Move safe_header_probe() before registry_lookup()
  3. Add Pool TLS fallback after header probe
  4. Keep Registry lookup as last resort
  5. Build + Test
  6. Expected: 30-40M → 50-60M ops/s (+25-50% additional)

Phase E3-3: Remove C7 Special Cases

Priority: P2 - MEDIUM Estimated Time: 30 minutes Risk: LOW (code cleanup, no perf impact)

Steps:

  1. Remove if (class_idx == 7) conditionals from:
    • core/hakmem_tiny_free.inc
    • core/hakmem_tiny_alloc.inc
    • core/hakmem_tiny_slow.inc
  2. Unify base pointer calculation (always ptr - 1)
  3. Build + Test
  4. Expected: 50-60M → 59-70M ops/s (+5-10% from reduced branching)

Verification

Benchmark Commands

# Build Phase E3 optimized binary
./build.sh bench_random_mixed_hakmem

# Test all sizes (3 runs each for stability)
for size in 128 256 512 1024; do
    echo "=== Testing ${size}B ==="
    for i in 1 2 3; do
        ./out/release/bench_random_mixed_hakmem 100000 $size 42 2>&1 | tail -1
    done
done

Success Criteria

Phase E3-1 Complete:

  • 128B: ≥30M ops/s (+226% vs current 9.2M)
  • 256B: ≥32M ops/s (+240% vs current 9.4M)
  • 512B: ≥28M ops/s (+233% vs current 8.4M)
  • 1024B: ≥28M ops/s (+233% vs current 8.4M)

Phase E3-2 Complete:

  • 128B: ≥50M ops/s (+443% vs current)
  • 256B: ≥55M ops/s (+485% vs current)
  • 512B: ≥50M ops/s (+495% vs current)
  • 1024B: ≥50M ops/s (+495% vs current)

Phase E3-3 Complete (TARGET):

  • 128B: 59M ops/s (+541% vs current) 🎯
  • 256B: 70M ops/s (+645% vs current) 🎯
  • 512B: 68M ops/s (+710% vs current) 🎯
  • 1024B: 65M ops/s (+674% vs current) 🎯

Lessons Learned

What Went Right

  1. Phase 7 Design: Header-based classification was correct (5-10 cycles)
  2. Phase E1 Fix: Adding headers to C7 eliminated root cause (false positives)
  3. Documentation: CLAUDE.md preserved Phase 7 knowledge for recovery

What Went Wrong

  1. Communication Gap: Phase E1 completed, but Phase 7 fast path was not updated
  2. Defensive Programming: Added expensive C7 check without verifying it was still needed
  3. Performance Testing: Regression not caught immediately (9M vs 59M)
  4. Code Review: Registry lookup added without cycle budget analysis

Process Improvements

  1. Always benchmark after "safety" fixes - 50-100 cycle overhead is not acceptable
  2. Check if problem still exists - Phase E1 already fixed C7, registry lookup was redundant
  3. Document cycle budgets - Fast path must stay <10 cycles
  4. A/B testing - Compare before/after for all "optimization" commits

Conclusion

Root Cause Identified: Commit 5eabb89ad9 added unnecessary 50-100 cycle SuperSlab registry lookup to fast path

Why Unnecessary: Phase E1 had already added headers to C7, making registry lookup redundant

Fix Complexity: LOW - Remove 10 lines, revert to Phase 7-1.3 approach

Expected Recovery: 9M → 59-70M ops/s (+541-674%)

Risk: LOW - Phase 7-1.3 code proven stable at 59-70M ops/s

Recommendation: Proceed immediately with Phase E3-1 (remove registry lookup)


Next Steps: See /docs/PHASE_E3_IMPLEMENTATION_PLAN.md for detailed implementation guide.