Skip to content

Implement Hash Map #162

Closed
Closed

Description

@nockawa

Summary

Implement a page-backed hash map as a new Typhon primitive — O(1) average-case lookup, insert, and delete on exact-match keys. Single generic class HashMap<TKey, TValue> works with any unmanaged key type. Hash function is JIT-specialized by sizeof(TKey).

Design document: claude/design/Foundation/Collections/linear-hash-map.md
Reference algorithm: claude/scratch/linear-hashing-implementation.md

Motivation

Capability B+Tree Hash Map
Exact-match lookup O(log n), 3-4 chunk accesses O(1), 1-2 chunk accesses
Range queries Yes No
Space overhead ~30% (internal nodes) ~2% (directory)

First consumer: Spatial partitioning Layer 1 (PagedHashMap in SpatialRTree.md) — O(1) cell occupancy check.

Key Architecture Decisions

  • Single generic class — HashMap<TKey, TValue> where TKey : unmanaged, IEquatable<TKey>. No subclasses needed.
  • JIT-specialized hash — sizeof(TKey) branching: 4B → Wang/Jenkins (~3-4 cycles), 8B → xxHash32 (~8-10 cycles), other → xxHash32 over raw bytes. Dead branches eliminated by JIT.
  • 256-byte chunks in a dedicated ChunkBasedSegment (one hash map per segment)
  • Lock-free meta reads — (Level, Next, BucketCount) packed into atomic 64-bit word
  • OLC per-bucket — reuses existing OlcLatch, consistent with B+Tree concurrency
  • SoA entry layout — keys and values in separate contiguous arrays
  • Gradual growth — linear hashing: one bucket splits at a time, no stop-the-world resize
  • AllowMultiple — constructor flag for multi-value keys via VSBS buffer indirection

Implementation Phases

  • Phase 1: Core Structures (~800 LOC) — HashMapMeta/HashMapDirectory/HashMapBucketHeader structs, Create/Open factories, segment init
  • Phase 2: Read Path (~400 LOC) — ScanChain, TryGet with OLC read protocol
  • Phase 3: Write Path (~600 LOC) — AppendEntry, RemoveFromChain, Insert/Upsert/Remove with OLC write protocol
  • Phase 4: Split (~500 LOC) — ShouldSplit, ExecuteSplit, EnsureDirectoryCapacity, atomic meta update
  • Phase 5: Recovery & Diagnostics (~300 LOC) — VerifyIntegrity, CreateAndPopulate, GetStats
  • Phase 6: Concurrent Enumeration (~150 LOC) — ConcurrentEnumerator with per-bucket OLC and live bucketCount
  • Phase 7: AllowMultiple Support (~400 LOC) — Multi-value keys via VSBS buffer indirection
  • Phase 8: Tests (~1200 LOC) — 71 tests passing

Enumeration Design (Phase 6)

Mode OLC bucketCount Use Case
GetEnumerator None Snapshotted Single-threaded: rebuild, diagnostics
GetConcurrentEnumerator Per-bucket OLC + collect-then-yield Live Query pipeline, concurrent writers active

AllowMultiple Design (Phase 7)

Constructor flag — stored int value becomes a VSBS buffer ID. Insert appends to buffer, RemoveValue walks buffer chain, TryGetMultiple returns accessor. Split is unaffected (buffer IDs are opaque ints).

API Surface

// Works with any unmanaged key type — no subclasses needed
var intMap  = HashMap<int, int>.Create(segment);
var longMap = HashMap<long, int>.Create(segment);
var multiMap = HashMap<int, int>.Create(segment, allowMultiple: true);

// Core operations
bool TryGet(TKey key, out TValue value, ref ChunkAccessor accessor);
bool Insert(TKey key, TValue value, ref ChunkAccessor accessor, ChangeSet changeSet);
bool Remove(TKey key, out TValue value, ref ChunkAccessor accessor, ChangeSet changeSet);
bool Upsert(TKey key, TValue value, ref ChunkAccessor accessor, ChangeSet changeSet);

// AllowMultiple-only
bool RemoveValue(TKey key, TValue value, ref ChunkAccessor accessor, ChangeSet changeSet);
VariableSizedBufferAccessor<TValue> TryGetMultiple(TKey key, ref ChunkAccessor accessor);

// Enumeration
Enumerator GetEnumerator(ref ChunkAccessor accessor);                    // single-threaded
ConcurrentEnumerator GetConcurrentEnumerator(ref ChunkAccessor accessor); // concurrent-safe

File Structure

File Purpose
src/Typhon.Engine/Data/Index/HashMap.Structs.cs HashMapMeta, HashMapDirectory, OverflowDirIndex, HashMapBucketHeader, HashMapStats
src/Typhon.Engine/Data/Index/HashMapBase.cs Meta management, directory addressing, split lock, diagnostics
src/Typhon.Engine/Data/Index/HashMap.cs HashMap<TKey, TValue>: hash functions, CRUD, split, enumerators, AllowMultiple, factories
test/Typhon.Engine.Tests/Data/HashMapTests.cs 71 tests: CRUD, split, concurrent, enumeration, AllowMultiple

Activity

  1. self-assigned this
    on Mar 12, 2026
  2. moved this to Backlog in Typhon devon Mar 12, 2026
  3. moved this from Backlog to In Progress in Typhon devon Mar 12, 2026
  4. changed the title [-]Implement Linear Hash Map (L32/L64)[/-] [+]Implement Hash Map (L32/L64)[/+] on Mar 14, 2026
  5. changed the title [-]Implement Hash Map (L32/L64)[/-] [+]Implement Hash Map[/+] on Mar 14, 2026
  6. moved this from In Progress to Done in Typhon devon Mar 14, 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