Unverified Commit 7640d0bd authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] hashing improvements to turbo-persistence (#90936)

## Summary

Reduces CPU overhead in turbo-persistence SST reads through three optimizations:

1. **Switch from `twox-hash` to `xxhash-rust`** — `twox_hash::XxHash3_64::with_seed(0)` heap-allocates a 192-byte secret buffer on every call. `xxhash_rust::xxh3::Xxh3Default::new()` is a `const fn` with zero allocation. Applied to both `turbo-persistence` and `turbo-tasks-hash`.

2. **Bulk `write()` in `KeyBase::hash` impls** — The hash implementations were feeding bytes one at a time via `write_u8()`, preventing xxh3 from using its optimized bulk ingestion path. Changed all slice-backed types (`&[u8]`, `[u8; N]`, `Vec<u8>`, `Box<[u8]>`) to use a single `state.write(slice)` call.

3. **Binary search improvements in SST lookups:**
   - **Index block lookup**: Replaced hand-rolled binary search with `as_chunks::<10>()` + stdlib `binary_search_by`, making the code simpler and leveraging the stdlib's optimized search.
   - **Duplicate key scans**: When collecting all entries with the same key (FIND_ALL mode), the backward/forward scans now use the binary search bounds (`l..m` and `m+1..r`) instead of scanning from `0` to `entry_count`. The binary search already proved entries outside these bounds are different, so this avoids unnecessary comparisons.
   - **`entry_matches_key` helper**: Equality checks during duplicate scans now use a dedicated function that avoids recomputing the full hash when no hash is stored in the block (block type 2/4). Previously `compare_hash_key` would call `hash_key()` to compute the full hash even when only an equality check was needed.

## Benchmark results

Compared against the `fixed_size_blocks` branch using `cargo bench -p turbo-persistence -- 'read/get/key_8'` (8-byte keys, 4-byte values):

| Benchmark | Change |
|-----------|--------|
| 10.67Mi/compacted/miss/cached | **-45%** |
| 10.67Mi/compacted/hit/cached | **-35%** |
| 10.67Mi/uncompacted/hit/cached | **-35%** |
| 10.67Mi/uncompacted/hit/uncached | **-22%** |
| 10.67Mi/uncompacted/miss/uncached | **-22%** |
| 10.67Mi/uncompacted/miss/cached | **-21%** |
| 10.67Mi/20commits/hit/cached | **-26%** |
| 10.67Mi/20commits/miss/* | -13% |
| 85.33Mi/compacted/hit/uncached | **-56%** |
| 85.33Mi/compacted/hit/cached | **-22%** |
| 85.33Mi/compacted/miss/* | **-22%** |
| 85.33Mi/uncompacted/hit/cached | -10% |
| 85.33Mi/20commits/hit/uncached | -12% |
| 85.33Mi/20commits/hit/cached | -6% |
| 85.33Mi/20commits/miss/* | -1 to -3% |

Largest wins on cached paths with smaller datasets where CPU cost (hashing, search) dominates over I/O.
parent c44558be
...@@ -4031,7 +4031,7 @@ version = "0.11.3" ...@@ -4031,7 +4031,7 @@ version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75761162ae2b0e580d7e7c390558127e5f01b4194debd6221fd8c207fc80e3f5" checksum = "75761162ae2b0e580d7e7c390558127e5f01b4194debd6221fd8c207fc80e3f5"
dependencies = [ dependencies = [
"twox-hash 1.6.3", "twox-hash",
] ]
[[package]] [[package]]
...@@ -6452,7 +6452,7 @@ checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d" ...@@ -6452,7 +6452,7 @@ checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d"
dependencies = [ dependencies = [
"byteorder", "byteorder",
"derive_more 0.99.18", "derive_more 0.99.18",
"twox-hash 1.6.3", "twox-hash",
] ]
[[package]] [[package]]
...@@ -9470,7 +9470,7 @@ dependencies = [ ...@@ -9470,7 +9470,7 @@ dependencies = [
"tracing", "tracing",
"turbo-bincode", "turbo-bincode",
"turbo-tasks-malloc", "turbo-tasks-malloc",
"twox-hash 2.1.2", "xxhash-rust",
] ]
[[package]] [[package]]
...@@ -9733,7 +9733,7 @@ dependencies = [ ...@@ -9733,7 +9733,7 @@ dependencies = [
"data-encoding", "data-encoding",
"sha2", "sha2",
"turbo-tasks-macros", "turbo-tasks-macros",
"twox-hash 2.1.2", "xxhash-rust",
] ]
[[package]] [[package]]
...@@ -10505,15 +10505,6 @@ dependencies = [ ...@@ -10505,15 +10505,6 @@ dependencies = [
"static_assertions", "static_assertions",
] ]
[[package]]
name = "twox-hash"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c"
dependencies = [
"rand 0.9.0",
]
[[package]] [[package]]
name = "typeid" name = "typeid"
version = "1.0.3" version = "1.0.3"
......
...@@ -475,7 +475,7 @@ tokio-util = { version = "0.7.13", features = ["io", "rt"] } ...@@ -475,7 +475,7 @@ tokio-util = { version = "0.7.13", features = ["io", "rt"] }
tracing = "0.1.37" tracing = "0.1.37"
tracing-subscriber = "0.3.16" tracing-subscriber = "0.3.16"
triomphe = { git = "https://github.com/sokra/triomphe", branch = "sokra/unstable" } triomphe = { git = "https://github.com/sokra/triomphe", branch = "sokra/unstable" }
twox-hash = { version = "2.1.2", features = ["std", "xxhash3_64", "xxhash3_128"] } xxhash-rust = { version = "0.8.12", features = ["xxh3"] }
unsize = "1.1.0" unsize = "1.1.0"
unty = "0.0.4" unty = "0.0.4"
url = "2.2.2" url = "2.2.2"
......
...@@ -33,7 +33,7 @@ smallvec = { workspace = true } ...@@ -33,7 +33,7 @@ smallvec = { workspace = true }
thread_local = { workspace = true } thread_local = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
turbo-bincode= { workspace = true } turbo-bincode= { workspace = true }
twox-hash = { workspace = true } xxhash-rust = { workspace = true }
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true } criterion = { workspace = true }
......
...@@ -22,9 +22,7 @@ impl KeyBase for &'_ [u8] { ...@@ -22,9 +22,7 @@ impl KeyBase for &'_ [u8] {
} }
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
for item in *self { state.write(self);
state.write_u8(*item);
}
} }
} }
...@@ -38,9 +36,7 @@ impl<const N: usize> KeyBase for [u8; N] { ...@@ -38,9 +36,7 @@ impl<const N: usize> KeyBase for [u8; N] {
} }
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
for item in self { state.write(self);
state.write_u8(*item);
}
} }
} }
...@@ -54,9 +50,7 @@ impl KeyBase for Vec<u8> { ...@@ -54,9 +50,7 @@ impl KeyBase for Vec<u8> {
} }
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
for item in self { state.write(self);
state.write_u8(*item);
}
} }
} }
...@@ -70,9 +64,7 @@ impl KeyBase for Box<[u8]> { ...@@ -70,9 +64,7 @@ impl KeyBase for Box<[u8]> {
} }
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
for item in self { state.write(self);
state.write_u8(*item);
}
} }
} }
...@@ -230,7 +222,7 @@ impl<T: StoreKey> StoreKey for &'_ T { ...@@ -230,7 +222,7 @@ impl<T: StoreKey> StoreKey for &'_ T {
/// Hashes a key with a fast, deterministic hash function. /// Hashes a key with a fast, deterministic hash function.
pub fn hash_key(key: &impl KeyBase) -> u64 { pub fn hash_key(key: &impl KeyBase) -> u64 {
let mut hasher = twox_hash::XxHash3_64::with_seed(0); let mut hasher = xxhash_rust::xxh3::Xxh3Default::new();
key.hash(&mut hasher); key.hash(&mut hasher);
hasher.finish() hasher.finish()
} }
......
...@@ -272,47 +272,19 @@ impl StaticSortedFile { ...@@ -272,47 +272,19 @@ impl StaticSortedFile {
/// Looks up a hash in a index block. /// Looks up a hash in a index block.
fn lookup_index_block(&self, mut block: &[u8], hash: u64) -> Result<u16> { fn lookup_index_block(&self, mut block: &[u8], hash: u64) -> Result<u16> {
let first_block = block.read_u16::<BE>()?; let first_block = block.read_u16::<BE>()?;
let entry_count = block.len() / 10; // Each entry is 10 bytes: 8 bytes for the hash, 2 bytes for the block index
if entry_count == 0 { let (entries, remainder) = block.as_chunks::<10>();
if entries.is_empty() {
return Ok(first_block); return Ok(first_block);
} }
let entries = block; if !remainder.is_empty() {
fn get_hash(entries: &[u8], index: usize) -> Result<u64> { bail!("invalid index block, {} extra bytes", remainder.len())
Ok((&entries[index * 10..]).read_u64::<BE>()?)
} }
fn get_block(entries: &[u8], index: usize) -> Result<u16> { match entries.binary_search_by(|entry| (&entry[..]).read_u64::<BE>().unwrap().cmp(&hash)) {
Ok((&entries[index * 10 + 8..]).read_u16::<BE>()?) Ok(i) => Ok((&entries[i][8..]).read_u16::<BE>()?),
Err(0) => Ok(first_block),
Err(i) => Ok((&entries[i - 1][8..]).read_u16::<BE>()?),
} }
let first_hash = get_hash(entries, 0)?;
match hash.cmp(&first_hash) {
Ordering::Less => {
return Ok(first_block);
}
Ordering::Equal => {
return get_block(entries, 0);
}
Ordering::Greater => {}
}
let mut l = 1;
let mut r = entry_count;
// binary search for the range
while l < r {
let m = (l + r) / 2;
let mid_hash = get_hash(entries, m)?;
match hash.cmp(&mid_hash) {
Ordering::Less => {
r = m;
}
Ordering::Equal => {
return get_block(entries, m);
}
Ordering::Greater => {
l = m + 1;
}
}
}
get_block(entries, l - 1)
} }
/// Looks up a key in a key block and the value in a value block. /// Looks up a key in a key block and the value in a value block.
...@@ -418,15 +390,14 @@ impl StaticSortedFile { ...@@ -418,15 +390,14 @@ impl StaticSortedFile {
// to collect all entries. The tombstone, if present, will be the // to collect all entries. The tombstone, if present, will be the
// last entry in the results. // last entry in the results.
let mut results = SmallVec::new(); let mut results = SmallVec::new();
// Backward scan: collect all entries before `m` with the same key for i in (l..m).rev() {
for i in (0..m).rev() {
let GetKeyEntryResult { let GetKeyEntryResult {
hash, hash,
key: entry_key, key: entry_key,
ty, ty,
val, val,
} = get_entry(i)?; } = get_entry(i)?;
if compare_hash_key(hash, entry_key, key_hash, key) != Ordering::Equal { if !entry_matches_key(hash, entry_key, key_hash, key) {
break; break;
} }
results.push(self.handle_key_match(ty, val, block, value_block_cache)?); results.push(self.handle_key_match(ty, val, block, value_block_cache)?);
...@@ -440,15 +411,14 @@ impl StaticSortedFile { ...@@ -440,15 +411,14 @@ impl StaticSortedFile {
// Add the entry at `m` // Add the entry at `m`
results.push(self.handle_key_match(ty, val, block, value_block_cache)?); results.push(self.handle_key_match(ty, val, block, value_block_cache)?);
// Forward scan: collect remaining entries with the same key for i in (m + 1)..r {
for i in (m + 1)..entry_count {
let GetKeyEntryResult { let GetKeyEntryResult {
hash, hash,
key: entry_key, key: entry_key,
ty, ty,
val, val,
} = get_entry(i)?; } = get_entry(i)?;
if compare_hash_key(hash, entry_key, key_hash, key) != Ordering::Equal { if !entry_matches_key(hash, entry_key, key_hash, key) {
break; break;
} }
results.push(self.handle_key_match(ty, val, block, value_block_cache)?); results.push(self.handle_key_match(ty, val, block, value_block_cache)?);
...@@ -921,6 +891,24 @@ fn compare_hash_key<K: QueryKey>( ...@@ -921,6 +891,24 @@ fn compare_hash_key<K: QueryKey>(
} }
} }
/// Checks if a query key equals an entry key, optionally comparing stored hashes first.
/// When a hash is stored (8 bytes), compares hashes before keys for speed.
/// When no hash is stored, compares keys directly (avoiding hash recomputation).
fn entry_matches_key<K: QueryKey>(
entry_hash: &[u8],
entry_key: &[u8],
full_hash: u64,
query_key: &K,
) -> bool {
if entry_hash.is_empty() {
// No hash stored - compare keys directly instead of recomputing hash
query_key.cmp(entry_key) == Ordering::Equal
} else {
// Hash stored - cheap 8-byte comparison first, then key comparison
full_hash.to_be_bytes()[..] == *entry_hash && query_key.cmp(entry_key) == Ordering::Equal
}
}
/// Returns the byte size of the value portion for a given key block entry type. /// Returns the byte size of the value portion for a given key block entry type.
fn entry_val_size(ty: u8) -> Result<usize> { fn entry_val_size(ty: u8) -> Result<usize> {
match ty { match ty {
......
...@@ -17,4 +17,4 @@ bincode = { workspace = true } ...@@ -17,4 +17,4 @@ bincode = { workspace = true }
data-encoding = { workspace = true } data-encoding = { workspace = true }
sha2 = { workspace = true } sha2 = { workspace = true }
turbo-tasks-macros = { workspace = true } turbo-tasks-macros = { workspace = true }
twox-hash = { workspace = true } xxhash-rust = { workspace = true }
use twox_hash::XxHash3_128; use std::hash::Hasher;
use xxhash_rust::xxh3::Xxh3Default;
use crate::{DeterministicHash, DeterministicHasher}; use crate::{DeterministicHash, DeterministicHasher};
...@@ -10,12 +12,12 @@ pub fn hash_xxh3_hash128<T: DeterministicHash>(input: T) -> u128 { ...@@ -10,12 +12,12 @@ pub fn hash_xxh3_hash128<T: DeterministicHash>(input: T) -> u128 {
} }
/// Xxh3Hash128 hasher. /// Xxh3Hash128 hasher.
pub struct Xxh3Hash128Hasher(XxHash3_128); pub struct Xxh3Hash128Hasher(Xxh3Default);
impl Xxh3Hash128Hasher { impl Xxh3Hash128Hasher {
/// Create a new hasher. /// Create a new hasher.
pub fn new() -> Self { pub fn new() -> Self {
Self(XxHash3_128::with_seed(0)) Self(Xxh3Default::new())
} }
/// Uses the DeterministicHash trait to hash the input in a /// Uses the DeterministicHash trait to hash the input in a
...@@ -32,7 +34,7 @@ impl Xxh3Hash128Hasher { ...@@ -32,7 +34,7 @@ impl Xxh3Hash128Hasher {
/// Finish the hash computation and return the digest. /// Finish the hash computation and return the digest.
pub fn finish(&self) -> u128 { pub fn finish(&self) -> u128 {
self.0.finish_128() self.0.digest128()
} }
} }
...@@ -42,7 +44,7 @@ impl DeterministicHasher for Xxh3Hash128Hasher { ...@@ -42,7 +44,7 @@ impl DeterministicHasher for Xxh3Hash128Hasher {
} }
fn write_bytes(&mut self, bytes: &[u8]) { fn write_bytes(&mut self, bytes: &[u8]) {
self.0.write(bytes); Xxh3Default::write(&mut self.0, bytes);
} }
} }
......
use std::hash::Hasher; use std::hash::Hasher;
use twox_hash::XxHash3_64; use xxhash_rust::xxh3::Xxh3Default;
use crate::{DeterministicHash, DeterministicHasher}; use crate::{DeterministicHash, DeterministicHasher};
...@@ -12,12 +12,12 @@ pub fn hash_xxh3_hash64<T: DeterministicHash>(input: T) -> u64 { ...@@ -12,12 +12,12 @@ pub fn hash_xxh3_hash64<T: DeterministicHash>(input: T) -> u64 {
} }
/// Xxh3Hash64 hasher. /// Xxh3Hash64 hasher.
pub struct Xxh3Hash64Hasher(XxHash3_64); pub struct Xxh3Hash64Hasher(Xxh3Default);
impl Xxh3Hash64Hasher { impl Xxh3Hash64Hasher {
/// Create a new hasher. /// Create a new hasher.
pub fn new() -> Self { pub fn new() -> Self {
Self(XxHash3_64::with_seed(0)) Self(Xxh3Default::new())
} }
/// Uses the DeterministicHash trait to hash the input in a /// Uses the DeterministicHash trait to hash the input in a
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment