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.
Crate & Project Links
- GitHub Repository: Source code, issue tracker, and releases.
- Crates.io: Published Rust crate package.
- Docs.rs API Reference: Generated
rustdocAPI documentation. - Roadmap: Planned v0.5.0 milestones and SIMD/mmap roadmap.
- License (Apache-2.0): Open-source license terms.
References
Technical Articles & Deep Dives
- Why We’ve Been Indexing Data Wrong for 50 Years: Replacing B-Trees with Math in Rust: Architectural breakdown of CPU cache dynamics, the memory wall, mathematical CDF approximation, and real-world system implications of replacing pointer hierarchies with linear functions.
- Learned Indexes in Rust v0.2: Answering Reddit, Adding Range Queries, and Beating B-Trees: Community technical follow-up addressing memory overhead questions, implementing predecessor search (
lower_bound), slice scans, and expanding benchmark baselines.
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
- gvinciguerra/PGM-index: Official C++ reference implementation of the Piecewise Geometric Model index (University of Pisa, pgm.di.unipi.it).
- std::collections::BTreeMap: Rust Standard Library B-Tree implementation.
- slice::binary_search: Rust Standard Library core slice binary search.
- Algorithmica: Eytzinger Binary Search: Microarchitectural analysis of cache line alignment and branchless search.
Industry Storage Engines & Analytical Systems
- facebook/rocksdb: High-performance embedded key-value database using LSM-Trees and BlockBasedTable format.
- duckdb/duckdb: High-performance embedded analytical columnar database.
- ClickHouse/ClickHouse: High-performance columnar database management system for real-time analytics.
- apache/parquet-format: Open-source columnar storage format for deep nested and flat record data.
- scylladb/scylladb: Low-latency NoSQL columnar database written in C++.
- google/leveldb: Foundational LSM-Tree storage engine written by Sanjay Ghemawat and Jeff Dean.
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
Segmentstructs 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.
- Two contiguous
| Cache Line Slice | Struct Payload | Field Breakdown | Byte Range |
|---|---|---|---|
| Segment 0 | 24 bytes | key (8B) + slope (8B) + intercept (8B) | Bytes 0–23 |
| Segment 1 | 24 bytes | key (8B) + slope (8B) + intercept (8B) | Bytes 24–47 |
| Segment 2 (Partial) | 16 bytes | key (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:
segments: Vec<Segment>: Compact array containing only linear segment parameters.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
PgmIndexis 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 Dimension | Streaming Linear PLA (This Lab) | High-Order Polynomials / Splines | Deep Neural Networks (MLP / RBF) |
|---|---|---|---|
| Error Guarantees | Deterministic ± ε worst-case | Hard to bound strictly | No 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 Execution | 1 FMA instruction ($\sim 4$ cycles) | Multiple multiplies + division | Matrix GEMM / activation vector calls |
| Hardware Fit | Standard scalar registers | SIMD / AVX-512 register pressure | GPU / NPU accelerator required |
| Index Size | 24 bytes per segment | 48–96 bytes per spline node | Megabytes of weight matrices |
| Branch Predictor | 1 branchless local scan | Multiple branch checks | Model evaluation branching |
Rationale for Linear PLA
- 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.
- 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.
- 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
BTreeMapor branchless structures likeEytzingerprovide 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 Characteristic | Recommended Structure | Rationale |
|---|---|---|
| Frequent in-place mutations / OLTP | BTreeMap / B+Tree | Better suited for dynamic concurrent writes, page splits, and transaction management. |
| Immutable / Read-heavy sorted datasets (< 10M keys) | PgmIndex | Ideal for SSTables in LSM engines, Parquet columnar row groups, and static lookup tables. |
| Massive datasets (> 10M keys) where segments overflow L3 | MultilevelPgmIndex | Recursive PGM tree guarantees O(h * log eps) lookup without binary searching large segment arrays. |
| Irregular distributions / Extreme Pareto skew / Micro-bursts | BTreeMap / EytzingerSearch | Localized tree node caching and branchless binary search outperform linear approximation when segment counts explode. |
| Memory-constrained environments | PgmIndex / MultilevelPgmIndex | Reduces index metadata footprint by up to 14,700x (~5.7x total resident RAM) compared to pointer-based trees. |
| Batch ingestion / SSTable compaction | merge_sorted_batch | Merges sorted batches in O(N + M) and rebuilds streaming PLA segments at > 10M keys/sec. |
| Cache-friendly binary search | EytzingerSearch | Replaces standard slice::binary_search with branchless level-order traversal when duplicate data buffer is tolerable. |
| Zero extra memory allowed | slice::binary_search | In-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 / Topic | Summary Extract | Seminal Research & Full Paper |
|---|---|---|
| CDF Approximation in Learned Indexes | Models sorted keys as Empirical CDF regressions ($Pos(k) \approx N \times CDF(k)$) | CDF Theory Extract · Kraska et al. (SIGMOD 2018) · PDF |
| Optimal Streaming PLA | Single-pass $O(N)$ streaming slope corridor $[s_{\min}, s_{\max}]$ under bounded tolerance ± ε | Streaming PLA Extract · Ferragina & Vinciguerra (PVLDB 2020) · PDF |
| Duplicate Keys & Plateaus | Deterministic error bounding and segment splitting under duplicate runs ($dx = 0$) | Duplicates Guide · Ferragina & Vinciguerra (PVLDB 2020) |
| Epsilon Tuning & Cache Hierarchy | Microarchitectural hardware cache-line alignment, Pareto curves, and sizing guidelines | Epsilon Tuning Guide · Ferragina & Vinciguerra (PVLDB 2020) |
| Hierarchical Multilevel PGM | Recursive segment indexing ($O(\log N) \to O(h \cdot \log \epsilon)$) for large-scale datasets | Multilevel Extract · Ferragina & Vinciguerra (PVLDB 2020) · PDF |
| Batch Merge & Streaming Rebuild | Two-way sorted merge and $O(N + M)$ streaming PLA rebuild for SSTable workloads | Batch Merge Extract · Ferragina & Vinciguerra (PVLDB 2020) · PDF |
| Eytzinger (Breadth-First) Layout | Complete 1-based binary tree array layout with branchless cmov traversal | Eytzinger Extract · Khuong & Morin (ACM JEA 2017) · PDF |
| Bounded Local Search | Combines global segment binary search ($O(\log S)$) with local corridor scans ($O(\log \epsilon)$) | Bounded Search Extract · Ferragina & Vinciguerra (2020) · PDF |
| Learned Index Landscape & SOTA | Comparative matrix of PGM, RMI, ALEX, RadixSpline, FITing-Tree, and B+Tree | Landscape 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
- Seminal Paper: Kraska, T., Beutel, A., Chi, E. H., Dean, J., & Polyzotis, N. (2018). “The Case for Learned Index Structures”, ACM SIGMOD.
- MIT Data Systems Group: The Case for Learned Index Structures Overview
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):
-
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]$$
-
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
-
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.
-
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. -
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
- Foundational Paper: Ferragina, P., & Vinciguerra, G. (2020). “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”, Proceedings of the VLDB Endowment (PVLDB), 13(8): 1162–1175.
- Official PGM Project Site: https://pgm.di.unipi.it/
- C++ Reference Implementation: GitHub: gvinciguerra/PGM-index
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:
-
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}})$).
-
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))$$
-
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.
- Binary Search (
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
- Foundational Paper: Ferragina, P., & Vinciguerra, G. (2020). “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds”, PVLDB 13(8): 1162–1175.
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:
- Level 0 (Base Layer): Directly indexes the $N$ raw sorted data keys using base error tolerance ε₀, producing $S_0$ linear segments.
- 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.
- 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 Scale | Single-Level PgmIndex | MultilevelPgmIndex | Architectural 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 Touched | Cache Residency Profile |
|---|---|---|---|---|
| 4 | 9 keys | 72 B | ~1.1 lines | 100% L1-resident, but segments S explode |
| 8 | 17 keys | 136 B | ~2.1 lines | Fits across 2–3 L1 cache lines |
| 16 | 33 keys | 264 B | ~4.1 lines | Sweet spot for uniform/skewed data (100% L1) |
| 32 | 65 keys | 520 B | ~8.1 lines | Sweet spot for sequential/dense data (L1-resident) |
| 64 | 129 keys | 1,032 B | ~16.1 lines | Exceeds 1 KB; prefetcher saturation risk |
| 128 | 257 keys | 2,056 B | ~32.1 lines | Local search starts incurring L2 cache stalls |
| 256 | 513 keys | 4,104 B | ~64.1 lines | Local binary search branch mispredictions dominate |
Why ε ∈ [16, 32] is the Empirical Sweet Spot
- 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.
- Branch Misprediction Minimization: A local binary search over 33 elements requires at most ⌈log₂(33)⌉ = 6 branch comparisons, keeping pipeline flush penalties low.
- 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.
- Widens the slope corridor
- 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.
- Tightens the prediction corridor, narrowing the local search window (
Trade-off Regimes Across the ε Spectrum
| Regime | Segment 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 table | Fast (< 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
- 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.
- 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 Profile | Recommended ε | Rationale |
|---|---|---|
| Dense Sequential / Monotonic Logs | ε = 32 or 64 | High linearity allows extreme compression (e.g. 93 segments for 1M keys). Local scan over 65 elements remains 100% L1-resident. |
| Uniform Sparse Random Keys | ε = 16 | Balances moderate slope variance against local verification speed, yielding ~1,400 segments (48 KB). |
| Clustered / Skewed (Lognormal, Geospatial OSM) | ε = 16 | Restricts local verification latency in dense cluster pockets while preventing excessive segment fragmentation in sparse tails. |
| Micro-Bursts & Duplicate Heavy (Wiki-TS) | ε = 32 | Prevents identical key plateaus from constantly triggering corridor resets and segment splits. |
| Extreme Pareto Skew (Book ISBNs) | Classical B-Tree | Non-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:
- 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})$.
- If a duplicate run has length $L \le \varepsilon$, all points $(x_i, y_i)$ reside within vertical distance
- 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)$.
- When identical keys exceed
Summary of Duplicate Handling States
| Scenario | Condition | Segment Action | Slope Corridor Impact |
|---|---|---|---|
| Short Duplicate | dx == 0 and abs(y_i - y_0) <= ε | Absorbed into active segment | Preserved (no change) |
| Plateau Overflow | dx == 0 and abs(y_i - y_0) > ε | Finalize segment; anchor new segment | Reset 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.0prevents 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:
segments.binary_search_by_key(&target, |s| s.key)returns an index matchingtarget.- Because each segment covering the duplicate plateau was constructed with
dx = 0, its prediction evaluates toapprox = round(intercept). - The local search window
[approx - eps, approx + eps]is guaranteed to intersect the duplicate run inself.data. 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_boundlocates the earliest instance by checking boundary conditions at the edge of the bounded corridor.range(start..=end)locates the start bound withlower_bound(start)and the end bound withlower_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
BTreeMapWins: Because duplicate keys force frequent segment splitting, workloads dominated by massive duplicate runs experience reduced PGM compression ratios ($S$ grows). In such workloads,BTreeMaphandles 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
-
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.
-
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 Dimension | Dynamic 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 Write | Zero 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 Interference | Requires locks / latching or tree cow | Lock-free immutable snapshot reads |
Key Architectural Takeaways
-
Write Amplification on Small Batches: If an application requires frequent single-key insertions or random updates,
BTreeMapis overwhelmingly superior. Rebuilding a PGM index for small $M$ wastes millions of CPU cycles re-approximating unchanged regions. -
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.
-
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
khas left child at2kand right child at2k + 1.
Microarchitectural Advantages
- Cache Locality: The top levels of the search tree (which are accessed on every single query) reside permanently in CPU L1/L2 cache lines.
- 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
- Foundational Paper: Khuong, P.-V., & Morin, P. (2017). “Array Layouts for Comparison-Based Searching”, ACM Journal of Experimental Algorithmics (JEA), 22(1): 1–39.
- Algorithmica Tutorial: Eytzinger Binary Search Guide
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
| Architecture | Seminal Publication | Model Representation | Lookup Complexity | Space Bound Guarantee | In-Place Write Support |
|---|---|---|---|---|---|
Classical B+Tree / BTreeMap | Bayer & McCreight (1972); Comer (1979) | Multi-way pointer/node hierarchy | O(log_B N) | Worst-case 50% storage utilization | Fully dynamic (O(log_B N) rebalancing) |
| RMI (Recursive Model Index) | Kraska et al. (SIGMOD 2018) | Multi-stage staged regressions (Linear / Neural / Splines) | Variable / Empirical bounds | Heuristic (no formal worst-case bound) | Read-only (full retrain needed) |
| FITing-Tree | Galakatos et al. (SIGMOD 2019) | Piecewise linear segments indexed by classical B+Tree | O(log S + log ε) | Heuristic PLA bound | Dynamic via buffer / leaf shifts |
| PGM-Index | Ferragina & Vinciguerra (PVLDB 2020) | Optimal streaming PLA indexed recursively | O(h · log ε) or O(log S + log ε) | Provably optimal segment count for fixed ε | Read-heavy / Batch merge (O(N + M)) |
| RadixSpline | Kipf et al. (aiDM 2020) | Top radix lookup table + linear spline points | O(1 + log ε) | Bounded by spline points + 2^r radix table | Read-only (single-pass build) |
| ALEX | Ding et al. (SIGMOD 2020) | Adaptive gapped array nodes + linear models | O(log N) expected | Heuristic (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 / Dimension | B+Tree / BTreeMap | RMI | ALEX | RadixSpline | PGM-Index |
|---|---|---|---|---|---|
| Deterministic Error ± ε | Exact page boundaries | No (heuristic fallback) | No (gapped offsets) | Yes (± ε) | Yes (± ε provable) |
| Segment Count Optimality | N/A | Heuristic | Heuristic | Greedy heuristic | Provably optimal |
| Build Time Complexity | O(N log N) | O(N · epochs) | O(N log N) | O(N) single pass | O(N) single pass |
| Build Throughput | 2–5 M keys/s | 0.2–1 M keys/s | 1–4 M keys/s | > 20 M keys/s | 10–15 M keys/s |
| Index Metadata Overhead | High (15%–30%) | Low (< 1%) | Moderate (10%–25%) | Very Low (< 1%) | Minimal (< 0.1% to 0.01%) |
| In-Place Insertions | Native (O(log N)) | Not supported | Native (O(log N)) | Not supported | LSM / Batch Rebuild (O(N + M)) |
| Concurrent Writes | High (fine-grained latches) | None | Complex node locks | None | Reader-Writer lock on snapshot |
| Extreme Skew Resilience | Optimal | Poor | Moderate | Poor | Moderate to Poor |
| Hardware Fit | Memory latency bound | ALU bound | Cache & pointer bound | Memory latency bound | L1 cache bound (local scan) |
4. Workload Decision Guide
Select the indexing structure tailored to workload constraints:
-
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.
- Recommendation: Classical B+Tree /
-
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.
-
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.
-
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.
- Recommendation: PGM-Index (
-
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.
- Recommendation: Classical B+Tree /
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:
- Pre-Sorted Input: Vectors passed to constructors must be sorted in non-decreasing order (
data[i] <= data[i + 1]). - Deterministic Error Bounds: Every key’s predicted position is strictly bounded by $\pm \varepsilon$ around the true index.
- Zero Pointer Indirection: Segments and data arrays are contiguous memory buffers with zero runtime heap allocations during queries.
- Thread-Safe Read Concurrency: All index structures implement
SendandSync, allowing multi-threaded read sharing viaArc.
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
| Recipe | Target Topic | Primary APIs & Patterns |
|---|---|---|
| 1. Point & Range Queries | Exact matches, predecessors, and range scans | find, lower_bound, range, build |
| 2. Concurrent Read Scaling | Multi-core read parallelism without lock contention | Arc<PgmIndex>, std::thread, thread pools |
| 3. LSM SSTable Double-Buffering | Non-blocking compaction lifecycle in LSM engines | merge_sorted_batch, RwLock<Arc<PgmIndex>> |
| 4. Columnar Block Zone Maps | Sparse indexing for Parquet / ClickHouse blocks | Block boundaries, row-group pruning |
| 5. Operational Tuning & Monitoring | Production sizing, epsilon tuning, and health checks | Cache 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,rangeimmediately returns an empty slice&[]. - Out of Bounds: If
end_key > max_key,rangesafely truncates todata.len(). - Extreme Limits: Fully supports
u64::MIN(0) andu64::MAXwithout 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
- Zero Reader Downtime: Active lookups are never blocked by the CPU-intensive 2-way merge or segment construction.
- Deterministic Memory Footprint: The previous generation is freed automatically as soon as existing readers drop their cloned
Arcreferences. - 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 Tier | Best For |
|---|---|---|---|---|
| 8 | 17 keys (136 bytes) | ~2 cache lines | L1 Data Cache | Low-latency point lookups |
| 16 | 33 keys (264 bytes) | ~4 cache lines | L1 / L2 Cache | General-purpose default |
| 32 | 65 keys (520 bytes) | ~8 cache lines | L2 Cache | High-compression datasets |
| 64 | 129 keys (1032 bytes) | ~16 cache lines | L2 / L3 Cache | Ultra-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
| Metric | Calculation | Healthy Range | Degraded Signal | Recommended Action |
|---|---|---|---|---|
| Compression Ratio | N/S (keys per segment) | $> 100\times$ | $< 50\times$ | Increase $\varepsilon$ or evaluate key distribution skew |
| Index Metadata Size | pgm.metadata_bytes() | $< 1%$ of raw data | $> 5%$ of raw data | Switch to MultilevelPgmIndex |
| Lookup Latency | Mean 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
Arcwithout 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:
std::collections::BTreeMap: Rust standard library pointer-based dynamic search tree (B-Tree).Flat slice::binary_search: In-situ contiguous sorted slice binary search.EytzingerSearch: 1-based complete binary tree array layout with branchlesscmovtraversal.PgmIndex: Piecewise Geometric Model learned index with bounded linear approximation corridors.MultilevelPgmIndex: Hierarchical recursive PGM-Index with $O(h \cdot \log \epsilon)$ descent.
Benchmark Methodology
- Hardware Platform: x86_64, Windows, Rust
--releasemode. - 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:
| Structure | Raw Data Buffer (1M keys) | Index Metadata Overhead | Total Resident Memory | Mutation / Ingestion Model |
|---|---|---|---|---|
Flat Slice | 7.63 MB (10⁶ × 8 B) | 0.00 KB | 7.63 MB | Read-only (shift O(N)) |
Eytzinger (In-Situ) | 7.63 MB (level-order) | 0.00 KB | 7.63 MB | Read-only (rebuild required) |
Eytzinger (Index) | 7.63 MB (sorted source) | 7.63 MB (tree array) | 15.26 MB | Read-only (rebuild required) |
PgmIndex | 7.63 MB (10⁶ × 8 B) | 3.1 KB – 1.50 MB | 7.63 MB – 9.13 MB | Read-only (batch merge O(N+M)) |
MultilevelPgmIndex | 7.63 MB (10⁶ × 8 B) | 2.0 KB – 1.32 MB | 7.63 MB – 8.95 MB | Read-only (batch merge O(N+M)) |
BTreeMap | Embedded in heap nodes | ~45.78 MB (nodes + pointers) | 45.78 MB | Dynamic (in-place O(log N)) |
PgmIndexandMultilevelPgmIndexdo 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
BTreeMapon 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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 66.57 ms | 224.1 ns | 229.4 ns | 229.1 ns | 45.78 MB | 227.5 ns | 1.00x |
| Flat Slice | 0.00 ms | 168.2 ns | 139.4 ns | 122.7 ns | 0.00 KB | 143.4 ns | 1.33x |
| Eytzinger | 5.54 ms | 137.8 ns | 140.8 ns | 143.1 ns | 7.63 MB | 140.6 ns | 1.63x |
| PGM-Index | 4.64 ms | 107.1 ns | 101.0 ns | 132.0 ns | 3.1 KB | 113.4 ns | 2.09x |
| Multilevel PGM | 4.61 ms | 145.8 ns | 133.1 ns | 206.4 ns | 2.0 KB | 161.8 ns | 1.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 Slicerequires 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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 66.36 ms | 240.6 ns | 252.7 ns | 232.5 ns | 45.78 MB | 241.9 ns | 1.00x |
| Flat Slice | 0.00 ms | 152.5 ns | 133.0 ns | 135.5 ns | 0.00 KB | 140.4 ns | 1.58x |
| Eytzinger | 5.43 ms | 130.1 ns | 132.6 ns | 126.8 ns | 7.63 MB | 129.8 ns | 1.85x |
| PGM-Index | 5.16 ms | 126.3 ns | 115.0 ns | 137.9 ns | 48.1 KB | 126.4 ns | 1.91x |
| Multilevel PGM | 4.80 ms | 139.1 ns | 121.8 ns | 199.9 ns | 33.0 KB | 153.6 ns | 1.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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 65.83 ms | 227.6 ns | 228.7 ns | 228.1 ns | 45.78 MB | 228.1 ns | 1.00x |
| Flat Slice | 0.00 ms | 174.0 ns | 138.4 ns | 153.8 ns | 0.00 KB | 155.4 ns | 1.31x |
| Eytzinger | 5.35 ms | 132.9 ns | 130.7 ns | 131.8 ns | 7.63 MB | 131.8 ns | 1.71x |
| PGM-Index | 5.16 ms | 117.0 ns | 105.0 ns | 139.5 ns | 12.1 KB | 120.5 ns | 1.95x |
| Multilevel PGM | 5.12 ms | 154.8 ns | 131.9 ns | 215.0 ns | 10.8 KB | 167.2 ns | 1.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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 66.08 ms | 232.4 ns | 247.0 ns | 244.6 ns | 45.78 MB | 241.3 ns | 1.00x |
| Flat Slice | 0.00 ms | 151.3 ns | 132.6 ns | 136.2 ns | 0.00 KB | 140.1 ns | 1.54x |
| Eytzinger | 5.25 ms | 140.3 ns | 135.8 ns | 127.9 ns | 7.63 MB | 134.7 ns | 1.66x |
| PGM-Index | 5.11 ms | 119.9 ns | 123.2 ns | 151.8 ns | 192.1 KB | 131.6 ns | 1.94x |
| Multilevel PGM | 4.95 ms | 160.3 ns | 150.2 ns | 204.7 ns | 97.4 KB | 171.7 ns | 1.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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 36.32 ms | 111.1 ns | 104.2 ns | 108.7 ns | 45.78 MB | 108.0 ns | 1.00x |
| Flat Slice | 0.00 ms | 134.6 ns | 111.7 ns | 124.2 ns | 0.00 KB | 123.5 ns | 0.83x |
| Eytzinger | 5.30 ms | 131.9 ns | 124.5 ns | 137.2 ns | 7.63 MB | 131.2 ns | 0.84x |
| PGM-Index | 5.57 ms | 136.5 ns | 135.3 ns | 167.6 ns | 192.1 KB | 146.5 ns | 0.81x (slower) |
| Multilevel PGM | 4.86 ms | 153.9 ns | 197.7 ns | 209.6 ns | 152.3 KB | 187.1 ns | 0.72x (slower) |
- Key Takeaway:
BTreeMapis 1.35x faster thanPGM-Indexand 1.73x faster thanMultilevel 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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 11.34 ms | 37.3 ns | 26.0 ns | 41.5 ns | 45.78 MB | 34.9 ns | 1.00x |
| Flat Slice | 0.00 ms | 64.9 ns | 25.4 ns | 62.2 ns | 0.00 KB | 50.8 ns | 0.58x (slower) |
| Eytzinger | 5.34 ms | 58.6 ns | 32.4 ns | 59.8 ns | 7.63 MB | 50.3 ns | 0.64x (slower) |
| PGM-Index | 3.06 ms | 86.3 ns | 63.5 ns | 151.1 ns | 1.50 MB | 100.3 ns | 0.43x (2.87x slower) |
| Multilevel PGM | 3.33 ms | 144.2 ns | 115.3 ns | 201.2 ns | 1.32 MB | 153.6 ns | 0.26x (4.40x slower) |
- Key Takeaway:
BTreeMapsignificantly 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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Metadata | Moyenne Totale Latence | Speedup vs BTree | Total Memory (Data + Index) |
|---|---|---|---|---|---|---|---|---|
| BTreeMap | 52.08 ms | 178.8 ns | 181.3 ns | 180.7 ns | 45.78 MB | 180.3 ns | 1.00x | 45.78 MB |
| Flat Slice | 0.00 ms | 140.9 ns | 113.4 ns | 122.4 ns | 0.00 KB | 125.6 ns | 1.27x | 7.63 MB |
| Eytzinger | 5.37 ms | 122.0 ns | 116.2 ns | 121.1 ns | 7.63 MB | 119.7 ns | 1.47x | 15.26 MB |
| PGM-Index | 4.78 ms | 115.5 ns | 107.2 ns | 146.7 ns | 330.6 KB | 123.1 ns | 1.55x | 7.96 MB |
| Multilevel PGM | 4.61 ms | 149.7 ns | 141.7 ns | 206.1 ns | 274.5 KB | 165.8 ns | 1.19x | 7.90 MB |
Objective Architectural Findings
- No Universal Winner:
PGM-Indexis fastest on smooth, continuous, or moderately clustered distributions (Time-Series, Uniform, Lognormal, OSM), delivering up to 2.09x speedup overBTreeMapwith low metadata ($3.1\text{ KB} - 192\text{ KB}$).BTreeMapwins 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.EytzingerSearchprovides 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_searchremains 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.
- 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.
- Multilevel Scaling Limits at $10^6$ Keys:
- At $N = 10^6$,
MultilevelPgmIndexis slower than single-levelPgmIndex(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.
- At $N = 10^6$,
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
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)
| Dimension | Standard BTreeMap | Flat slice::binary_search | EytzingerSearch (Breadth-First) | PGM-Index (Learned Model) |
|---|---|---|---|---|
| Data Layout | Heap node hierarchy | Contiguous sorted slice | 1-based complete binary tree array | Compact array of $(a, b, k_0)$ segments |
| Lookup Mechanism | 4–6 pointer hops across heap | $\sim 20$ binary jumps across RAM | Branchless arithmetic traversal (k = 2k + bit) | In-register ALU prediction + bounded local scan |
| Cache Locality | Poor (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 Strength | Dynamic in-place mutations | Zero extra memory | Branchless search, cache friendly | Sub-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 / Target | Build Time | Hit Latency | Miss Latency | Lower Bound | Index Memory | Moyenne Totale Latence | Speedup vs BTree |
|---|---|---|---|---|---|---|---|
| BTreeMap | 84.12 ms | 314.4 ns | 331.4 ns | 350.0 ns | 45.78 MB | 331.9 ns | 1.00x |
| Flat Slice | 0.00 ms | 282.7 ns | 272.9 ns | 275.3 ns | 0.00 KB | 277.0 ns | 1.20x |
| Eytzinger | 6.30 ms | 163.7 ns | 160.9 ns | 169.2 ns | 7.63 MB | 164.6 ns | 2.02x |
| PGM-Index | 6.82 ms | 153.0 ns | 154.1 ns | 208.6 ns | 21.1 KB | 171.9 ns | 1.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
- Theoretical Foundations:
- CDF Approximation in Learned Indexes: Mathematical regression formulation.
- Optimal Streaming PLA: Single-pass bounded slope corridor algorithm.
- Eytzinger Layout: Complete binary tree array with branchless traversal.
- Bounded Local Search: In-register ALU bounds and local verification.
- Theory Index & Full Papers: Overview with direct links to academic publications.
- Benchmarks & Performance:
- Statistical Benchmarks (10-Run Matrix): Detailed results for Dense Time-Series, Uniform Sparse, and Heavy-Tailed Lognormal distributions.
- Architecture & Use Cases:
- Production Architecture & Real-World Use Cases: OLAP columnar zone maps, LSM-Tree NVMe cache residency, and decision matrices.
- Historical Archives:
References
Technical Articles & Deep Dives
- Why We’ve Been Indexing Data Wrong for 50 Years: Replacing B-Trees with Math in Rust: Architectural breakdown of CPU cache dynamics, the memory wall, mathematical CDF approximation, and real-world system implications of replacing pointer hierarchies with linear functions.
- Learned Indexes in Rust v0.2: Answering Reddit, Adding Range Queries, and Beating B-Trees: Community technical follow-up addressing memory overhead questions, implementing predecessor search (
lower_bound), slice scans, and expanding benchmark baselines.
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
- gvinciguerra/PGM-index: Official C++ reference implementation of the Piecewise Geometric Model index (University of Pisa, pgm.di.unipi.it).
- std::collections::BTreeMap: Rust Standard Library B-Tree implementation.
- slice::binary_search: Rust Standard Library core slice binary search.
- Algorithmica: Eytzinger Binary Search: Microarchitectural analysis of cache line alignment and branchless search.
Industry Storage Engines & Analytical Systems
- facebook/rocksdb: High-performance embedded key-value database using LSM-Trees and BlockBasedTable format.
- duckdb/duckdb: High-performance embedded analytical columnar database.
- ClickHouse/ClickHouse: High-performance columnar database management system for real-time analytics.
- apache/parquet-format: Open-source columnar storage format for deep nested and flat record data.
- scylladb/scylladb: Low-latency NoSQL columnar database written in C++.
- google/leveldb: Foundational LSM-Tree storage engine written by Sanjay Ghemawat and Jeff Dean.
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)
Note
Historical Archive: This document preserves the state of the documentation for v0.2.0 of
learned-index, which introduced comparison againstFlat 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).
- The foundational concept of Learned Index Structures was originated by Tim Kraska, Alex Beutel, Ed H. Chi, Jeffrey Dean, and Neoklis Polyzotis (MIT / Google) in their landmark paper “The Case for Learned Index Structures” (SIGMOD 2018).
- The Piecewise Geometric Model Index (PGM-index) and its optimal streaming piecewise linear approximation (PLA) algorithm were invented and proven by Paolo Ferragina and Giorgio Vinciguerra (University of Pisa) in “The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds” (PVLDB 2020) (arXiv:1910.06169, official site: pgm.di.unipi.it, C++ repository: gvinciguerra/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:
std::collections::BTreeMap: The standard library mutable, dynamic pointer-based search tree.Flat slice::binary_search: The standard library immutable baseline (contiguous array binary search).
| Dimension | Standard BTreeMap | Flat slice::binary_search | PGM-Index (Learned) | Microarchitectural Advantage |
|---|---|---|---|---|
| Index Structure | Dynamic nodes across heap | Contiguous raw buffer | Compact array of $(a, b, k_0)$ segments | Metadata fits entirely inside L1/L2 cache |
| Lookup Mechanism | 4–6 node hops across RAM | $\sim 20$ binary jumps across 8 MB | 1 in-register math eval + local 4 cache lines | Eliminates 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 ns | 3x 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
| Metric | BTreeMap | Flat slice::binary_search | PGM-Index (Learned) | Improvement Factor |
|---|---|---|---|---|
| Mean Build Time | 67.94 ms | 0.00 ms (pre-sorted) | 3.65 ms | 18.6x faster than BTree |
| Index-Only Memory | 45.78 MB | 0 KB | 3.1 KB | 14,700x compression |
| Mean Hit Latency | 221.8 ns/op | 152.7 ns/op | 63.5 ns/op | 3.50x vs BTree / 2.41x vs Slice |
| Mean Miss Latency | 10.0 ns/op | 23.7 ns/op | 0.7 ns/op | 14.3x faster negative rejection |
| Segments Count | N/A | N/A | 83 segments | 12,048x factor |
| Verification | 100.0% match | 100.0% match | 100.0% match | 0 discrepancies across 10 runs |
2. Uniform Sparse Random Keys
Distribution: Uniform Sparse Random | Tolerance: epsilon = 16
| Metric | BTreeMap | Flat slice::binary_search | PGM-Index (Learned) | Improvement Factor |
|---|---|---|---|---|
| Mean Build Time | 68.79 ms | 0.00 ms (pre-sorted) | 3.82 ms | 18.0x faster than BTree |
| Index-Only Memory | 45.78 MB | 0 KB | 48.1 KB | -99.89% memory reduction |
| Mean Hit Latency | 223.0 ns/op | 150.9 ns/op | 70.5 ns/op | 3.16x vs BTree / 2.14x vs Slice |
| Mean Miss Latency | 214.6 ns/op | 104.0 ns/op | 68.1 ns/op | 3.15x vs BTree / 1.53x vs Slice |
| Segments Count | N/A | N/A | 1,406 segments | 711x compression |
| Verification | 100.0% match | 100.0% match | 100.0% match | 0 discrepancies across 10 runs |
3. Clustered Heavy-Tailed Lognormal Distribution
Distribution: Lognormal Clustered | Tolerance: epsilon = 16
| Metric | BTreeMap | Flat slice::binary_search | PGM-Index (Learned) | Improvement Factor |
|---|---|---|---|---|
| Mean Build Time | 69.75 ms | 0.00 ms (pre-sorted) | 3.90 ms | 17.9x faster than BTree |
| Index-Only Memory | 45.78 MB | 0 KB | 12.1 KB | -99.97% memory reduction |
| Mean Hit Latency | 216.4 ns/op | 141.0 ns/op | 48.6 ns/op | 4.45x vs BTree / 2.90x vs Slice |
| Mean Miss Latency | 61.4 ns/op | 39.8 ns/op | 38.2 ns/op | 1.61x vs BTree / 1.04x vs Slice |
| Segments Count | N/A | N/A | 455 segments | 2,197x compression |
| Verification | 100.0% match | 100.0% match | 100.0% match | 0 discrepancies across 10 runs |
Learned Index Lab: Piecewise Geometric Model (PGM-Index) in Rust
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
- Mathematical Foundation
- Why It Outperforms Traditional B-Trees
- Statistical Benchmark Suite (10-Run Rigorous Analysis)
- Real-World Production Applications
- Quickstart & Code Example
- Reproducibility & Verification
- Resources & References
- License
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:
- Pointer Chasing: Navigating down a tree requires sequential memory dereferences across disparate memory addresses, causing recurring L1/L2/L3 cache misses.
- High Memory Overhead: Tree nodes require significant metadata per key (child pointers, balance factors, keys, values), consuming 30–50 bytes per entry.
- 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.
Bounded Local Search
During point lookup:
- The responsible segment is found via a rapid binary search across the segment array ($O(\log S)$ where $S \ll N$).
- The position estimate is computed directly via ALU instructions: $$\text{Pos}_{\text{approx}} = \text{round}(y_0 + s \cdot (k - x_0))$$
- 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
| Dimension | Standard BTreeMap | PGM-Index (Learned) | Concrete Hardware Impact |
|---|---|---|---|
| Index Structure | Dynamic nodes with pointers | Contiguous array of $(a, b, k_0)$ segments | Entire index resides in CPU L1/L2 cache |
| Lookup Mechanism | 4–6 node hops across RAM | 1 affine math evaluation + local L1 search | Eliminates 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 keys | 3.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 |
|---|---|---|---|---|---|
| 01 | 77.7 ms / 3.1 ms | 288.3 ns / 116.2 ns | 14.1 ns / 0.9 ns | 2.48x | 93 |
| 02 | 77.4 ms / 3.3 ms | 262.6 ns / 84.0 ns | 8.6 ns / 0.7 ns | 3.13x | 84 |
| 03 | 72.4 ms / 3.1 ms | 263.4 ns / 70.0 ns | 8.7 ns / 0.6 ns | 3.76x | 81 |
| 04 | 79.8 ms / 4.4 ms | 322.7 ns / 119.7 ns | 11.6 ns / 0.8 ns | 2.70x | 83 |
| 05 | 77.2 ms / 3.1 ms | 282.8 ns / 78.2 ns | 10.8 ns / 0.6 ns | 3.62x | 84 |
| 06 | 73.0 ms / 3.1 ms | 311.0 ns / 102.8 ns | 8.8 ns / 0.7 ns | 3.03x | 81 |
| 07 | 75.4 ms / 4.6 ms | 323.7 ns / 103.5 ns | 17.9 ns / 0.9 ns | 3.13x | 81 |
| 08 | 72.9 ms / 3.1 ms | 286.6 ns / 87.8 ns | 8.5 ns / 0.7 ns | 3.26x | 80 |
| 09 | 76.1 ms / 3.6 ms | 309.3 ns / 126.6 ns | 9.0 ns / 1.2 ns | 2.44x | 83 |
| 10 | 73.9 ms / 3.4 ms | 265.4 ns / 108.5 ns | 8.6 ns / 1.0 ns | 2.45x | 82 |
| AVG | 75.57 ms / 3.49 ms | 291.6 ns / 99.7 ns | 10.7 ns / 0.8 ns | 3.00x | 83 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
| Metric | BTreeMap (Standard) | PGM-Index (Learned) | Improvement Factor |
|---|---|---|---|
| Mean Build Time | 76.01 ms | 3.34 ms | 22.8x faster build |
| Index-Only Memory | 45.78 MB | 48.1 KB | -99.89% memory reduction |
| Segments Count | N/A (thousands of nodes) | 1,406 segments | 711x compression |
| Mean Hit Latency | 264.6 ns/op | 89.4 ns/op | 2.98x faster (Min: 73.2 ns, Max: 109.9 ns) |
| Mean Miss Latency | 251.7 ns/op | 81.6 ns/op | 3.08x faster |
| Verification | 100.0% match | 100.0% match | Zero 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
| Metric | BTreeMap (Standard) | PGM-Index (Learned) | Improvement Factor |
|---|---|---|---|
| Mean Build Time | 75.04 ms | 3.24 ms | 23.1x faster build |
| Index-Only Memory | 45.78 MB | 12.1 KB | -99.97% memory reduction |
| Segments Count | N/A | 455 segments | 2,197x compression |
| Mean Hit Latency | 260.2 ns/op | 81.3 ns/op | 3.21x faster (Min: 69.2 ns, Max: 92.1 ns) |
| Mean Miss Latency | 68.7 ns/op | 42.0 ns/op | 1.64x faster |
| Verification | 100.0% match | 100.0% match | Zero 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
- Why We’ve Been Indexing Data Wrong for 50 Years: Replacing B-Trees with Math in Rust: A comprehensive architectural breakdown exploring CPU cache dynamics, the memory wall, mathematical CDF approximation, and real-world system implications of replacing pointer hierarchies with linear functions.
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).