kividb 1.2.1

A fast Redis®-compatible in-memory store written in Rust
Documentation
// src/replication/digest.rs
//
// A fingerprint of the whole dataset: what lets a replica that already holds
// what a restarted master holds carry on from it, rather than be sent all of
// it again.
//
// A master killed (rather than stopped) and started from its AOF cannot say
// where in its old stream its dataset stands, so its replicas used to be
// sent everything. Now it fingerprints its dataset as it starts, before any
// client is served, and keeps its new stream from there. A replica whose
// dataset has the same fingerprint holds exactly that, and is continued from
// the start of the new stream. Any difference at all — a write one of them
// has and the other has not — and the fingerprints differ, and the replica
// is sent everything as before.
//
// The fingerprint is a sum over keys, so it does not depend on the order in
// which keys are stored; members of hashes and sets, whose order also
// differs from node to node, are summed the same way.

use crate::store::ValueRef;
use xxhash_rust::xxh3::{Xxh3, xxh3_64};

fn value_digest(h: &mut Xxh3, value: crate::store::ValueRef<'_>) {
    match value {
        ValueRef::String(bytes) => {
            h.update(b"s");
            match crate::commands::hyperloglog::hll_cache_range(&bytes) {
                // A HyperLogLog's cached count is not part of its value:
                // each node fills it in when it counts (#28).
                Some(cache) => {
                    h.update(&bytes[..cache.start]);
                    h.update(&bytes[cache.end..]);
                }
                None => h.update(&bytes),
            }
        }
        ValueRef::List(list) => {
            h.update(b"l");
            for item in list.read().iter() {
                h.update(&(item.len() as u64).to_le_bytes());
                h.update(item);
            }
        }
        ValueRef::Hash(hash) => {
            h.update(b"h");
            let mut sum = 0u64;
            for (field, value) in hash.read().iter() {
                let mut e = Xxh3::new();
                e.update(&(field.len() as u64).to_le_bytes());
                e.update(field.as_bytes());
                e.update(value);
                sum = sum.wrapping_add(e.digest());
            }
            h.update(&sum.to_le_bytes());
        }
        ValueRef::Set(set) => {
            h.update(b"S");
            let sum = set
                .read()
                .iter()
                .fold(0u64, |sum, member| sum.wrapping_add(xxh3_64(member)));
            h.update(&sum.to_le_bytes());
        }
        ValueRef::SortedSet(zset) => {
            h.update(b"z");
            for (score, member) in zset.read().by_score.keys() {
                h.update(&score.to_bits().to_le_bytes());
                h.update(&(member.len() as u64).to_le_bytes());
                h.update(member);
            }
        }
        // The rest as they are laid out in a snapshot. Where that depends on
        // a node's own order, the fingerprints differ and the replica is
        // sent everything: never wrong, only slower.
        // After the four bytes an empty key was laid out as until #441, so
        // that a value's digest is what it was, on nodes of either version.
        other => {
            let mut laid_out = 0u32.to_le_bytes().to_vec();
            if crate::snapshot::write_kdb_value(&mut laid_out, other).is_ok() {
                h.update(b"o");
                h.update(&laid_out);
            }
        }
    }
}

/// `DEBUG DIGEST-VALUE`: a digest of one value, 40 hex digits as Redis's are
/// (Redis's are SHA-1), the same for equal values on any node and whatever
/// order their members are stored in. Only the value: not the key, nor its
/// time to live.
///
/// `redis-cli --cluster fix` compares a key's two copies with it when it
/// finds the key on two nodes, and answered `OK` it failed an assertion and
/// stopped half-way (#295).
pub fn value_hex(value: ValueRef<'_>) -> String {
    let mut h = Xxh3::new();
    value_digest(&mut h, value);
    format!("{:040x}", h.digest128())
}

/// The fingerprint of the dataset. Call with nothing writing to it: at
/// startup, or on a replica between syncs.
pub fn dataset_digest(store: &crate::store::Store) -> u64 {
    let threads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .clamp(1, 8);
    let mut total = 0u64;
    for (db_index, db) in store.iter().enumerate() {
        let shards: Vec<_> = db.iter().collect();
        let per = shards.len().div_ceil(threads).max(1);
        let keys_sum: u64 = std::thread::scope(|scope| {
            let handles: Vec<_> = shards
                .chunks(per)
                .map(|run| {
                    scope.spawn(move || {
                        let mut sum = 0u64;
                        for shard in run {
                            for entry in crate::read_lock!(shard).entries() {
                                let key = entry.key();
                                let mut h = Xxh3::new();
                                h.update(&(db_index as u64).to_le_bytes());
                                h.update(&(key.len() as u64).to_le_bytes());
                                h.update(key);
                                value_digest(&mut h, entry.value());
                                sum = sum.wrapping_add(h.digest());
                                // Its time to live, if it has one.
                                if let Some(ms) = entry.expires() {
                                    let mut h = Xxh3::new();
                                    h.update(b"ttl");
                                    h.update(&(db_index as u64).to_le_bytes());
                                    h.update(key);
                                    h.update(&ms.to_le_bytes());
                                    sum = sum.wrapping_add(h.digest());
                                }
                            }
                        }
                        sum
                    })
                })
                .collect();
            handles
                .into_iter()
                .map(|h| h.join().unwrap_or(0))
                .fold(0u64, u64::wrapping_add)
        });
        total = total.wrapping_add(keys_sum);
    }
    total
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::KiviDBValue;

    /// Equal values have one digest on any node, whatever their members'
    /// order; different values have different ones.
    #[test]
    fn a_values_digest_follows_the_value() {
        let a = crate::store::new_store(1);
        let b = crate::store::new_store(1);
        let set = |store: &crate::store::Store, k: &str, v: &str| {
            crate::write_lock!(crate::store::get_shard(&store[0], k)).insert_str(k, v.as_bytes());
        };
        set(&a, "k", "one");
        set(&b, "k", "one");
        set(&b, "other", "two");
        let hex = |store: &crate::store::Store, k: &str| {
            let shard = crate::store::get_shard(&store[0], k);
            let map = crate::read_lock!(shard);
            value_hex(map.get(k).unwrap())
        };
        assert_eq!(hex(&a, "k"), hex(&b, "k"));
        assert_ne!(hex(&b, "k"), hex(&b, "other"));
        assert_eq!(hex(&a, "k").len(), 40);
        assert!(hex(&a, "k").bytes().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn the_fingerprint_follows_the_data_not_its_order() {
        let a = crate::store::new_store(1);
        let b = crate::store::new_store(1);
        let set = |store: &crate::store::Store, k: &str, v: &str| {
            crate::write_lock!(crate::store::get_shard(&store[0], k)).insert_str(k, v.as_bytes());
        };
        for i in 0..100 {
            set(&a, &format!("k{i}"), "v");
        }
        for i in (0..100).rev() {
            set(&b, &format!("k{i}"), "v");
        }
        assert_eq!(dataset_digest(&a), dataset_digest(&b));
        set(&b, "k7", "w");
        assert_ne!(dataset_digest(&a), dataset_digest(&b));
        // A time to live is part of it.
        crate::write_lock!(crate::store::get_shard(&a[0], "k7")).insert_str("k7", b"w");
        assert_eq!(dataset_digest(&a), dataset_digest(&b));
        crate::write_lock!(crate::store::get_shard(&a[0], "k7")).set_expires("k7", 99);
        assert_ne!(dataset_digest(&a), dataset_digest(&b));
        crate::write_lock!(crate::store::get_shard(&b[0], "k7")).set_expires("k7", 99);
        assert_eq!(dataset_digest(&a), dataset_digest(&b));
    }

    /// A HyperLogLog's cached count is each node's own: two that differ only
    /// there are the same data (#28). Its registers are not.
    #[test]
    fn a_hyperloglogs_cached_count_is_not_part_of_the_fingerprint() {
        let (a, b) = (crate::store::new_store(1), crate::store::new_store(1));
        let hll = |cache: u8, register: u8| {
            let mut blob = vec![0u8; 16 + 12288];
            blob[..4].copy_from_slice(b"HYLL");
            blob[4] = 1;
            blob[8] = cache;
            blob[15] = if cache == 0 { 0x80 } else { 0 };
            blob[100] = register;
            KiviDBValue::String(crate::types::SharedBytes::from(blob.as_slice()))
        };
        let put = |store: &crate::store::Store, v: KiviDBValue| {
            crate::write_lock!(crate::store::get_shard(&store[0], "h")).insert("h", v);
        };
        put(&a, hll(0, 1));
        put(&b, hll(7, 1));
        assert_eq!(dataset_digest(&a), dataset_digest(&b));
        put(&b, hll(7, 2));
        assert_ne!(dataset_digest(&a), dataset_digest(&b));

        let sparse = |cache: u8, register: u8| {
            let mut blob = vec![0u8; 18];
            blob[..4].copy_from_slice(b"HYLL");
            blob[4] = 1;
            blob[8] = cache;
            blob[15] = if cache == 0 { 0x80 } else { 0 };
            blob[16] = 0x7f;
            blob[17] = register;
            KiviDBValue::String(crate::types::SharedBytes::from(blob.as_slice()))
        };
        put(&a, sparse(0, 0xff));
        put(&b, sparse(7, 0xff));
        assert_eq!(dataset_digest(&a), dataset_digest(&b));
        put(&b, sparse(7, 0xfe));
        assert_ne!(dataset_digest(&a), dataset_digest(&b));
    }
}