folly SpookyHashV2 — fast non-crypto hash
한 줄 요약:
SpookyHashV2는 Bob Jenkins의 빠른 non-cryptographic hash다. F14의 기본 hasher 후보로 분포·속도 모두 좋고, 결정적이라 sharding에도 쓸 수 있다.
#동기
좋은 hash 함수는 다음 셋을 만족해야 한다.
- 빠르다 — 입력 byte당 처리 비용이 작다.
- 분포가 좋다 — avalanche test, χ² test 통과.
- 결정적 — 같은 입력에 같은 출력.
std::hash는 1만 만족. Fingerprint64는 1,2,3 모두 OK지만 느림. SpookyHashV2는 셋 다 충족하면서 가장 빠른 축에 든다.
대략적 throughput (단일 코어, 큰 입력) std::hash (구현체 의존, 보통 ~1 GB/s) Fingerprint64 ~ 1.5 GB/s SpookyHashV2 ~ 6 GB/s xxHash3 ~ 10 GB/s (SIMD) WyHash ~ 8 GB/s Crypto (SHA-2) ~ 0.5 GB/sSpookyHash는 SIMD 없이도 ARX(Add-Rotate-XOR) 연산만으로 6 GB/s를 낸다. instruction-level parallelism이 잘 풀린다.
#API
#include <folly/hash/SpookyHashV2.h>
// one-shotuint64_t h = folly::hash::SpookyHashV2::Hash64( data, len, /*seed=*/0);
uint32_t h32 = folly::hash::SpookyHashV2::Hash32(data, len, 0);
void Hash128Pair(const void* data, size_t len, uint64_t* h1, uint64_t* h2) { folly::hash::SpookyHashV2::Hash128(data, len, h1, h2);}
// streamingfolly::hash::SpookyHashV2 spooky;spooky.Init(seed1, seed2);spooky.Update(part1, len1);spooky.Update(part2, len2);uint64_t h1, h2;spooky.Final(&h1, &h2);세 가지 출력 크기 (32/64/128) 모두 같은 알고리즘에서 derive. 64-bit가 일반.
#알고리즘 — ARX
state: 12 x uint64_t (96 byte)
매 96-byte 블록 마다: for i in 0..12: state[i] += input[i] state[(i+11)%12] ^= state[(i+2)%12] state[(i+1)%12] = ROL(state[(i+1)%12], rotConst[i]) state[i] += state[(i+1)%12]operation:
- Add —
state[i] += input[i] - Rotate —
state[i] = ROL(state[i], k) - XOR —
state[i] ^= state[j]
세 가지 모두 1-cycle 명령. 12-word state가 register pressure에 맞고 ILP가 최대.
#내부 구현
// folly/hash/SpookyHashV2.cpp 약식void SpookyHashV2::Update(const void* msg, size_t len) { // 1. accumulate to internal buffer until 96-byte aligned // 2. process 96-byte blocks directly // 3. save remainder while (len >= sc_blockSize) { // 96 bytes Mix(reinterpret_cast<const uint64_t*>(p), h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11); p += sc_blockSize; len -= sc_blockSize; } std::memcpy(remainder_, p, len);}
static void Mix(const uint64_t* d, uint64_t& h0, uint64_t& h1, /* ... */) { h0 += d[0]; h2 ^= h10; h11 ^= h0; h0 = Rot64(h0, 11); h11 += h1; h1 += d[1]; h3 ^= h11; h0 ^= h1; h1 = Rot64(h1, 32); h0 += h2; // ... 12회 repeat}Mix가 12 line으로 펼쳐져 inline. compiler가 register에 다 올린다.
#F14의 hasher로
struct MyKey { uint64_t a, b; };
namespace folly {template <>struct hasher<MyKey> { size_t operator()(const MyKey& k) const noexcept { return hash::SpookyHashV2::Hash64(&k, sizeof(k), 0); }};}
folly::F14FastMap<MyKey, V> m;F14는 H1/H2 분리를 위해 hash quality가 높을수록 좋다. SpookyHashV2는 avalanche가 좋아 H2 7-bit이 거의 균등 분포. SIMD compare의 hit rate가 최대화된다.
기본 std::hash도 쓸 수 있지만 lower bit 분포가 약하면 H2가 편향돼 SIMD 가속 효과가 떨어진다.
#std와의 비교
| 항목 | std::hash | SpookyHashV2 | xxHash3 | WyHash |
|---|---|---|---|---|
| 결정성 | X | O | O | O |
| 큰 입력 throughput | 보통 | 6 GB/s | 10 GB/s | 8 GB/s |
| 작은 입력 (≤16 byte) | 빠름 | 빠름 | 빠름 | 매우 빠름 |
| avalanche | 구현체 의존 | 좋음 | 좋음 | 좋음 |
| seed | 보통 X | O | O | O |
| 표준 | C++ | folly | 외부 | 외부 |
가장 빠른 비-cryptographic hash는 xxHash3 또는 WyHash. SpookyHash는 folly 안에서 일관성과 결정성을 동시 제공.
#Cryptographic vs non-cryptographic
| 속성 | non-crypto | crypto |
|---|---|---|
| 충돌 발견 | adversary가 만들 수 있음 | computationally infeasible |
| preimage attack | 가능 | infeasible |
| 속도 | 매우 빠름 | 느림 |
| 사용처 | hash table, dedup, shard | password, MAC, integrity |
SpookyHashV2는 비-cryptographic. 사용자 입력을 신뢰할 수 없으면 (예: 외부에서 hash key를 보내고 충돌 attack을 시도) cryptographic hash 필요. fbcode에서는 internal RPC라 SpookyHash로 충분.
#코드 리뷰 포인트
- 외부 입력으로 hash key를 만드는 곳에 non-crypto hash — DoS 가능. Crypto hash 또는 random seed 매번.
std::hash결과를 sharding 키로 — 결정적이지 않음. SpookyHash 또는 Fingerprint.- F14 hasher가 trivial (identity 같은) — H2 분포 깨짐. SpookyHash 같은 quality hash.
- 작은 키 (≤16 byte)에 SpookyHash 한 번 — 오버헤드 클 수 있음. WyHash가 작은 키에 더 적합.
#자주 보는 안티패턴
// 1. seed를 매번 random — 결정성 잃음uint64_t h = SpookyHashV2::Hash64(data, len, std::random_device{}());// → seed 고정해야 다른 process에서 비교 가능
// 2. 32-bit truncate해서 사용uint32_t h32 = static_cast<uint32_t>(SpookyHashV2::Hash64(...));// → 32-bit이 필요하면 Hash32() 호출 (별도 mixing)
// 3. 동일 객체를 두 번 update (잘못된 incremental 사용)SpookyHashV2 s; s.Init(0, 0);s.Update(data, len);s.Final(&h1, &h2);s.Update(more, more_len); // 초기화 안 했음 — 의도 불명s.Final(&h1b, &h2b);#실전 — Bloom filter
class BloomFilter { std::vector<uint64_t> bits_; size_t k_; // hash 개수
void add(folly::ByteRange data) { uint64_t h1, h2; folly::hash::SpookyHashV2::Hash128(data.data(), data.size(), &h1, &h2); // double hashing trick — h1 + i*h2 for (size_t i = 0; i < k_; ++i) { size_t bit = (h1 + i * h2) % (bits_.size() * 64); bits_[bit / 64] |= (uint64_t(1) << (bit % 64)); } }};SpookyHashV2의 128-bit 결과를 둘로 쪼개 double hashing. 한 hash 계산으로 k개의 가짜 hash를 얻는다.
#정리
SpookyHashV2는 ARX 기반 fast non-crypto hash, 6 GB/s.- 결정적 — 다른 머신에서 같은 결과.
- F14의 기본 hasher 후보로 분포가 좋다.
- cryptographic은 아님 — 외부 input에서 attack 우려시 별도 도구.
- 더 빠른 hash가 필요하면 xxHash3 / WyHash 외부.
#다음 편
Part 18로 넘어가 init, Indestructible, MicroLock류를 본다.
#관련 항목
Folly Code Review · 76 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
folly Fingerprint64·128 — 분산 hash
Fingerprint의 polynomial Rabin-Karp 기반 hash — sharding, dedup, content addressing.
같은 시리즈에서 이어 읽기
fbcode 패턴 모음 — folly 사용의 실전
Meta fbcode 코드 리뷰에서 반복적으로 등장하는 folly 사용 패턴 — overview + 시리즈 마무리.
같은 시리즈에서 이어 읽기
folly::observer — hot config의 atomic refresh
folly::observer — read mostly 값의 atomic refresh, hot config·feature flag·LB weight 같은 패턴의 표준.
같은 시리즈에서 이어 읽기