Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Learned Index Lab Documentation

Welcome to the Learned Index Lab documentation portal — a pure Rust implementation and comparative benchmark suite for Piecewise Geometric Model (PGM) learned index structures.

Core Structures

  • PgmIndex: Single-pass optimal streaming Piecewise Linear Approximation (PLA) with strict $\epsilon$ error bounds and bounded local search.
  • MultilevelPgmIndex: Hierarchical recursive PGM index reducing lookup complexity to $O(h \cdot \log \epsilon)$ for massive datasets.
  • EytzingerSearch: Cache-conscious breadth-first binary search layout without approximation error.

Documentation Map

  • Architecture & Production: Internal Rust memory layout, cache-line alignment, and production deployment patterns.
  • Theoretical Foundations: Mathematical foundations of CDF approximation, streaming PLA, error corridors, and $\epsilon$ tuning.
  • Integration Cookbook: Practical production recipes for point/range queries, concurrent reads, LSM SSTables, and zone maps.
  • Statistical Benchmarks: Reproducible latency, memory, and build-time comparisons across synthetic and SOSD real-world workloads.
  • Historical Archives: Frozen snapshots of previous major release READMEs.


References

Technical Articles & Deep Dives

Seminal Research Papers

  • Kraska et al. (2018): “The Case for Learned Index Structures” (ACM SIGMOD 2018) – PDF (arXiv) · arXiv:1712.01208. Seminal paper proving that sorted indexes can be modeled as cumulative distribution function (CDF) regressions.
  • Ferragina & Vinciguerra (2020): “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds” (PVLDB 2020) – PDF (PVLDB) · PDF (arXiv) · arXiv:1910.06169. Establishes optimal piecewise linear approximation (PLA) under bounded error corridors $\epsilon$.
  • Khuong & Morin (2017): “Array Layouts for Comparison-Based Searching” (ACM JEA 2017) – PDF (arXiv) · arXiv:1509.05053. Formalizes the cache-conscious Eytzinger array layout and branchless level-order search.

Reference Codebases & Implementations

Industry Storage Engines & Analytical Systems

Code Architecture & Memory Layout Guide

This document provides an architectural walkthrough of the learned_index_lab Rust implementation, detailing internal data structures, CPU cache alignment, arithmetic search mechanics, and microarchitectural engineering trade-offs.


1. Core Data Structures & Memory Alignment

Segment Layout & 64-Byte Cache Line Density

In learned_index_lab, an index segment is defined as:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Segment {
    pub key: u64,       // 8 bytes (offset 0)
    pub slope: f64,     // 8 bytes (offset 8)
    pub intercept: f64, // 8 bytes (offset 16)
}
}
  • Size of Segment: 24 bytes of active payload.
  • Alignment: 8-byte aligned (align_of::<Segment>() == 8).
  • Cache packing: In standard x86_64 / ARM64 architectures with 64-byte L1/L2 cache lines:
    • Two contiguous Segment structs occupy 48 bytes ($2 \times 24\text{ B}$), leaving 16 bytes for the start of a third segment.
    • Over sequential traversals, fetching a single 64-byte cache line brings 2.66 segments directly into L1 cache without pointer chasing.
Cache Line SliceStruct PayloadField BreakdownByte Range
Segment 024 byteskey (8B) + slope (8B) + intercept (8B)Bytes 0–23
Segment 124 byteskey (8B) + slope (8B) + intercept (8B)Bytes 24–47
Segment 2 (Partial)16 byteskey (8B) + slope (8B)Bytes 48–63

Contiguous Data Buffer Locality

While std::collections::BTreeMap organizes data in heap-allocated multi-key nodes (holding up to 11 elements per node in Rust’s standard library to exploit intra-node cache locality), navigating deeper levels still requires pointer dereferences between heap allocations.

In contrast, PgmIndex and MultilevelPgmIndex decouple the index from the data:

  1. segments: Vec<Segment>: Compact array containing only linear segment parameters.
  2. data: Vec<u64>: Continuous sorted raw data buffer.
flowchart LR
    subgraph Host["PgmIndex Host Struct (32 Bytes)"]
        Eps["epsilon: usize"]
        SegPtr["segments: Vec~Segment~"]
        DataPtr["data: Vec~u64~"]
    end

    subgraph IndexArray["Index Array (Heap Allocated)"]
        Segs["[ Seg 0 | Seg 1 | Seg 2 | ... | Seg S-1 ]"]
    end

    subgraph DataArray["Primary Data Array (Contiguous RAM)"]
        Keys["[ K0 | K1 | K2 | K3 | ... | Kn-1 ]"]
    end

    SegPtr --> IndexArray
    DataPtr --> DataArray

2. Search Mechanics: Two-Tier Arithmetic Lookup

Looking up a key $k$ in PgmIndex follows a two-stage process:

flowchart TD
    Key["Target Key: k"] --> Step1["1. Global Segment Selection: binary_search_by_key"]
    Step1 --> Seg["Matched Segment: s (key, slope, intercept)"]
    Seg --> Step2["2. In-Register ALU Prediction: approx = round(intercept + slope * (k - key))"]
    Step2 --> Window["Corridor Search Window: [approx - ε, approx + ε]"]
    Window --> Step3["3. Local Slice Verification: data[low..=high].binary_search(k)"]
    Step3 --> Result["Exact Index in data (or None)"]

Step 1: Global Segment Resolution ($O(\log S)$)

  • binary_search_by_key(&target, |s| s.key) searches over $S$ segments.
  • Distribution Sensitivity:
    • For smooth or moderately clustered distributions, $S \ll N$ (e.g. 93 segments / $3.1\text{ KB}$ on sequential data, or 1,416 segments / $48.1\text{ KB}$ on uniform random), allowing the entire segment table to fit comfortably inside CPU L1/L2 cache.
    • On highly irregular or heavy-tailed Pareto distributions (e.g. SOSD Books), the number of segments can reach 55,000+ ($1.50\text{ MB}$), exceeding L2 cache capacity and requiring multiple cache line fetches during the segment binary search.

Step 2: Arithmetic CDF Projection (ALU Operation)

  • Once the responsible segment $s$ is loaded: $$\Delta x = k - s.\text{key}$$ $$\text{pos}_{\text{approx}} = \text{round}(s.\text{intercept} + s.\text{slope} \times \Delta x)$$
  • This computation requires 1 integer subtraction, 1 floating-point multiply-add (FMA), and 1 round-to-integer conversion. Modern x86_64 CPUs execute this in $\sim 4\text{ to }6$ CPU cycles entirely inside scalar registers.

Step 3: Bounded Local Verification ($O(\log \epsilon)$)

  • The mathematical guarantee of streaming PLA ensures: $$\text{pos}{\text{actual}} \in [\text{pos}{\text{approx}} - \epsilon, \text{pos}_{\text{approx}} + \epsilon]$$
  • For $\epsilon = 16$, the verification window spans at most 33 elements ($2\epsilon + 1$).
  • Contiguous memory layout guarantees that these 33 elements reside across at most 4 cache lines ($264\text{ bytes}$), minimizing TLB misses and DRAM page activation latency.

3. Hierarchical Multilevel Indexing (MultilevelPgmIndex)

When $N > 10^7$ or under large-scale workloads where segment arrays exceed L3 cache capacities, MultilevelPgmIndex recursively constructs upper PGM layers over segment start keys:

flowchart TD
    subgraph Root["Level h-1 (Root PGM Layer)"]
        R["Top-Level Segments (<= 2 * ε_rec)"]
    end

    subgraph Inter["Level 1 (Intermediate PGM Layer)"]
        I["Indexes Level 0 Segment Anchors"]
    end

    subgraph Base["Level 0 (Base PGM Layer)"]
        B["Indexes Raw Data Keys with ε0"]
    end

    subgraph Data["Primary Storage Buffer"]
        D["Contiguous Sorted Vec~u64~"]
    end

    R -->|"Top-Down Arithmetic Descent"| I
    I -->|"Arithmetic CDF Projection"| B
    B -->|"Local Window: [pos - ε, pos + ε]"| D
  • Lookup Complexity: $O(h \cdot \log \epsilon_{\text{rec}} + \log \epsilon_0)$, where $h \approx \log_{2\epsilon} S$.
  • Trade-off at Scale: For $N = 10^6$, single-level PgmIndex is faster because the flat segment array fits in L2/L3 cache, avoiding the extra arithmetic and memory hops of multi-level descent. The hierarchical design is specifically intended for datasets exceeding tens of millions of keys.

4. Engineering Trade-offs: Linear Segments vs. Alternative Models

Design DimensionStreaming Linear PLA (This Lab)High-Order Polynomials / SplinesDeep Neural Networks (MLP / RBF)
Error GuaranteesDeterministic ± ε worst-caseHard to bound strictlyNo worst-case bounds
Build Complexity$O(N)$ single streaming pass$O(N)$ to $O(N^2)$ matrix solve$O(\text{epochs} \cdot N)$ gradient descent
ALU Execution1 FMA instruction ($\sim 4$ cycles)Multiple multiplies + divisionMatrix GEMM / activation vector calls
Hardware FitStandard scalar registersSIMD / AVX-512 register pressureGPU / NPU accelerator required
Index Size24 bytes per segment48–96 bytes per spline nodeMegabytes of weight matrices
Branch Predictor1 branchless local scanMultiple branch checksModel evaluation branching

Rationale for Linear PLA

  1. Memory Wall vs. ALU Overhead: DRAM latency ($\sim 50\text{–}80\text{ ns}$) dominates search performance. Higher-order curves or neural networks do not reduce memory reads compared to a narrow $\epsilon = 16$ window, but dramatically increase register pressure and instruction latencies.
  2. Deterministic Guarantees: A production database index must guarantee bounds. Streaming PLA strictly enforces that the key is within the predicted corridor without falling back to expensive unconstrained scans.
  3. Distribution Caveat: While linear PLA excels when CDFs are piecewise regular, it remains vulnerable to distributions with extreme step-function variance (such as heavy-tailed book ISBNs), where classical tree structures like BTreeMap or branchless structures like Eytzinger provide superior lookups.

Production Architecture & Real-World Applications

This document details practical integration patterns, performance trade-offs, and target use cases for learned index structures.


Decision Matrix: Selecting the Right Index Structure

Workload CharacteristicRecommended StructureRationale
Frequent in-place mutations / OLTPBTreeMap / B+TreeBetter suited for dynamic concurrent writes, page splits, and transaction management.
Immutable / Read-heavy sorted datasets (< 10M keys)PgmIndexIdeal for SSTables in LSM engines, Parquet columnar row groups, and static lookup tables.
Massive datasets (> 10M keys) where segments overflow L3MultilevelPgmIndexRecursive PGM tree guarantees O(h * log eps) lookup without binary searching large segment arrays.
Irregular distributions / Extreme Pareto skew / Micro-burstsBTreeMap / EytzingerSearchLocalized tree node caching and branchless binary search outperform linear approximation when segment counts explode.
Memory-constrained environmentsPgmIndex / MultilevelPgmIndexReduces index metadata footprint by up to 14,700x (~5.7x total resident RAM) compared to pointer-based trees.
Batch ingestion / SSTable compactionmerge_sorted_batchMerges sorted batches in O(N + M) and rebuilds streaming PLA segments at > 10M keys/sec.
Cache-friendly binary searchEytzingerSearchReplaces standard slice::binary_search with branchless level-order traversal when duplicate data buffer is tolerable.
Zero extra memory allowedslice::binary_searchIn-situ search over pre-sorted data with 0 KB metadata overhead.

Production Applications

1. Columnar OLAP Engines (ClickHouse, DuckDB, Apache Parquet)

Analytical columnar engines process sorted row groups containing millions of records. Replacing conventional coarse zone maps with PGM linear segments enables sub-microsecond tuple filtering without disk or memory amplification.

2. LSM-Tree Storage Engines (RocksDB, ScyllaDB, LevelDB)

SSTables written to NVMe storage are strictly immutable. Replacing sparse block index tables with compact PGM models allows billions of key offsets to reside resident in CPU cache or RAM, ensuring exactly 1 physical I/O per query.

3. OS File System Cataloging & Forensic Indexing

Fast file catalogers (e.g. NTFS Master File Table / USN journal indexers) can index tens of millions of records in only a few kilobytes of RAM.

4. High-Throughput Network Routing (Forwarding Information Base)

At line rates exceeding 100 Gbps, IP forwarding tables must guarantee bounded lookup latency without saturating CPU cache lines.

Theoretical Foundations Index

This directory provides concise extracts of each foundational theory behind learned_index_lab, paired with direct links to the seminal research publications and full PDF papers:

Theory / TopicSummary ExtractSeminal Research & Full Paper
CDF Approximation in Learned IndexesModels sorted keys as Empirical CDF regressions ($Pos(k) \approx N \times CDF(k)$)CDF Theory Extract · Kraska et al. (SIGMOD 2018) · PDF
Optimal Streaming PLASingle-pass $O(N)$ streaming slope corridor $[s_{\min}, s_{\max}]$ under bounded tolerance ± εStreaming PLA Extract · Ferragina & Vinciguerra (PVLDB 2020) · PDF
Duplicate Keys & PlateausDeterministic error bounding and segment splitting under duplicate runs ($dx = 0$)Duplicates Guide · Ferragina & Vinciguerra (PVLDB 2020)
Epsilon Tuning & Cache HierarchyMicroarchitectural hardware cache-line alignment, Pareto curves, and sizing guidelinesEpsilon Tuning Guide · Ferragina & Vinciguerra (PVLDB 2020)
Hierarchical Multilevel PGMRecursive segment indexing ($O(\log N) \to O(h \cdot \log \epsilon)$) for large-scale datasetsMultilevel Extract · Ferragina & Vinciguerra (PVLDB 2020) · PDF
Batch Merge & Streaming RebuildTwo-way sorted merge and $O(N + M)$ streaming PLA rebuild for SSTable workloadsBatch Merge Extract · Ferragina & Vinciguerra (PVLDB 2020) · PDF
Eytzinger (Breadth-First) LayoutComplete 1-based binary tree array layout with branchless cmov traversalEytzinger Extract · Khuong & Morin (ACM JEA 2017) · PDF
Bounded Local SearchCombines global segment binary search ($O(\log S)$) with local corridor scans ($O(\log \epsilon)$)Bounded Search Extract · Ferragina & Vinciguerra (2020) · PDF
Learned Index Landscape & SOTAComparative matrix of PGM, RMI, ALEX, RadixSpline, FITing-Tree, and B+TreeLandscape Analysis · Kraska et al. (2018) · Ferragina & Vinciguerra (2020)

Theory: CDF Approximation in Learned Indexes

Summary Extract

Traditional database indexes treat search keys as opaque values and navigate through comparison-based pointer hierarchies ($B\text{-Tree}$, $B^+\text{-Tree}$, LSM block indexes), incurring $O(\log N)$ sequential pointer dereferences across memory.

Learned Index Structures reframe indexing as a regression problem: Given a sorted sequence of keys $K = (k_0, k_1, \dots, k_{N-1})$, the ordinal rank and position of any key $k$ is proportional to the Empirical Cumulative Distribution Function (CDF):

$$\text{Pos}(k) \approx N \times \text{CDF}(k)$$

By approximating the CDF with functional models (such as piecewise linear segments), the search algorithm replaces pointer chasing with an in-register arithmetic calculation that narrows the target key’s location down to a deterministic corridor $[\text{Pos}{\text{approx}} - \epsilon, \text{Pos}{\text{approx}} + \epsilon]$. Final retrieval is then performed via a fast local verification scan within the contiguous data buffer.


Architectural Distinctions & Trade-Offs

  • Not Direct Addressing: Unlike hash tables or perfect minimal hash functions, learned CDF approximations do not resolve keys to absolute memory addresses in a single step. They act as bounded spatial filters that drastically reduce the search space for a subsequent contiguous memory lookup.
  • Continuous vs. Discontinuous CDFs:
    • For smooth, monotonically continuous distributions (e.g. sensor timestamps, sequential logs, uniform random sequences), linear CDF approximation compresses millions of keys into a few dozen or hundred parameters.
    • For discontinuous or heavy-tailed distributions with steep plateaus and massive gaps (e.g. power-law ISBNs, repeated transaction IDs), empirical CDF approximation requires high segment densities, diminishing the speed advantage over classical tree structures.

Full Research Papers & Resources

Theory: Optimal Streaming Piecewise Linear Approximation (PLA)

Summary Extract

The Piecewise Geometric Model (PGM-Index) represents sorted keys using a minimal set of linear segments $y = ax + b$, guaranteeing that the predicted position of any key $k$ falls within a bounded error corridor $[y - \epsilon, y + \epsilon]$.

The index builder executes in a single sequential pass ($O(N)$ time, $O(1)$ auxiliary working space):

  1. Slope Corridor: Starting from origin point $(x_0, y_0)$, each subsequent point $(x_i, y_i)$ (where $x_i$ is key value and $y_i = i$ is the array rank) narrows the feasible slope range $[s_{\min}, s_{\max}]$: $$s_{\min} = \max_{j} \left[ \frac{(y_j - \epsilon) - y_0}{x_j - x_0} \right], \quad s_{\max} = \min_{j} \left[ \frac{(y_j + \epsilon) - y_0}{x_j - x_0} \right]$$

  2. Segment Finalization: As long as $s_{\min} \le s_{\max}$, the corridor remains feasible and point $(x_i, y_i)$ can be accommodated within the current segment. The moment $s_{\min} > s_{\max}$, the corridor collapses: the segment is finalized with median slope $s = \frac{s_{\min} + s_{\max}}{2}$, and a new segment begins anchored at $(x_i, y_i)$.


Edge Cases & Practical Engineering Considerations

  1. Duplicate Keys ($dx = 0$): When identical keys appear sequentially ($x_i = x_0$), the denominator $x_i - x_0$ is zero, causing infinite or undefined slopes. If the run of duplicates exceeds the error tolerance $\epsilon$ ($|y_i - y_0| > \epsilon$), the corridor cannot encompass the vertical step. The builder must finalize the active segment and start a new one to prevent error corridor violations.

  2. Numerical Precision (IEEE-754 f64): Slopes and intercepts are stored as 64-bit floating-point numbers (f64). When key coordinates span large integer values ($u64$ near $2^{63}$), finite mantissa precision (53 bits) can introduce minor rounding errors during multiplication. In production implementations, error corridors are designed with conservative bounds to preserve the invariant under floating-point arithmetic.

  3. Optimality Proof: Ferragina & Vinciguerra (2020) proved that this greedy streaming corridor algorithm produces the provably optimal (minimal) number of piecewise linear segments for a given $\epsilon$ in $O(N)$ time, without requiring multi-pass dynamic programming.


Full Research Papers & Resources

Theory: Bounded Local Search & Error Corridors

Summary Extract

In a Piecewise Geometric Model (PGM-Index), lookup combines global mathematical interpolation with strictly bounded local search in a 3-step pipeline:

  1. Global Segment Resolution: Given a target key $k$, the algorithm locates the responsible segment whose starting key satisfies $s.\text{key} \le k$. In single-level PGM, this is performed via binary search over the $S$ segment headers ($O(\log S)$). In multilevel PGM, it is resolved via recursive arithmetic descent ($O(h \cdot \log \epsilon_{\text{rec}})$).

  2. ALU Arithmetic Prediction: Once the responsible segment $s = (k_0, \text{slope}, \text{intercept})$ is identified, the predicted ordinal offset is computed via scalar registers: $$\text{Pos}_{\text{approx}} = \text{round}(\text{intercept} + \text{slope} \times (k - k_0))$$

  3. Bounded Local Verification: The optimal streaming PLA construction guarantees that if $k$ exists in the dataset, its true index resides strictly within: $$[\max(0, \text{Pos}{\text{approx}} - \epsilon), \min(N - 1, \text{Pos}{\text{approx}} + \epsilon)]$$ A local search over this bounded window ($\le 2\epsilon + 1$ elements) takes $O(\log \epsilon)$ time and accesses at most 1–4 contiguous 64-byte cache lines.


Microarchitectural Analysis of the Local Window

  • Cache Footprint: For $\epsilon = 16$, the maximum search span is $2\epsilon + 1 = 33$ elements ($33 \times 8 = 264\text{ bytes}$). Because this slice is contiguous, fetching the first element causes the hardware prefetcher to pull the remaining 3 cache lines directly into L1 cache.
  • Local Search Strategies:
    • Binary Search (slice::binary_search): Minimizes comparison count ($\approx \lceil \log_2(33) \rceil = 6$ comparisons), but each step incurs a conditional branch that may trigger CPU branch mispredictions.
    • Linear / SIMD Scan: For very small $\epsilon$ ($\le 16$), unrolled linear comparisons or vector SIMD instructions (e.g. AVX2 / ARM NEON) can evaluate multiple keys simultaneously without branch misprediction stalls, representing an optimization path for high-throughput engines.

Guarantees & Trade-offs

  • Complexity: $O(\log S + \log \epsilon)$ for single-level PGM; $O(h \log \epsilon_{\text{rec}} + \log \epsilon_0)$ for multilevel PGM.
  • Exactness: 100% exact (zero false positives, zero false negatives).
  • Sensitivity to Segment Count: If $S$ is small (smooth CDF), Step 1 takes negligible time. If $S$ is large (severe skew or step functions), Step 1 dominates the entire query latency, eliminating the speedup over classical search trees.

Full Research Papers & Resources

Hierarchical Multilevel PGM-Index

Theoretical Foundation

In a single-level PgmIndex, locating the responsible segment for a query key requires a binary search across the $S$ segment headers, taking $O(\log S)$ comparisons. While $S \ll N$ on smooth distributions, the segment array can grow large when dataset size exceeds tens of millions ($N > 10^7$).

The Hierarchical Multilevel PGM-Index (Ferragina & Vinciguerra, PVLDB 2020) eliminates flat binary search across segments by recursively constructing PGM index layers over the start keys of lower levels:

  1. Level 0 (Base Layer): Directly indexes the $N$ raw sorted data keys using base error tolerance ε₀, producing $S_0$ linear segments.
  2. Recursive Upper Levels: For level $i \ge 1$, an upper PGM index is constructed over the $S_{i-1}$ segment start keys of level $i-1$ using recursive tolerance ε_rec.
  3. Root Level: Construction terminates when the top level contains $\le 2 \cdot \varepsilon_{\text{rec}}$ segments, which fit in a single CPU cache line.

Complexity & Deterministic Guarantees

  • Tree Height: $h \approx \lceil \log_{2\varepsilon_{\text{rec}}} S_0 \rceil$.
  • Query Time: $O(h \cdot \log \varepsilon_{\text{rec}} + \log \varepsilon_0)$, replacing global binary search over segments with top-down arithmetic projections.
  • Deterministic Bounds: Every descent step stays within [pos - ε_rec, pos + ε_rec], ensuring intermediate lookups remain tightly bounded.

Practical Scale Considerations: When Multilevel Wins vs. Lags

Empirical benchmarks highlight critical trade-offs between single-level and multilevel PGM structures:

Dataset ScaleSingle-Level PgmIndexMultilevelPgmIndexArchitectural Recommendation
Small / Moderate (N ≤ 10⁶)Faster (~123 ns avg)Slower (~165 ns avg)Single-Level: S₀ fits in L2/L3 cache (< 330 KB). Flat binary search is faster than multi-hop arithmetic descent.
Massive (N > 10⁷)Slower (segment cache thrashing)Faster (predictable cache residency)Multilevel: S₀ overflows L3 cache (> 10 MB); hierarchical descent prevents large stride memory jumps.
Severe Pareto Skew (SOSD Books)Slower (100 ns)Slower (153 ns)BTreeMap (35 ns): Tree node caching outperforms learned arithmetic when segments explode.

Academic Reference

  • Paolo Ferragina & Giorgio Vinciguerra (2020): “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”, Proceedings of the VLDB Endowment (PVLDB), Vol. 13, No. 8, pp. 1162–1175.
  • DOI: 10.14778/3389133.3389135 · PDF on arXiv

Epsilon (ε) Tuning & Hardware Cache Hierarchy Guide

Overview

In the Piecewise Geometric Model (PGM-Index), the parameter ε (epsilon) is the single most critical configuration knob. It defines the maximum absolute error bound guaranteed by the streaming Piecewise Linear Approximation (PLA) algorithm:

$$|\text{Pos}{\text{actual}}(k) - \text{Pos}{\text{predicted}}(k)| \le \varepsilon$$

Understanding how ε interacts with CPU cache line sizes (64 bytes), L1/L2 data cache capacities, and algorithmic search complexities is essential for achieving optimal lookup throughput and memory efficiency.


1. Microarchitectural Alignment: Cache Lines & Window Spans

During the third phase of a PGM lookup, the algorithm performs a local verification scan within the bounded interval:

$$[\text{Pos}{\text{approx}} - \varepsilon, \text{Pos}{\text{approx}} + \varepsilon]$$

This window contains at most 2ε + 1 elements. For 64-bit unsigned integer keys (u64, 8 bytes per key), contiguous memory layout directly determines how many 64-byte CPU cache lines are touched:

εWindow Elements (2ε + 1)Window Size (Bytes)64-Byte Cache Lines TouchedCache Residency Profile
49 keys72 B~1.1 lines100% L1-resident, but segments S explode
817 keys136 B~2.1 linesFits across 2–3 L1 cache lines
1633 keys264 B~4.1 linesSweet spot for uniform/skewed data (100% L1)
3265 keys520 B~8.1 linesSweet spot for sequential/dense data (L1-resident)
64129 keys1,032 B~16.1 linesExceeds 1 KB; prefetcher saturation risk
128257 keys2,056 B~32.1 linesLocal search starts incurring L2 cache stalls
256513 keys4,104 B~64.1 linesLocal binary search branch mispredictions dominate

Why ε ∈ [16, 32] is the Empirical Sweet Spot

  1. L1 Cache Line Density: A 33-element window (264 bytes) spans roughly 4 contiguous cache lines. Modern CPU spatial prefetchers fetch adjacent cache lines upon the first memory request.
  2. Branch Misprediction Minimization: A local binary search over 33 elements requires at most ⌈log₂(33)⌉ = 6 branch comparisons, keeping pipeline flush penalties low.
  3. Metadata Control: At ε = 16 or 32, the number of generated segments S is compressed by orders of magnitude relative to N, allowing the entire segment table to fit into L1/L2 cache lines.

2. The Fundamental Pareto Trade-Off: Segment Count (S) vs. Window Size (ε)

The total lookup latency of a single-level PGM-Index is governed by the sum of two distinct search phases:

$$T_{\text{lookup}} = \underbrace{T_{\text{segment}}(S)}{O(\log S)} + \underbrace{T{\text{ALU}}}{O(1)} + \underbrace{T{\text{local}}(\varepsilon)}_{O(\log \varepsilon)}$$

  • Increasing ε:
    • Widens the slope corridor [s_min, s_max], allowing each segment to cover a wider span of keys.
    • Decreases total segment count S ∝ 1/ε.
    • Reduces index metadata memory footprint.
    • Speeds up Step 1 (fewer segments to search).
    • Downside: Widens the local verification window, increasing Step 3 latency.
  • Decreasing ε:
    • Tightens the prediction corridor, narrowing the local search window (2ε + 1).
    • Speeds up Step 3 (fewer elements to scan).
    • Downside: Causes segment fragmentation (S increases). If S grows from hundreds to tens of thousands (as seen in heavy Pareto distributions), the global binary search over segments spills out of L2 cache into L3/DRAM, degrading overall performance.

Trade-off Regimes Across the ε Spectrum

RegimeSegment Count (S)Step 1 (Segment Lookup)Step 3 (Local Corridor Scan)Overall Latency Result
Undersized (ε ≤ 4)Explodes (S ≫ 10⁴, spills out of L2/L3)Bottleneck: slow binary search over large segment tableFast (< 9 keys, 1 cache line)High: segment lookup dominates
Sweet Spot (ε = 16–32)Compact (S ≈ 100–1,500, L1/L2-resident)Fast (O(log S) in cache)Fast (33–65 keys, 4–8 L1 lines)Optimal: balanced Step 1 and Step 3
Oversized (ε ≥ 128)Minimal (S < 50, < 2 KB)Instant (O(log S) ≤ 5 checks)Bottleneck: wide scan (> 257 keys, > 32 cache lines)High: degrades toward raw slice search

3. Tuning ε in Hierarchical Indexing (MultilevelPgmIndex)

In MultilevelPgmIndex, the base layer and upper recursive layers have distinct memory profiles and can be parameterized with independent epsilons:

#![allow(unused)]
fn main() {
let ml_pgm = MultilevelPgmIndex::build_with_epsilons(
    data, 
    epsilon_base,       // eps_0 (e.g. 16 or 32)
    epsilon_recursive   // eps_rec (e.g. 8 or 16)
);
}

Decoupling ε₀ and ε_rec

  1. Base Epsilon (ε₀):
    • Operates on the raw data buffer (N keys).
    • Controls the trade-off between total raw segment count S₀ and the final local data slice scan.
  2. Recursive Epsilon (ε_rec):
    • Operates on segment start keys (S₀, S₁, …).
    • Determines the fan-out and tree height h ≈ ⌈log_{2ε_rec} S₀⌉.
    • Because upper level keys are purely segment boundaries already resident in CPU cache, keeping ε_rec = 16 guarantees that each descent step accesses at most 4 cache lines while reducing the number of segments by a factor of ≈ 2ε_rec = 32× per level.

4. Practical Workload Tuning Matrix

Workload ProfileRecommended εRationale
Dense Sequential / Monotonic Logsε = 32 or 64High linearity allows extreme compression (e.g. 93 segments for 1M keys). Local scan over 65 elements remains 100% L1-resident.
Uniform Sparse Random Keysε = 16Balances moderate slope variance against local verification speed, yielding ~1,400 segments (48 KB).
Clustered / Skewed (Lognormal, Geospatial OSM)ε = 16Restricts local verification latency in dense cluster pockets while preventing excessive segment fragmentation in sparse tails.
Micro-Bursts & Duplicate Heavy (Wiki-TS)ε = 32Prevents identical key plateaus from constantly triggering corridor resets and segment splits.
Extreme Pareto Skew (Book ISBNs)Classical B-TreeNon-linear step functions produce excessive segments (~55,000 segments / 1.5 MB). BTreeMap is 2.87x faster than PGM under this regime.

5. Academic Foundations & Theoretical Proofs

  • Optimal Segment Cardinality: Ferragina & Vinciguerra (PVLDB 2020) proved that greedy streaming PLA produces the minimum possible number of linear segments covering N sorted points for any fixed ε in O(N) time and O(1) auxiliary space.
  • Worst-Case Lookup Bounds: Lookup in a single-level PGM-Index is strictly bounded by O(log S + log ε), with zero heuristic fallbacks or unbounded scan penalties.

References

  • Ferragina, P., & Vinciguerra, G. (2020). “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”, PVLDB, 13(8): 1162–1175.
  • Marcus, R., et al. (2019). “Benchmarking Learned Indexes”, Proceedings of the VLDB Endowment / AIDB 2019.

Duplicate Keys & Plateaus in Streaming PLA

Overview

In sorted dataset indexing, duplicate keys (or runs of identical values) represent a classic challenge for continuous regression models. In a learned index, keys $x_i$ are mapped to ordinal positions $y_i = i$. When two or more consecutive keys are identical ($x_i = x_{i-1}$), the empirical Cumulative Distribution Function (CDF) exhibits a vertical jump or step discontinuity:

$$\Delta x = x_i - x_{i-1} = 0, \quad \Delta y = y_i - y_{i-1} \ge 1$$

Mathematically, the instantaneous slope between these points is undefined or infinite ($\frac{\Delta y}{0} \to \infty$). This document details how learned_index_lab deterministically bounds duplicate keys in single-pass streaming PLA without producing NaN or Inf floating-point errors, backed by formal error corridor proofs.


1. The Geometry of Duplicates under Bounded Corridors (± ε)

The Piecewise Geometric Model (PGM) does not fit an exact interpolation curve; it constructs a vertical error corridor [y - ε, y + ε] of radius ε around linear segments (Ferragina & Vinciguerra, 2020, Section 3).

Under this formal definition, a segment covering range [j, k] is valid if and only if:

$$\forall i \in [j, k], \quad |f(x_i) - y_i| \le \varepsilon$$

When encountering duplicate keys where x_j = x_i (Δx = 0), any linear function $f(x) = s \cdot (x - x_j) + y_j$ simplifies to $f(x_i) = y_j$. The error condition becomes:

$$|y_i - y_j| \le \varepsilon$$

Because of this vertical corridor tolerance, duplicate keys are processed deterministically according to their run length:

  1. Short Duplicate Runs (run length <= ε):
    • If a duplicate run has length $L \le \varepsilon$, all points $(x_i, y_i)$ reside within vertical distance ε of the segment origin $(x_0, y_0)$.
    • The corridor absorbs the duplicates without splitting the segment or modifying the slope bounds $(s_{\min}, s_{\max})$.
  2. Long Duplicate Runs / Plateaus (run length > ε):
    • When identical keys exceed ε elements ($|y_i - y_0| > \varepsilon$), no single linear model can cover both $(x_0, y_0)$ and $(x_i, y_i)$ within tolerance ± ε.
    • As proven in Ferragina & Vinciguerra (2020, Lemma 1), the active segment must be finalized, and a new segment is initialized anchored at the current duplicate key $(x_i, y_i)$.

Summary of Duplicate Handling States

ScenarioConditionSegment ActionSlope Corridor Impact
Short Duplicatedx == 0 and abs(y_i - y_0) <= εAbsorbed into active segmentPreserved (no change)
Plateau Overflowdx == 0 and abs(y_i - y_0) > εFinalize segment; anchor new segmentReset to [-∞, +∞]

2. Implementation in src/pgm.rs

In learned_index_lab, streaming PLA handles duplicates during the single sequential scan:

#![allow(unused)]
fn main() {
for (i, &xi) in data.iter().enumerate().skip(1) {
    let yi = i as f64;
    let dx = (xi - x0) as f64;

    if dx == 0.0 {
        // Duplicate key: delta x is zero.
        if (yi - y0).abs() > eps {
            // Plateau height exceeds epsilon: finalize segment.
            let slope = compute_slope(s_min, s_max);
            segments.push(Segment {
                key: x0,
                slope,
                intercept: y0,
            });
            x0 = xi;
            y0 = yi;
            s_min = 0.0;
            s_max = f64::INFINITY;
        }
        continue;
    }
    
    // Normal slope corridor calculation for distinct keys...
}
}

Invariants Maintained:

  • Division by Zero Prevention: The condition dx == 0.0 prevents division by zero in slope calculations ((yi ± eps) - y0) / dx.
  • Bounded Vertical Error: No segment ever spans a vertical range greater than ε from its baseline origin for duplicate keys.
  • Non-decreasing Segments: Successive segments have non-decreasing start keys (s[k].key <= s[k+1].key).

3. Query Mechanics with Duplicate Keys

Point Query (find)

When a key appears multiple times across consecutive segments:

  1. segments.binary_search_by_key(&target, |s| s.key) returns an index matching target.
  2. Because each segment covering the duplicate plateau was constructed with dx = 0, its prediction evaluates to approx = round(intercept).
  3. The local search window [approx - eps, approx + eps] is guaranteed to intersect the duplicate run in self.data.
  4. slice.binary_search(&target) returns a valid match in $O(\log \varepsilon)$ time.

Predecessor and Range Queries (lower_bound & range)

  • lower_bound(target) returns the first element >= target. If multiple duplicates exist, lower_bound locates the earliest instance by checking boundary conditions at the edge of the bounded corridor.
  • range(start..=end) locates the start bound with lower_bound(start) and the end bound with lower_bound(end), returning the entire contiguous duplicate sub-slice directly.

4. Architectural & Performance Impact

  • Segment Table Inflation: On datasets with high duplicate cardinality (e.g. SOSD Wikipedia Timestamps wiki_ts, where millions of revisions share identical timestamps), the model must generate a new segment every ≈ ε duplicate items.
  • When BTreeMap Wins: Because duplicate keys force frequent segment splitting, workloads dominated by massive duplicate runs experience reduced PGM compression ratios ($S$ grows). In such workloads, BTreeMap handles duplicate keys natively within tree nodes without segment boundary thrashing.

Academic Reference

  • Ferragina, P., & Vinciguerra, G. (2020): “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”, PVLDB 13(8): 1162–1175.
    • Section 3: The Optimal Piecewise Linear Approximation.
    • Lemma 1 & Section 3.2: Bounding Space and Time under Discontinuous and Repeated Keys.

Batch Merge & Streaming PLA Rebuild

Overview

A fundamental trade-off exists between dynamic in-place mutation structures (like std::collections::BTreeMap or B+Trees) and immutable learned structures relying on batch rebuilds.

  • Dynamic Trees (BTreeMap): Support granular, low-latency point insertions ($O(\log N)$ per key). Keys are inserted into multi-key nodes without rewriting the rest of the dataset.
  • Learned Structures (PgmIndex): Are strictly immutable once built. Updates require a two-way merge of the existing sorted data with the new batch, followed by a full single-pass streaming PLA reconstruction ($O(N + M)$).

This design mirrors the immutable SSTable compaction architecture used in LSM-tree storage engines (e.g. RocksDB, LevelDB, ScyllaDB), where writes are buffered in memory and flushed periodically in large sequential runs.


Algorithmic Mechanics

  1. Two-Way Sorted Merge ($O(N + M)$): Given existing sorted data of size $N$ and an incoming sorted batch of size $M$, two pointers merge both inputs into a single contiguous destination buffer. Sequential traversal allows the CPU prefetcher to operate at full memory bus bandwidth.

  2. Single-Pass Streaming PLA ($O(N + M)$): The merged buffer is streamed into the optimal convex hull slope corridor algorithm. Each element is evaluated once, producing the minimal optimal set of segments satisfying error tolerance $\pm \epsilon$.


Engineering Trade-Offs: When Batch Merge Wins vs. When B-Tree Wins

Workload DimensionDynamic In-Place B-Tree (BTreeMap)Batch Merge + Streaming PLA (PgmIndex)
Point Updates ($M = 1$ key)$O(\log N)$ ($\approx 20\text{–}25$ ops)$OO(N) full buffer rewrite (massive write amplification)
Small Batches ($M \ll N$)$O(M \log N)$ (localized node edits)$O(N + M)$ (rewrites all $N$ elements)
Large Compactions ($M \approx N$)$OO(M log(N + M)) pointer hops$O(N + M)$ strictly contiguous stream
Transient Memory During WriteZero extra buffer (node-by-node allocation)$2 \times (N + M)$ double-buffering during merge
Post-Merge Total Memory (1M keys)~45.78 MB (nodes + data embedded)~7.65 MB – 9.13 MB (7.63 MB data + index metadata)
Concurrent Read InterferenceRequires locks / latching or tree cowLock-free immutable snapshot reads

Key Architectural Takeaways

  1. Write Amplification on Small Batches: If an application requires frequent single-key insertions or random updates, BTreeMap is overwhelmingly superior. Rebuilding a PGM index for small $M$ wastes millions of CPU cycles re-approximating unchanged regions.

  2. Transient Double-Buffering Overhead: Merging a dataset of size $N$ with a batch $M$ requires allocating a contiguous buffer of size $(N + M) \times 8\text{ bytes}$. During the merge, both the old buffer and the new buffer reside simultaneously in memory. In memory-constrained environments, this transient peak can cause out-of-memory errors unless disk spillover is implemented.

  3. Sweet Spot: Batch merge and streaming rebuild is optimal specifically for write-rare, read-heavy analytical workloads (OLAP) or LSM-tree compaction stages where updates naturally occur in massive, pre-sorted blocks.

Theory: Cache-Conscious Eytzinger (Breadth-First) Layout

Summary Extract

Standard binary search over a contiguous sorted array jumps across disparate memory offsets (e.g. N/2, N/4, N/8), incurring recurring L1/L2/L3 cache misses and branch mispredictions.

The Eytzinger layout (also known as breadth-first or level-order array layout) reorganizes pre-sorted keys into a complete binary tree stored in an array indexed from 1:

  • Root is at index 1.
  • Node k has left child at 2k and right child at 2k + 1.

Microarchitectural Advantages

  1. Cache Locality: The top levels of the search tree (which are accessed on every single query) reside permanently in CPU L1/L2 cache lines.
  2. Branchless Traversal: Traversal uses arithmetic index advancement: $$k = 2k + (\text{target} > \text{tree}[k])$$ This compiles into conditional move instructions (cmov), completely eliminating branch misprediction stalls.

Full Research Papers & Resources

Learned Index Comparative Landscape & SOTA Analysis

Learned index structures replace or augment pointer-based hierarchical search trees by framing indexing as a cumulative distribution function (CDF) regression problem. Since the seminal proposal by Kraska et al. (2018), multiple distinct architectures have emerged, each navigating different microarchitectural trade-offs between theoretical guarantees, build speed, update mutability, and hardware cache alignment.

This document provides a comparative analysis of the primary learned and classical index designs.


1. High-Level Taxonomy Matrix

ArchitectureSeminal PublicationModel RepresentationLookup ComplexitySpace Bound GuaranteeIn-Place Write Support
Classical B+Tree / BTreeMapBayer & McCreight (1972); Comer (1979)Multi-way pointer/node hierarchyO(log_B N)Worst-case 50% storage utilizationFully dynamic (O(log_B N) rebalancing)
RMI (Recursive Model Index)Kraska et al. (SIGMOD 2018)Multi-stage staged regressions (Linear / Neural / Splines)Variable / Empirical boundsHeuristic (no formal worst-case bound)Read-only (full retrain needed)
FITing-TreeGalakatos et al. (SIGMOD 2019)Piecewise linear segments indexed by classical B+TreeO(log S + log ε)Heuristic PLA boundDynamic via buffer / leaf shifts
PGM-IndexFerragina & Vinciguerra (PVLDB 2020)Optimal streaming PLA indexed recursivelyO(h · log ε) or O(log S + log ε)Provably optimal segment count for fixed εRead-heavy / Batch merge (O(N + M))
RadixSplineKipf et al. (aiDM 2020)Top radix lookup table + linear spline pointsO(1 + log ε)Bounded by spline points + 2^r radix tableRead-only (single-pass build)
ALEXDing et al. (SIGMOD 2020)Adaptive gapped array nodes + linear modelsO(log N) expectedHeuristic (subject to gap fragmentation)Fully dynamic (in-node shifts & splits)

2. Structural & Microarchitectural Profiles

Classical B+Tree (std::collections::BTreeMap)

  • Core Philosophy: Partition keys into fixed-size node pages connected by pointers. Rust’s standard library implementation packs up to 11 keys and 12 children per internal node to optimize L1/L2 cache-line filling.
  • Hardware Profile: Sequential node traversal across heap pages induces repeated pointer dereferences and cache misses when the tree exceeds the CPU cache hierarchy.
  • Key Advantage: Distribution-agnostic robustness. Delivers predictable $O(\log N)$ performance regardless of non-linear plateaus, extreme Pareto skew, or adversarial patterns. Unmatched support for concurrent writes via page-level latch crabbing.
  • Primary Bottleneck: Index metadata footprint ($15%\text{–}30%$ of total storage) and lack of arithmetic rank interpolation.

RMI (Recursive Model Index)

  • Core Philosophy: A directed acyclic graph of models organized in layers (typically 2 to 3 stages). The root model maps an input key to a child model in layer 1, which progressively narrows the prediction corridor until the leaf model estimates the exact array offset.
  • Hardware Profile: Very fast arithmetic execution when models fit in CPU registers and L1 cache. Often executes in sub-10ns when simple linear or polynomial models are used.
  • Key Advantage: Ultra-low lookup latency on smooth, continuous, and predictable distributions (e.g. uniform or Gaussian).
  • Primary Bottleneck: Non-deterministic worst-case bounds. If an irregular key cluster diverges from the regression, the local search window can expand significantly, degrading to linear scan or wide binary search. High training overhead and lack of in-place mutation.

RadixSpline

  • Core Philosophy: Fits a greedy linear spline with error bound $\varepsilon$ during a single sequential scan, and layers a direct radix lookup table indexing the top $r$ bits of spline segment keys.
  • Hardware Profile: The top radix lookup operates in $O(1)$ with a single array indexation, eliminating binary search over spline anchors. The remaining window is verified with binary search within the bounded corridor $[-\varepsilon, +\varepsilon]$.
  • Key Advantage: Extremely fast single-pass build time with integer-only radix indexing. Predictable flat memory layout.
  • Primary Bottleneck: Radix sensitivity. Highly skewed keys sharing identical leading bit patterns degrade the radix table’s selectivity, forcing larger spline intervals or excessive radix table memory allocation ($2^r \times \text{pointer size}$).

ALEX (Adaptive Learned Index)

  • Core Philosophy: Blends learned linear models with gapped arrays inside dynamic tree nodes. Models predict target slots within gapped memory buffers, absorbing incoming insertions without immediate structural shifts.
  • Hardware Profile: High cache locality for in-memory read-write workloads. When gaps fill, nodes split or expand dynamically.
  • Key Advantage: Efficient dynamic insertions and updates within an in-memory learned architecture, outperforming B+Trees on mixed read/write workloads under gentle distributions.
  • Primary Bottleneck: Memory fragmentation caused by vacant gap slots. Degrades under non-uniform insertion bursts, triggering costly node expansions and structural rebalancing.

PGM-Index (learned-index)

  • Core Philosophy: Uses optimal streaming piecewise linear approximation (PLA) to compute the minimal number of segments $S$ covering $N$ keys within a deterministic vertical error corridor $\pm \varepsilon$. The resulting segment anchors can themselves be indexed recursively.
  • Hardware Profile: Each segment is represented by a compact 24-byte struct (key: u64, slope: f32, intercept: f32). Local search executes within a tiny bounded slice ($2\varepsilon + 1$ keys), fully residing in L1 cache (e.g. 65 elements for $\varepsilon=32$).
  • Key Advantage: Provable worst-case guarantees for both lookup time ($O(\log S + \log \varepsilon)$) and segment count optimality (Ferragina & Vinciguerra, 2020). Extreme index compression (metadata down to $0.003\text{ MB}$ per million keys vs $45.8\text{ MB}$ for BTreeMap).
  • Primary Bottleneck: Immutable base data array. Dynamic writes require out-of-place LSM-tree buffering or two-way batch merges ($O(N + M)$). Slower than classical trees on extreme Pareto heavy tails (e.g. SOSD Books) where non-linear steps explode segment counts.

3. Detailed Trade-off Matrix

Metric / DimensionB+Tree / BTreeMapRMIALEXRadixSplinePGM-Index
Deterministic Error ± εExact page boundariesNo (heuristic fallback)No (gapped offsets)Yes (± ε)Yes (± ε provable)
Segment Count OptimalityN/AHeuristicHeuristicGreedy heuristicProvably optimal
Build Time ComplexityO(N log N)O(N · epochs)O(N log N)O(N) single passO(N) single pass
Build Throughput2–5 M keys/s0.2–1 M keys/s1–4 M keys/s> 20 M keys/s10–15 M keys/s
Index Metadata OverheadHigh (15%–30%)Low (< 1%)Moderate (10%–25%)Very Low (< 1%)Minimal (< 0.1% to 0.01%)
In-Place InsertionsNative (O(log N))Not supportedNative (O(log N))Not supportedLSM / Batch Rebuild (O(N + M))
Concurrent WritesHigh (fine-grained latches)NoneComplex node locksNoneReader-Writer lock on snapshot
Extreme Skew ResilienceOptimalPoorModeratePoorModerate to Poor
Hardware FitMemory latency boundALU boundCache & pointer boundMemory latency boundL1 cache bound (local scan)

4. Workload Decision Guide

Select the indexing structure tailored to workload constraints:

  1. High-Frequency In-Place Updates & Transactions (OLTP):

    • Recommendation: Classical B+Tree / BTreeMap.
    • Reasoning: Unmatched page-level locking, predictable tree balance, and zero overhead for out-of-order writes.
  2. In-Memory Mixed Read/Write with Regular Key Distributions:

    • Recommendation: ALEX.
    • Reasoning: Combines learned prediction with gapped array insertion buffers, delivering high write throughput without periodic full rebuilds.
  3. Ultra-Fast Ingestion / Ephemeral Columnar Row Groups:

    • Recommendation: RadixSpline.
    • Reasoning: Constructing the index requires only a single sequential pass with direct radix table population, ideal for short-lived immutable batches.
  4. Immutable SSTables, Parquet Footers, NVMe/DRAM Constrained Systems:

    • Recommendation: PGM-Index (learned-index).
    • Reasoning: Minimal metadata footprint ($14,700\times$ smaller than B-Trees) and strict deterministic worst-case bounds make it suited for read-heavy immutable storage layers.
  5. Heavy-Tailed, Non-Linear Key Distributions (e.g. Pareto, Power-Law Books):

    • Recommendation: Classical B+Tree / EytzingerSearch.
    • Reasoning: Empirical benchmarks demonstrate that classical structures outperform linear learned models by $2.8\times$ when severe key clustering causes segment count explosion.

Academic References

  • Kraska, T., Beutel, A., Chi, E. H., Dean, J., & Polyzotis, N. (2018): “The Case for Learned Index Structures”, ACM SIGMOD, pp. 489–504.
  • Ferragina, P., & Vinciguerra, G. (2020): “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”, PVLDB 13(8): 1162–1175.
  • Ding, J., Min, D., Yu, H., & Kraska, T. (2020): “ALEX: An Updatable Adaptive Learned Index”, ACM SIGMOD, pp. 969–984.
  • Kipf, A., Marcus, R., van Renen, A., Stoian, M., Kemper, A., Kraska, T., & Neumann, T. (2020): “RadixSpline: a single-pass learned index”, aiDM@SIGMOD, pp. 5:1–5:8.
  • Galakatos, A., Markovitch, M., Binnig, C., Fonseca, R., & Kraska, T. (2019): “FITing-Tree: A Data-aware Index Structure”, ACM SIGMOD, pp. 1189–1206.
  • Bayer, R., & McCreight, E. (1972): “Organization and Maintenance of Large Ordered Indices”, Acta Informatica 1(3): 173–189.

Integration Cookbook: Practical Recipes for Production

This directory contains self-contained, production-tested integration patterns and recipes for embedding learned_index_lab (PgmIndex, MultilevelPgmIndex, and EytzingerSearch) into real-world storage engines, embedded databases, and analytical pipelines.


Architectural Invariants

All learned index structures in this lab adhere to four foundational constraints:

  1. Pre-Sorted Input: Vectors passed to constructors must be sorted in non-decreasing order (data[i] <= data[i + 1]).
  2. Deterministic Error Bounds: Every key’s predicted position is strictly bounded by $\pm \varepsilon$ around the true index.
  3. Zero Pointer Indirection: Segments and data arrays are contiguous memory buffers with zero runtime heap allocations during queries.
  4. Thread-Safe Read Concurrency: All index structures implement Send and Sync, allowing multi-threaded read sharing via Arc.
flowchart TD
    subgraph Storage["Storage Engine / Compaction Pipeline"]
        Raw["Sorted Data Array (u64)"] --> PLA["Streaming PLA (Single-Pass)"]
        PLA --> Segments["Contiguous Linear Segments"]
    end

    subgraph Memory["Query Serving Engine"]
        Key["Query Key x"] --> ALU["ALU Prediction: y = a*x + b"]
        ALU --> Window["Local Search Window: 2ε + 1 Keys"]
        Window --> Match["Exact Key / Predecessor"]
    end

    Segments -.->|"Segment Parameters"| ALU
    Raw -.->|"Contiguous Memory"| Window

Recipe Directory

RecipeTarget TopicPrimary APIs & Patterns
1. Point & Range QueriesExact matches, predecessors, and range scansfind, lower_bound, range, build
2. Concurrent Read ScalingMulti-core read parallelism without lock contentionArc<PgmIndex>, std::thread, thread pools
3. LSM SSTable Double-BufferingNon-blocking compaction lifecycle in LSM enginesmerge_sorted_batch, RwLock<Arc<PgmIndex>>
4. Columnar Block Zone MapsSparse indexing for Parquet / ClickHouse blocksBlock boundaries, row-group pruning
5. Operational Tuning & MonitoringProduction sizing, epsilon tuning, and health checksCache line sizing, N/S ratio monitoring

Recipe 1: Point Lookups, Predecessors & Contiguous Range Scans

This recipe covers standard query patterns for single-level and multi-level learned indexes: initializing the index, exact key lookups, predecessor searches, and zero-copy contiguous range queries.


1. Initializing & Sizing the Index

Choose between single-level PgmIndex and hierarchical MultilevelPgmIndex based on dataset magnitude:

#![allow(unused)]
fn main() {
use learned_index_lab::{MultilevelPgmIndex, PgmIndex};

fn build_indexes(keys: Vec<u64>) {
    let n = keys.len();

    if n <= 10_000_000 {
        // Single-level PGM-Index: optimal for datasets up to 10M keys
        // ε = 32 maps the 65-key local window into ~8 CPU cache lines (512 bytes)
        let pgm = PgmIndex::build(keys, 32);
        println!(
            "PgmIndex: {} segments ({:.2} KB metadata)",
            pgm.segments().len(),
            pgm.metadata_bytes() as f64 / 1024.0
        );
    } else {
        // Multilevel PGM-Index: for massive scale (> 10M keys)
        // ε = 32 at base layer, ε_rec = 16 for upper recursive index layers
        let ml_pgm = MultilevelPgmIndex::build_with_epsilons(keys, 32, 16);
        println!(
            "MultilevelPgmIndex: {} levels ({:.2} KB metadata)",
            ml_pgm.height(),
            ml_pgm.metadata_bytes() as f64 / 1024.0
        );
    }
}
}

2. Exact Point Lookup (find)

find locates the exact index of a target key in $O(\log S + \varepsilon)$ time. If duplicates exist, it returns an arbitrary matching position.

#![allow(unused)]
fn main() {
use learned_index_lab::PgmIndex;

fn execute_point_lookup(pgm: &PgmIndex, target_key: u64) {
    match pgm.find(target_key) {
        Some(idx) => {
            let val = pgm.data()[idx];
            assert_eq!(val, target_key);
            println!("Key {} found at offset {}", target_key, idx);
        }
        None => println!("Key {} is not present in index", target_key),
    }
}
}

3. Predecessor Search (lower_bound)

lower_bound returns the index of the first element greater than or equal to target_key, identical to std::slice::partition_point(|&k| k < target_key).

#![allow(unused)]
fn main() {
use learned_index_lab::PgmIndex;

fn execute_predecessor_search(pgm: &PgmIndex, query_key: u64) {
    let idx = pgm.lower_bound(query_key);

    if idx < pgm.data().len() {
        println!(
            "First key >= {}: at index {} (value = {})",
            query_key,
            idx,
            pgm.data()[idx]
        );
    } else {
        println!("All keys in the dataset are strictly smaller than {}", query_key);
    }
}
}

4. Zero-Copy Contiguous Range Queries (range)

range evaluates the bounding lower bounds for [start_key, end_key) and returns a direct borrowed slice &[u64]. Because the underlying data is contiguous in memory, range queries incur zero memory allocations.

#![allow(unused)]
fn main() {
use learned_index_lab::PgmIndex;

fn execute_range_query(pgm: &PgmIndex, start_ts: u64, end_ts: u64) -> &[u64] {
    // Zero heap allocations: returns a direct subslice &[u64]
    let slice = pgm.range(start_ts, end_ts);

    println!(
        "Range [{}, {}) matched {} contiguous records",
        start_ts,
        end_ts,
        slice.len()
    );

    slice
}
}

Boundary & Edge Case Semantics

  • Inverted Range: If start_key >= end_key, range immediately returns an empty slice &[].
  • Out of Bounds: If end_key > max_key, range safely truncates to data.len().
  • Extreme Limits: Fully supports u64::MIN (0) and u64::MAX without integer overflow or panics.

Recipe 2: Concurrent Multi-Threaded Read Scaling

This recipe demonstrates how to leverage the immutable memory layout of learned indexes to achieve linear read scalability across multiple CPU cores without lock contention.


Concurrency Guarantees

Both PgmIndex and MultilevelPgmIndex are strictly immutable once built. They implement Send and Sync:

  • Zero Synchronization Overhead: Readers perform arithmetic evaluation ($y = ax + b$) and contiguous binary searches without taking locks or incrementing atomic counters.
  • Cache-Line Sharing: Segment headers and data slices are read-only; multiple CPU cores can cache the same cache lines in their L1/L2 caches simultaneously without false-sharing penalties.

Multi-Core Query Server Pattern

#![allow(unused)]
fn main() {
use learned_index_lab::PgmIndex;
use std::sync::Arc;
use std::thread;

pub fn spawn_parallel_query_workers(
    data: Vec<u64>,
    worker_batches: Vec<Vec<u64>>,
) -> usize {
    // 1. Build immutable index and wrap in Arc for zero-copy thread sharing
    let shared_index = Arc::new(PgmIndex::build(data, 32));

    let mut handles = Vec::with_capacity(worker_batches.len());

    // 2. Distribute query batches across worker threads
    for batch in worker_batches {
        let index = Arc::clone(&shared_index);

        let handle = thread::spawn(move || {
            let mut matches = 0;
            for key in batch {
                // Lock-free point lookup
                if index.find(key).is_some() {
                    matches += 1;
                }
            }
            matches
        });

        handles.push(handle);
    }

    // 3. Aggregate results
    let total_matches: usize = handles
        .into_iter()
        .map(|h| h.join().expect("Worker thread panicked"))
        .sum();

    total_matches
}
}

Rayon Parallel Batch Evaluation

When integrating with data parallel frameworks such as Rayon, PgmIndex queries can be dispatched across thread pools using standard parallel iterators:

#![allow(unused)]
fn main() {
// Requires rayon = "1.8" in your Cargo.toml
use learned_index_lab::PgmIndex;
use rayon::prelude::*;

pub fn parallel_batch_lookup(pgm: &PgmIndex, query_keys: &[u64]) -> Vec<Option<usize>> {
    query_keys
        .par_iter()
        .map(|&key| pgm.find(key))
        .collect()
}
}

Performance Characteristic

On a 16-core system, read throughput scales near-linearly ($> 14\times$ speedup) because the contiguous segment array fits permanently in each core’s private L2 cache.

Recipe 3: LSM SSTable Double-Buffering & Compaction Lifecycle

In Log-Structured Merge-tree (LSM) architectures (such as RocksDB, ScyllaDB, and LevelDB), immutable SSTables are flushed to storage and periodically compacted in the background.

This recipe demonstrates the double-buffering compaction pattern: readers continue querying the active SSTable while a background worker merges an incoming batch and atomically swaps in the new index generation.


Compaction Lifecycle Architecture

sequenceDiagram
    autonumber
    participant Reader as Query Thread
    participant SSTable as Active Generation (RwLock<Arc<PgmIndex>>)
    participant Compactor as Background Compaction Worker

    Reader->>SSTable: Read query (find / lower_bound / range)
    Note over SSTable: Lock-free reads on cloned Arc
    Compactor->>Compactor: Merge sorted batch O(N + M)
    Compactor->>Compactor: Single-pass streaming PLA rebuild
    Compactor->>SSTable: Acquire quick write lock & swap Arc pointer
    Note over SSTable: Next generation active instantaneously
    Reader->>SSTable: Subsequent queries read new generation

Complete Implementation: LsmSstableEngine

#![allow(unused)]
fn main() {
use learned_index_lab::PgmIndex;
use std::sync::{Arc, RwLock};

pub struct LsmSstableEngine {
    /// Active generation wrapped in an RwLock for instantaneous atomic pointer swap
    active_index: RwLock<Arc<PgmIndex>>,
    epsilon: usize,
}

impl LsmSstableEngine {
    /// Initializes an SSTable with base sorted data
    pub fn new(initial_sorted_keys: Vec<u64>, epsilon: usize) -> Self {
        let index = Arc::new(PgmIndex::build(initial_sorted_keys, epsilon));
        Self {
            active_index: RwLock::new(index),
            epsilon,
        }
    }

    /// Read query: clones Arc pointer under a brief read lock.
    /// Traversal and ALU evaluation occur completely lock-free.
    pub fn get(&self, key: u64) -> Option<usize> {
        let generation = {
            let guard = self.active_index.read().expect("Lock poisoned");
            Arc::clone(&*guard)
        };

        generation.find(key)
    }

    /// Range scan: returns a contiguous slice from the active generation snapshot
    pub fn scan(&self, start_key: u64, end_key: u64) -> Vec<u64> {
        let generation = {
            let guard = self.active_index.read().expect("Lock poisoned");
            Arc::clone(&*guard)
        };

        generation.range(start_key, end_key).to_vec()
    }

    /// Background compaction worker: merges incoming sorted batch and swaps pointer.
    pub fn compact_and_rebuild(&self, sorted_batch: &[u64]) {
        // Step 1: Snapshot active generation
        let current_generation = {
            let guard = self.active_index.read().expect("Lock poisoned");
            Arc::clone(&*guard)
        };

        // Step 2: Perform heavy O(N + M) 2-way merge and PLA construction OUTSIDE locks
        let new_generation = current_generation.merge_sorted_batch(sorted_batch);
        let new_arc = Arc::new(new_generation);

        // Step 3: Instantaneous pointer swap under exclusive write lock
        {
            let mut guard = self.active_index.write().expect("Lock poisoned");
            *guard = new_arc;
        }
    }
}
}

Operational Advantages

  1. Zero Reader Downtime: Active lookups are never blocked by the CPU-intensive 2-way merge or segment construction.
  2. Deterministic Memory Footprint: The previous generation is freed automatically as soon as existing readers drop their cloned Arc references.
  3. Throughput: Single-pass PLA constructs segments at $> 10\text{ M keys/second}$, minimizing the compaction window.

Recipe 4: Columnar Block Indexing & Zone Map Pruning

In analytical engines (such as ClickHouse, DuckDB, and Apache Parquet), table data is horizontally partitioned into compressed row groups or data pages (typically 64 KB to 100,000 rows each).

Rather than indexing every individual record, PgmIndex can serve as a ultra-compact sparse block index over row-group boundaries to prune non-matching blocks without decompression.


Architecture: Sparse Boundary Indexing

flowchart LR
    Query["Target Key: 15,400"] --> PGM["PGM Sparse Index (Block Min Keys)"]
    PGM --> Predict["Lower Bound Lookup: Block #3"]
    Predict --> Disk["Physical Block #3 (Decompress & Scan)"]
    Predict -.->|"Pruned (Skip)"| Block1["Block #1 [0, 4999]"]
    Predict -.->|"Pruned (Skip)"| Block2["Block #2 [5000, 9999]"]

Implementation: ColumnarBlockIndex

#![allow(unused)]
fn main() {
use learned_index_lab::PgmIndex;

#[derive(Debug, Clone)]
pub struct BlockDescriptor {
    pub block_id: u32,
    pub min_key: u64,
    pub max_key: u64,
    pub byte_offset: u64,
    pub compressed_size: u32,
}

pub struct ColumnarBlockIndex {
    /// PGM index over the min_key of each storage block
    sparse_index: PgmIndex,
    /// Physical block descriptors
    blocks: Vec<BlockDescriptor>,
}

impl ColumnarBlockIndex {
    pub fn new(blocks: Vec<BlockDescriptor>) -> Self {
        let boundary_keys: Vec<u64> = blocks.iter().map(|b| b.min_key).collect();

        // Small epsilon (e.g. 8) ensures block boundary resolution in 1-2 cache lines
        let sparse_index = PgmIndex::build(boundary_keys, 8);

        Self {
            sparse_index,
            blocks,
        }
    }

    /// Identifies the candidate storage blocks that may contain the target key
    pub fn locate_candidate_blocks(&self, target_key: u64) -> &[BlockDescriptor] {
        let lb = self.sparse_index.lower_bound(target_key);
        let candidate_idx = if lb == 0 { 0 } else { lb - 1 };

        let start = candidate_idx;
        let end = (candidate_idx + 2).min(self.blocks.len());

        &self.blocks[start..end]
    }
}
}

Production Impact

  • Footprint: For 100,000 blocks covering 1 billion rows, the sparse boundary index requires less than 32 KB of RAM, residing permanently in L1/L2 cache.
  • I/O Savings: Queries eliminate up to 99.9% of decompression and storage reads by targeting only candidate blocks identified by the PGM model.

Recipe 5: Operational Tuning, Monitoring & Production Checklist

This recipe provides concrete rules for tuning $\varepsilon$ against hardware cache lines, monitoring segment degradation in production, and selecting the optimal index architecture.


1. Hardware Cache-Line Alignment for $\varepsilon$

On x86_64 and ARM64 architectures, CPU cache lines are 64 bytes wide (storing exactly eight 64-bit u64 keys).

The local search window size is $2\varepsilon + 1$ keys. Choosing $\varepsilon$ as a multiple of 8 aligns the search window to physical cache lines:

$\varepsilon$Local Search Window ($2\varepsilon + 1$)Cache Lines (64-byte)Hardware Cache TierBest For
817 keys (136 bytes)~2 cache linesL1 Data CacheLow-latency point lookups
1633 keys (264 bytes)~4 cache linesL1 / L2 CacheGeneral-purpose default
3265 keys (520 bytes)~8 cache linesL2 CacheHigh-compression datasets
64129 keys (1032 bytes)~16 cache linesL2 / L3 CacheUltra-low RAM footprint

2. Key Metrics & Alerting Thresholds

When operating learned indexes in production storage layers, track these runtime metrics:

flowchart TD
    Build["PgmIndex::build()"] --> Metric1["Compression Ratio: N / S"]
    Metric1 --> Check{"N / S >= 50?"}
    Check -->|"Yes (Healthy)"| Healthy["Optimal Linear Fit: L1/L2 Residency"]
    Check -->|"No (Degraded)"| Degraded["High Distribution Curvature / Noise"]
    Degraded --> Action["Action: Increase ε or switch to Multilevel / Eytzinger"]

Health Metrics Reference

MetricCalculationHealthy RangeDegraded SignalRecommended Action
Compression RatioN/S (keys per segment)$> 100\times$$< 50\times$Increase $\varepsilon$ or evaluate key distribution skew
Index Metadata Sizepgm.metadata_bytes()$< 1%$ of raw data$> 5%$ of raw dataSwitch to MultilevelPgmIndex
Lookup LatencyMean point lookup time$100 - 150\text{ ns}$$> 300\text{ ns}$Segments overflowing L3 cache; add hierarchical level

3. Production Deployment Checklist

Before deploying learned index pipelines to production, verify each invariant:

  • Input Sortedness Guarantee: Data buffer is validated with slice.windows(2).all(|w| w[0] <= w[1]) prior to index construction.
  • Zero-Drop Compaction: In LSM compactions, 2-way merges verify that total key count matches initial_len + batch_len.
  • Thread-Safe Architecture: Shared query indexes are wrapped in Arc without surrounding mutexes on query hot paths.
  • Duplicate Key Plateau Bounding: Datasets with high frequencies of identical keys are protected by the $\Delta x = 0$ absorption mechanics.
  • Memory Ceiling Verification: Ensure auxiliary buffer allocation during double-buffered compaction does not exceed host RAM capacity.

Statistical Benchmarks & Comparative Analysis (v0.4.0)

This document presents a rigorous, unbiased evaluation methodology, workload distributions, per-scenario statistical results, and architectural trade-offs across 5 distinct search paradigms:

  1. std::collections::BTreeMap: Rust standard library pointer-based dynamic search tree (B-Tree).
  2. Flat slice::binary_search: In-situ contiguous sorted slice binary search.
  3. EytzingerSearch: 1-based complete binary tree array layout with branchless cmov traversal.
  4. PgmIndex: Piecewise Geometric Model learned index with bounded linear approximation corridors.
  5. MultilevelPgmIndex: Hierarchical recursive PGM-Index with $O(h \cdot \log \epsilon)$ descent.

Benchmark Methodology

  • Hardware Platform: x86_64, Windows, Rust --release mode.
  • Dataset Size: 1,000,000 keys (64-bit unsigned integers, $8\text{ MB}$ raw data).
  • Queries: 100,000 lookups per run (50% hits, 50% internal misses within $[k_0, k_{N-1}]$).
  • Workload Distributions: 6 distinct benchmark profiles:
    • Synthetic: Dense Sequential Time-Series ($\epsilon = 32$), Uniform Sparse Random ($\epsilon = 16$), Heavy-Tailed Lognormal ($\epsilon = 16$).
    • SOSD Real-World: OpenStreetMap Cell IDs (osm_cellids, $\epsilon = 16$), Wikipedia Timestamps (wiki_ts, $\epsilon = 32$), Book ISBNs (books, $\epsilon = 16$).
  • Repetitions: 5 consecutive isolated runs per target and per suite (30 independent runs total per structure).
  • Cache Isolation: 32MB L1-L3 cache eviction barrier (clear_cpu_cache()) executed before every construction and lookup phase.
  • Thread Safety: Single-threaded execution (--test-threads=1) to eliminate core scheduling jitter.

Memory Model Distinction: Metadata vs. Total Resident Memory

When evaluating memory consumption, a critical distinction must be drawn between index metadata overhead and total resident memory:

StructureRaw Data Buffer (1M keys)Index Metadata OverheadTotal Resident MemoryMutation / Ingestion Model
Flat Slice7.63 MB (10⁶ × 8 B)0.00 KB7.63 MBRead-only (shift O(N))
Eytzinger (In-Situ)7.63 MB (level-order)0.00 KB7.63 MBRead-only (rebuild required)
Eytzinger (Index)7.63 MB (sorted source)7.63 MB (tree array)15.26 MBRead-only (rebuild required)
PgmIndex7.63 MB (10⁶ × 8 B)3.1 KB – 1.50 MB7.63 MB – 9.13 MBRead-only (batch merge O(N+M))
MultilevelPgmIndex7.63 MB (10⁶ × 8 B)2.0 KB – 1.32 MB7.63 MB – 8.95 MBRead-only (batch merge O(N+M))
BTreeMapEmbedded in heap nodes~45.78 MB (nodes + pointers)45.78 MBDynamic (in-place O(log N))
  • PgmIndex and MultilevelPgmIndex do not replace the underlying data buffer; they are secondary index structures requiring the raw contiguous sorted slice ($7.63\text{ MB}$).
  • While PGM reduces index metadata by up to 14,700x relative to BTreeMap on linear workloads, the total process memory reduction is approximately 5.0x to 5.7x ($7.63\text{ MB}$ vs $45.78\text{ MB}$).

Detailed Results by Distribution

1. Dense Sequential Time-Series Data ($\epsilon = 32$)

Monotonically increasing telemetry timestamps or auto-increment primary keys. Highly linear CDF.

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTree
BTreeMap66.57 ms224.1 ns229.4 ns229.1 ns45.78 MB227.5 ns1.00x
Flat Slice0.00 ms168.2 ns139.4 ns122.7 ns0.00 KB143.4 ns1.33x
Eytzinger5.54 ms137.8 ns140.8 ns143.1 ns7.63 MB140.6 ns1.63x
PGM-Index4.64 ms107.1 ns101.0 ns132.0 ns3.1 KB113.4 ns2.09x
Multilevel PGM4.61 ms145.8 ns133.1 ns206.4 ns2.0 KB161.8 ns1.54x
  • Analysis: PGM achieves its best relative performance here (2.09x vs BTree). The nearly perfect linear CDF is compressed into only 93 segments ($3.1\text{ KB}$), fitting permanently into the L1 CPU cache.
  • Trade-off: Flat Slice requires 0 ms build time and 0 KB metadata with respectable 143.4 ns latency.

2. Uniform Sparse Random Keys ($\epsilon = 16$)

Uniform 64-bit random values across a wide domain ($[0, 10^{12}]$).

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTree
BTreeMap66.36 ms240.6 ns252.7 ns232.5 ns45.78 MB241.9 ns1.00x
Flat Slice0.00 ms152.5 ns133.0 ns135.5 ns0.00 KB140.4 ns1.58x
Eytzinger5.43 ms130.1 ns132.6 ns126.8 ns7.63 MB129.8 ns1.85x
PGM-Index5.16 ms126.3 ns115.0 ns137.9 ns48.1 KB126.4 ns1.91x
Multilevel PGM4.80 ms139.1 ns121.8 ns199.9 ns33.0 KB153.6 ns1.73x
  • Analysis: PGM generates 1,416 segments ($48.1\text{ KB}$), remaining within L2 cache. PGM-Index (126.4 ns) and Eytzinger (129.8 ns) perform neck-and-neck, both outperforming BTreeMap by $\sim 1.9\text{x}$.
  • Trade-off: Eytzinger achieves near-identical latency without floating-point ALU operations.

3. Clustered Heavy-Tailed Lognormal Distribution ($\epsilon = 16$)

Power-law distribution with heavy skew in low values and an extended sparse tail.

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTree
BTreeMap65.83 ms227.6 ns228.7 ns228.1 ns45.78 MB228.1 ns1.00x
Flat Slice0.00 ms174.0 ns138.4 ns153.8 ns0.00 KB155.4 ns1.31x
Eytzinger5.35 ms132.9 ns130.7 ns131.8 ns7.63 MB131.8 ns1.71x
PGM-Index5.16 ms117.0 ns105.0 ns139.5 ns12.1 KB120.5 ns1.95x
Multilevel PGM5.12 ms154.8 ns131.9 ns215.0 ns10.8 KB167.2 ns1.47x
  • Analysis: Streaming PLA compresses the skewed CDF effectively into 475 segments ($12.1\text{ KB}$), delivering 120.5 ns latency.
  • Trade-off: On lower_bound, Eytzinger remains faster (131.8 ns vs 139.5 ns for PGM).

4. SOSD OpenStreetMap (OSM CellIDs) ($\epsilon = 16$)

Geospatial Hilbert cell IDs from real-world OpenStreetMap data with irregular cluster densities.

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTree
BTreeMap66.08 ms232.4 ns247.0 ns244.6 ns45.78 MB241.3 ns1.00x
Flat Slice0.00 ms151.3 ns132.6 ns136.2 ns0.00 KB140.1 ns1.54x
Eytzinger5.25 ms140.3 ns135.8 ns127.9 ns7.63 MB134.7 ns1.66x
PGM-Index5.11 ms119.9 ns123.2 ns151.8 ns192.1 KB131.6 ns1.94x
Multilevel PGM4.95 ms160.3 ns150.2 ns204.7 ns97.4 KB171.7 ns1.45x
  • Analysis: Despite generating 4,145 segments ($192.1\text{ KB}$), PGM-Index retains an edge in point lookups (119.9 ns), while Eytzinger is faster on range/predecessor queries (lower_bound: 127.9 ns).

5. SOSD Wikipedia Timestamps (Wiki-TS) ($\epsilon = 32$)

Real-world edit log timestamps featuring plateaus of duplicate keys, micro-bursts, and idle gaps.

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTree
BTreeMap36.32 ms111.1 ns104.2 ns108.7 ns45.78 MB108.0 ns1.00x
Flat Slice0.00 ms134.6 ns111.7 ns124.2 ns0.00 KB123.5 ns0.83x
Eytzinger5.30 ms131.9 ns124.5 ns137.2 ns7.63 MB131.2 ns0.84x
PGM-Index5.57 ms136.5 ns135.3 ns167.6 ns192.1 KB146.5 ns0.81x (slower)
Multilevel PGM4.86 ms153.9 ns197.7 ns209.6 ns152.3 KB187.1 ns0.72x (slower)
  • Key Takeaway: BTreeMap is 1.35x faster than PGM-Index and 1.73x faster than Multilevel PGM.
  • Reason: Micro-bursts and duplicate keys force frequent segment restarts (6,593 segments), degrading binary search over segments. B-Tree node caching handles bursty repeated queries more efficiently than linear projection.

6. SOSD Books (Heavy-Tailed Book ISBNs) ($\epsilon = 16$)

Real-world Book ISBNs from SOSD benchmark, displaying extreme Pareto step functions and cluster voids.

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTree
BTreeMap11.34 ms37.3 ns26.0 ns41.5 ns45.78 MB34.9 ns1.00x
Flat Slice0.00 ms64.9 ns25.4 ns62.2 ns0.00 KB50.8 ns0.58x (slower)
Eytzinger5.34 ms58.6 ns32.4 ns59.8 ns7.63 MB50.3 ns0.64x (slower)
PGM-Index3.06 ms86.3 ns63.5 ns151.1 ns1.50 MB100.3 ns0.43x (2.87x slower)
Multilevel PGM3.33 ms144.2 ns115.3 ns201.2 ns1.32 MB153.6 ns0.26x (4.40x slower)
  • Key Takeaway: BTreeMap significantly outperforms all learned and binary approaches. It is 2.87x faster than PGM-Index and 4.40x faster than Multilevel PGM.
  • Reason: Severe non-linearity breaks piecewise linear approximation, yielding 55,167 segments ($1.50\text{ MB}$ of metadata). Binary searching through a 1.50 MB segment array incurs repeated L2/L3 cache misses. Meanwhile, B-Tree branches quickly isolate dense prefixes.

Grand Summary (30 Runs Per Target Across All 6 Workload Suites)

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MetadataMoyenne Totale LatenceSpeedup vs BTreeTotal Memory (Data + Index)
BTreeMap52.08 ms178.8 ns181.3 ns180.7 ns45.78 MB180.3 ns1.00x45.78 MB
Flat Slice0.00 ms140.9 ns113.4 ns122.4 ns0.00 KB125.6 ns1.27x7.63 MB
Eytzinger5.37 ms122.0 ns116.2 ns121.1 ns7.63 MB119.7 ns1.47x15.26 MB
PGM-Index4.78 ms115.5 ns107.2 ns146.7 ns330.6 KB123.1 ns1.55x7.96 MB
Multilevel PGM4.61 ms149.7 ns141.7 ns206.1 ns274.5 KB165.8 ns1.19x7.90 MB

Objective Architectural Findings

  1. No Universal Winner:
    • PGM-Index is fastest on smooth, continuous, or moderately clustered distributions (Time-Series, Uniform, Lognormal, OSM), delivering up to 2.09x speedup over BTreeMap with low metadata ($3.1\text{ KB} - 192\text{ KB}$).
    • BTreeMap wins decisively on irregular, heavily fragmented, or extreme Pareto power-law distributions (Books: 2.87x faster than PGM; Wiki-TS: 1.35x faster), because localized pointer trees handle discontinuities and duplicates better than piecewise linear slopes.
    • EytzingerSearch provides the most consistent overall performance across all suites (average 119.7 ns, outperforming PGM’s 123.1 ns average) and the fastest predecessor search (lower_bound: 121.1 ns), without any sensitivity to key distribution shape.
    • Flat slice::binary_search remains the best choice when build time (0.00 ms) and index memory (0.00 KB) are constrained, lagging only $\sim 6\text{ ns}$ behind PGM overall.
  2. Memory Footprint Reality:
    • PGM’s metadata savings are dramatic ($330\text{ KB}$ vs $45.8\text{ MB}$), but since the raw sorted slice ($7.63\text{ MB}$) must be retained, the effective end-to-end memory reduction is $\approx 5.7\text{x}$, not 14,000x.
  3. Multilevel Scaling Limits at $10^6$ Keys:
    • At $N = 10^6$, MultilevelPgmIndex is slower than single-level PgmIndex (165.8 ns vs 123.1 ns). The arithmetic overhead of hierarchical descent does not pay off until datasets exceed $10^7$ keys where single-level segment arrays overflow L3 cache.

Academic References

  • SOSD Benchmark Suite:
    • Marcus, R., Kipf, A., van Renen, A., Tatarakis, M., Sheng, C., & Kraska, T. (2019). “Benchmarking Learned Indexes”. Proceedings of the VLDB Endowment (PVLDB) / AIDB.
    • Paper: arXiv:1908.07009 · Codebase: GitHub learnedsystems/SOSD
  • PGM-Index Theoretical Formulation:
    • Ferragina, P., & Vinciguerra, G. (2020). “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”. PVLDB 13(8): 1162–1175.
    • Paper: PVLDB PDF · arXiv:1910.06169
  • Eytzinger Layout Formalization:
    • Khuong, P.-V., & Morin, P. (2017). “Array Layouts for Comparison-Based Searching”. ACM Journal of Experimental Algorithmics (JEA), 22: 1–39.
    • Paper: arXiv:1509.05053

Learned Index: Piecewise Geometric Model (PGM-Index) in Rust

CI Crates.io Docs.rs License: Apache-2.0 Ko-fi GitHub Sponsors

A clean, zero-dependency Rust implementation and comparative benchmark suite of Piecewise Geometric Model (PGM) Learned Index Structures.

This repository evaluates mathematical function approximations of Empirical Cumulative Distribution Functions (CDFs) against standard pointer trees (BTreeMap), contiguous binary search (slice::binary_search), and cache-conscious breadth-first search (EytzingerSearch).

Note

Academic Attribution: Learned Indexes were originated by Kraska et al. (MIT/Google, SIGMOD 2018). The PGM-index was invented and proven by Paolo Ferragina and Giorgio Vinciguerra (University of Pisa, PVLDB 2020). The Eytzinger layout was formalized by Paul-Virak Khuong and Pat Morin (ACM JEA 2017). This repository is an independent, clean-room implementation in pure safe Rust.


Architectural Comparison (4 Search Paradigms)

DimensionStandard BTreeMapFlat slice::binary_searchEytzingerSearch (Breadth-First)PGM-Index (Learned Model)
Data LayoutHeap node hierarchyContiguous sorted slice1-based complete binary tree arrayCompact array of $(a, b, k_0)$ segments
Lookup Mechanism4–6 pointer hops across heap$\sim 20$ binary jumps across RAMBranchless arithmetic traversal (k = 2k + bit)In-register ALU prediction + bounded local scan
Cache LocalityPoor (scattered heap nodes)Medium (strided binary jumps)High (upper tree levels in L1/L2)Highest (segments fit entirely in L1/L2)
Index Overhead$\sim 45.78\text{ MB}$ per $10^6$ keys$0\text{ KB}$ (in-situ data only)$7.63\text{ MB}$ per $10^6$ keys (duplicate layout)3.1 KB – 48.1 KB (-99.9% vs BTree)
Primary StrengthDynamic in-place mutationsZero extra memoryBranchless search, cache friendlySub-microsecond lookups, extreme compression

Benchmark Summary (v0.3.0 Consolidated Results)

Measured on x86_64 hardware in --release mode. Consolidated average across all 3 workload distributions (30 independent runs per target structure with a 32MB L1-L3 CPU cache eviction barrier between phases):

Cible / TargetBuild TimeHit LatencyMiss LatencyLower BoundIndex MemoryMoyenne Totale LatenceSpeedup vs BTree
BTreeMap84.12 ms314.4 ns331.4 ns350.0 ns45.78 MB331.9 ns1.00x
Flat Slice0.00 ms282.7 ns272.9 ns275.3 ns0.00 KB277.0 ns1.20x
Eytzinger6.30 ms163.7 ns160.9 ns169.2 ns7.63 MB164.6 ns2.02x
PGM-Index6.82 ms153.0 ns154.1 ns208.6 ns21.1 KB171.9 ns1.93x

Detailed breakdown per distribution (Dense Time-Series, Uniform Sparse, and Heavy-Tailed Lognormal) is available in docs/benchmarks/statistical_benchmarks.md.


Reproducibility & Verification

The v0.3.0 test suite and benchmark harness support strict single-threaded isolation and modular target selection:

# Clone the repository
git clone https://github.com/gilnett/learned_index_lab.git
cd learned_index_lab

# Run the unit test suite with thread isolation
cargo test --release -- --test-threads=1

# Execute the full 10-run release benchmark across all 4 targets
cargo run --release

# Run isolated benchmarks on specific targets
cargo run --release -- --target eytzinger,pgm --runs 10
cargo run --release -- --target pgm --suite uniform

Documentation Index


References

Technical Articles & Deep Dives

Seminal Research Papers

  • Kraska et al. (2018): “The Case for Learned Index Structures” (ACM SIGMOD 2018) – PDF (arXiv) · arXiv:1712.01208. Seminal paper proving that sorted indexes can be modeled as cumulative distribution function (CDF) regressions.
  • Ferragina & Vinciguerra (2020): “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds” (PVLDB 2020) – PDF (PVLDB) · PDF (arXiv) · arXiv:1910.06169. Establishes optimal piecewise linear approximation (PLA) under bounded error corridors $\epsilon$.
  • Khuong & Morin (2017): “Array Layouts for Comparison-Based Searching” (ACM JEA 2017) – PDF (arXiv) · arXiv:1509.05053. Formalizes the cache-conscious Eytzinger array layout and branchless level-order search.

Reference Codebases & Implementations

Industry Storage Engines & Analytical Systems


License

Licensed under the Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0).

Learned Index: Piecewise Geometric Model (PGM-Index) in Rust (v0.2.0 Archive)

CI Crates.io Docs.rs License: Apache-2.0 Ko-fi GitHub Sponsors

Note

Historical Archive: This document preserves the state of the documentation for v0.2.0 of learned-index, which introduced comparison against Flat slice::binary_search, lower_bound, and range scans.


A zero-dependency, production-grade implementation of Piecewise Geometric Model (PGM) Learned Index Structures in pure Rust.

This repository demonstrates the paradigm shift away from traditional comparison-based pointer hierarchies (such as B-Trees and LSM block indexes) to mathematical function approximations of Empirical Cumulative Distribution Functions (CDFs) with provable $\epsilon$ error bounds.

Note

Academic Attribution & Acknowledgments: I am not the original creator of Learned Indexes or the Piecewise Geometric Model (PGM-index).

This repository (learned-index) is an independent, clean-room educational and production-oriented implementation in pure safe Rust, built to explore, benchmark, and evaluate learned indexing mechanics within the modern systems ecosystem.


Architectural Comparison & Hardware Dynamics

Starting with v0.2.0, learned-index evaluates PGM against both common baseline approaches:

  1. std::collections::BTreeMap: The standard library mutable, dynamic pointer-based search tree.
  2. Flat slice::binary_search: The standard library immutable baseline (contiguous array binary search).
DimensionStandard BTreeMapFlat slice::binary_searchPGM-Index (Learned)Microarchitectural Advantage
Index StructureDynamic nodes across heapContiguous raw bufferCompact array of $(a, b, k_0)$ segmentsMetadata fits entirely inside L1/L2 cache
Lookup Mechanism4–6 node hops across RAM$\sim 20$ binary jumps across 8 MB1 in-register math eval + local 4 cache linesEliminates DRAM stalls & cache pollution
Index Metadata$\sim 45\text{ MB}$ per $10^6$ keys$0\text{ KB}$ (data must stay resident)3.1 KB – 48 KB per $10^6$ keys-99.9% index memory vs B-Tree
Lookup Latency$220 - 290\text{ ns}$$140 - 160\text{ ns}$48 - 70 ns3x faster vs B-Tree, ~2.2x vs Slice
Construction Time$\sim 70\text{ ms}$ ($O(N \log N)$)$0\text{ ms}$ (pre-sorted input)$3.5\text{ ms}$ ($O(N)$ streaming)~18x faster construction than B-Tree

Statistical Benchmark Suite (10-Run Rigorous Analysis)

All benchmarks were measured locally on x86_64 hardware using Rust in --release mode. Each scenario was executed over 10 consecutive runs with distinct randomized seeds to eliminate CPU scheduling noise and warm-cache anomalies.

  • Dataset Size: 1,000,000 keys (64-bit integers)
  • Queries per Run: 100,000 queries (50% existing keys / hits, 50% non-existent keys / misses)

1. Dense Sequential Time-Series Data

Distribution: Dense Timestamp | Tolerance: epsilon = 32
MetricBTreeMapFlat slice::binary_searchPGM-Index (Learned)Improvement Factor
Mean Build Time67.94 ms0.00 ms (pre-sorted)3.65 ms18.6x faster than BTree
Index-Only Memory45.78 MB0 KB3.1 KB14,700x compression
Mean Hit Latency221.8 ns/op152.7 ns/op63.5 ns/op3.50x vs BTree / 2.41x vs Slice
Mean Miss Latency10.0 ns/op23.7 ns/op0.7 ns/op14.3x faster negative rejection
Segments CountN/AN/A83 segments12,048x factor
Verification100.0% match100.0% match100.0% match0 discrepancies across 10 runs

2. Uniform Sparse Random Keys

Distribution: Uniform Sparse Random | Tolerance: epsilon = 16
MetricBTreeMapFlat slice::binary_searchPGM-Index (Learned)Improvement Factor
Mean Build Time68.79 ms0.00 ms (pre-sorted)3.82 ms18.0x faster than BTree
Index-Only Memory45.78 MB0 KB48.1 KB-99.89% memory reduction
Mean Hit Latency223.0 ns/op150.9 ns/op70.5 ns/op3.16x vs BTree / 2.14x vs Slice
Mean Miss Latency214.6 ns/op104.0 ns/op68.1 ns/op3.15x vs BTree / 1.53x vs Slice
Segments CountN/AN/A1,406 segments711x compression
Verification100.0% match100.0% match100.0% match0 discrepancies across 10 runs

3. Clustered Heavy-Tailed Lognormal Distribution

Distribution: Lognormal Clustered | Tolerance: epsilon = 16
MetricBTreeMapFlat slice::binary_searchPGM-Index (Learned)Improvement Factor
Mean Build Time69.75 ms0.00 ms (pre-sorted)3.90 ms17.9x faster than BTree
Index-Only Memory45.78 MB0 KB12.1 KB-99.97% memory reduction
Mean Hit Latency216.4 ns/op141.0 ns/op48.6 ns/op4.45x vs BTree / 2.90x vs Slice
Mean Miss Latency61.4 ns/op39.8 ns/op38.2 ns/op1.61x vs BTree / 1.04x vs Slice
Segments CountN/AN/A455 segments2,197x compression
Verification100.0% match100.0% match100.0% match0 discrepancies across 10 runs

Learned Index Lab: Piecewise Geometric Model (PGM-Index) in Rust

CI Crates.io Docs.rs License: Apache-2.0

A zero-dependency, production-grade implementation of Piecewise Geometric Model (PGM) Learned Index Structures in pure Rust.

This repository demonstrates the paradigm shift away from traditional comparison-based pointer hierarchies (such as B-Trees and LSM block indexes) to mathematical function approximations of Empirical Cumulative Distribution Functions (CDFs) with provable $\epsilon$ error bounds.


Table of Contents


Overview & The Paradigm Shift

For more than 50 years, database indexing has relied on tree-based data structures (B-Tree, B+Tree, LSM-Tree). While mature, B-Trees possess inherent physical constraints on modern CPU architectures:

  1. Pointer Chasing: Navigating down a tree requires sequential memory dereferences across disparate memory addresses, causing recurring L1/L2/L3 cache misses.
  2. High Memory Overhead: Tree nodes require significant metadata per key (child pointers, balance factors, keys, values), consuming 30–50 bytes per entry.
  3. Branch Misprediction: Binary comparisons at each node introduce branch penalties on deeply pipelined modern CPUs.

Learned Indexes (originally introduced by Kraska et al., MIT / Google) reframe indexing as a regression problem: Given a sorted sequence of keys $K = (k_0, k_1, \dots, k_{N-1})$, the position of any key $k$ in memory corresponds to the scaled Empirical Cumulative Distribution Function:

$$\text{Pos}(k) \approx N \times \text{CDF}(k)$$

Rather than allocating deep node hierarchies, a PGM-Index partitions the data into a minimal set of linear segments $y = ax + b$, guaranteeing that the true position of any indexed key is within a strict error window $[y - \epsilon, y + \epsilon]$.


Mathematical Foundation

Optimal Streaming Piecewise Linear Approximation (PLA)

The index builder executes in a single streaming pass ($O(N)$ time, $O(1)$ extra space).

For a segment starting at point $(x_0, y_0)$ and a given maximum error tolerance $\epsilon$: Each subsequent point $(x_i, y_i)$ restricts the feasible slope interval $[s_{\min}, s_{\max}]$:

$$s_{\min} = \max_{j} \left[ \frac{(y_j - \epsilon) - y_0}{x_j - x_0} \right]$$

$$s_{\max} = \min_{j} \left[ \frac{(y_j + \epsilon) - y_0}{x_j - x_0} \right]$$

As long as $s_{\min} \le s_{\max}$, all points observed so far can be represented by a single straight line with error at most $\epsilon$. Once $s_{\min} > s_{\max}$, the segment is finalized with slope $s = \frac{s_{\min} + s_{\max}}{2}$, and a new segment starts.

During point lookup:

  1. The responsible segment is found via a rapid binary search across the segment array ($O(\log S)$ where $S \ll N$).
  2. The position estimate is computed directly via ALU instructions: $$\text{Pos}_{\text{approx}} = \text{round}(y_0 + s \cdot (k - x_0))$$
  3. The exact match is retrieved via a local binary search bounded strictly inside: $$[\max(0, \text{Pos}{\text{approx}} - \epsilon), \min(N - 1, \text{Pos}{\text{approx}} + \epsilon)]$$
  • Time Complexity: $O(\log S + \log \epsilon)$
  • Space Complexity: $O(S)$ where $S \approx \frac{N}{\text{compression ratio}}$
  • Correctness: 100% exact (0 false positives, 0 false negatives).

Why It Outperforms Traditional B-Trees

DimensionStandard BTreeMapPGM-Index (Learned)Concrete Hardware Impact
Index StructureDynamic nodes with pointersContiguous array of $(a, b, k_0)$ segmentsEntire index resides in CPU L1/L2 cache
Lookup Mechanism4–6 node hops across RAM1 affine math evaluation + local L1 searchEliminates unpredictable pointer chasing
Build Time$O(N \log N)$ repeated node rebalancing$O(N)$ single-pass linear streaming~22x faster build times
Memory Footprint~45 MB per 1,000,000 keys3.1 KB – 48 KB per 1,000,000 keys-99.89% to -99.99% memory reduction

Statistical Benchmark Suite (10-Run Rigorous Analysis)

All benchmarks were measured locally on x86_64 hardware using Rust 1.99 in --release mode. Each scenario was executed over 10 consecutive runs with distinct randomized seeds to eliminate CPU scheduling noise and warm-cache anomalies.

  • Dataset Size: 1,000,000 keys (64-bit integers)
  • Queries per Run: 100,000 queries (50% existing keys / hits, 50% non-existent keys / misses)

1. Dense Sequential Time-Series Data

Simulates monotonically increasing timestamps, network log sequences, or primary auto-increment keys.

Distribution: Dense Timestamp | Tolerance: epsilon = 32
Run #Build Time (BTree / PGM)Hit Latency (BTree / PGM)Miss Latency (BTree / PGM)Speedup (Hit)Segments
0177.7 ms / 3.1 ms288.3 ns / 116.2 ns14.1 ns / 0.9 ns2.48x93
0277.4 ms / 3.3 ms262.6 ns / 84.0 ns8.6 ns / 0.7 ns3.13x84
0372.4 ms / 3.1 ms263.4 ns / 70.0 ns8.7 ns / 0.6 ns3.76x81
0479.8 ms / 4.4 ms322.7 ns / 119.7 ns11.6 ns / 0.8 ns2.70x83
0577.2 ms / 3.1 ms282.8 ns / 78.2 ns10.8 ns / 0.6 ns3.62x84
0673.0 ms / 3.1 ms311.0 ns / 102.8 ns8.8 ns / 0.7 ns3.03x81
0775.4 ms / 4.6 ms323.7 ns / 103.5 ns17.9 ns / 0.9 ns3.13x81
0872.9 ms / 3.1 ms286.6 ns / 87.8 ns8.5 ns / 0.7 ns3.26x80
0976.1 ms / 3.6 ms309.3 ns / 126.6 ns9.0 ns / 1.2 ns2.44x83
1073.9 ms / 3.4 ms265.4 ns / 108.5 ns8.6 ns / 1.0 ns2.45x82
AVG75.57 ms / 3.49 ms291.6 ns / 99.7 ns10.7 ns / 0.8 ns3.00x83 segments
  • Compression Ratio: 1,000,000 keys compressed into 83 affine equations (12,048x factor).
  • Index Memory: 45.78 MB (BTreeMap) $\to$ 3.1 KB (PGM-Index) (-99.99%).
  • Hit Speedup: 3.00x faster average lookup.
  • Miss Speedup: 13.3x faster negative rejection.

2. Uniform Sparse Random Keys

Simulates randomly distributed 64-bit object IDs, hashed identifiers, and sparse primary keys.

Distribution: Uniform Sparse Random | Tolerance: epsilon = 16
MetricBTreeMap (Standard)PGM-Index (Learned)Improvement Factor
Mean Build Time76.01 ms3.34 ms22.8x faster build
Index-Only Memory45.78 MB48.1 KB-99.89% memory reduction
Segments CountN/A (thousands of nodes)1,406 segments711x compression
Mean Hit Latency264.6 ns/op89.4 ns/op2.98x faster (Min: 73.2 ns, Max: 109.9 ns)
Mean Miss Latency251.7 ns/op81.6 ns/op3.08x faster
Verification100.0% match100.0% matchZero discrepancies across 10 runs

3. Clustered Heavy-Tailed Lognormal Distribution

Simulates real-world power-law distributions (web traffic requests, financial transaction sizes, file size distributions).

Distribution: Lognormal Clustered | Tolerance: epsilon = 16
MetricBTreeMap (Standard)PGM-Index (Learned)Improvement Factor
Mean Build Time75.04 ms3.24 ms23.1x faster build
Index-Only Memory45.78 MB12.1 KB-99.97% memory reduction
Segments CountN/A455 segments2,197x compression
Mean Hit Latency260.2 ns/op81.3 ns/op3.21x faster (Min: 69.2 ns, Max: 92.1 ns)
Mean Miss Latency68.7 ns/op42.0 ns/op1.64x faster
Verification100.0% match100.0% matchZero discrepancies across 10 runs

Real-World Production Applications

1. Columnar OLAP Databases (ClickHouse, DuckDB, Parquet)

Analytical engines ingest massive sorted blocks. PGM-Index acts as a lightweight zone map replacement, locating record offsets across millions of rows with minimal CPU instruction overhead.

2. LSM-Tree Storage Engines (RocksDB, ScyllaDB, LevelDB)

In an LSM storage engine, SSTables written to NVMe are strictly immutable. Replacing traditional sparse block index tables with PGM segments allows billions of keys to be indexed entirely in host CPU cache or RAM, reducing NVMe read amplification to exactly 1 physical block I/O per query.

3. OS File Indexing & Cataloging

Fast local file indexers (e.g., Everything, NTFS USN Journal analyzers) can catalog tens of millions of records within a few megabytes of RAM while delivering sub-100ns path resolution.

4. High-Throughput Network Routing (FIB)

Forwarding Information Bases (FIB) at 100+ Gbps line rates require deterministic sub-microsecond packet IP classification where L1/L2 cache saturation would immediately induce packet drops.


Quickstart & Code Example

Add learned_index_lab to your Cargo.toml, or include pgm.rs directly in your project:

use pgm::PgmIndex;

fn main() {
    // 1. Prepare sorted data
    let data: Vec<u64> = vec![
        100, 105, 110, 115, 120, 250, 500, 1000, 1500, 2000, 5000, 10000
    ];

    // 2. Build the PGM index with maximum error epsilon (e.g. 16 or 32)
    let pgm = PgmIndex::build(data, 16);

    // 3. Point lookup (O(log S + log epsilon))
    match pgm.find(1500) {
        Some(index) => println!("Found key at position: {}", index),
        None => println!("Key not present in dataset"),
    }

    // 4. Inspect memory overhead
    println!("Total segments created: {}", pgm.segments.len());
    println!("Index-only memory: {} bytes", pgm.index_only_bytes());
}

Reproducibility & Verification

To verify the test suite and run the full 10-run statistical benchmark on your own machine:

# Clone the repository
git clone https://github.com/gilnett/learned_index_lab.git
cd learned_index_lab

# Run unit tests covering edge cases, gaps, and duplicates
cargo test

# Execute the 10-run release benchmark suite
cargo run --release

Resources & References

Primary Article & Technical Deep Dive

Seminal Research Papers

  • Kraska et al. (2018): “The Case for Learned Index Structures” (SIGMOD 2018) – arXiv:1712.01208. Seminal paper proving that sorted indexes can be modeled as cumulative distribution function (CDF) regressions.
  • Ferragina & Vinciguerra (2020): “The PGM-index: a data-structure with a guarantee on space and time efficiency” (VLDB 2020) – arXiv:1911.05496. Establishes optimal piecewise linear approximation (PLA) under bounded error corridors $\epsilon$.
  • Ferragina & Vinciguerra (2020): Reference C++ PGM implementation – GitHub: gvinciguerra/PGM-index.

License

Licensed under the Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0).