frozen_hash.rs

cdk-rsx/crates/cdk-rsx-collections-minima/src/frozen_hash.rs

frozen_hash.rs930 lines← SDK documentation
1//! Immutable exact dictionaries with two 4 KiB bucket choices.2//!3//! Construction is deliberately separate from lookup. A finite, caller-bounded4//! input is sorted, placed and independently checked before stable blocks are5//! allocated. Failed placements never become a collection descriptor.67const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("frozen_hash.rs");89use crate::{Collection, Error, Fixed, FixedKey, Result, Storage, Workspace};10use cdk_rsx_engine_nyxus::NyxusData;11use core::{cmp::Ordering, marker::PhantomData};1213const NODE_BYTES: usize = 4096;14const HEADER_BYTES: usize = 8;15const NODES_PER_BLOCK: u64 = 16;16const EMPTY: usize = usize::MAX;1718/// Finite admission and construction limits, including adversarial key sets.19#[derive(Clone, Copy, Debug)]20pub struct HashBuildConfig {21    pub max_entries: usize,22    /// Requested occupancy before rounding up to whole 64 KiB blocks, 1..=95.23    pub target_load_percent: u8,24    /// Saved with the table. No process-global or randomized hash state is used.25    pub seed: u64,26    /// Attempts at each size. Each attempt visits each input at most once.27    pub reseed_attempts: u8,28    /// Maximum doublings after the initial size.29    pub max_growth_steps: u8,30    pub max_buckets: u64,31}3233impl Default for HashBuildConfig {34    fn default() -> Self {35        Self {36            max_entries: 16_777_216,37            target_load_percent: 90,38            seed: 0x6d69_6e69_6d61_0001,39            reseed_attempts: 4,40            max_growth_steps: 3,41            max_buckets: 1_048_576,42        }43    }44}4546#[derive(Clone, Copy, Debug, Eq, PartialEq)]47pub struct HashBuildStats {48    pub entries: u64,49    pub buckets: u64,50    pub bucket_capacity: usize,51    pub primary_entries: u64,52    pub attempts: u32,53    pub growth_steps: u8,54}5556/// Move-only Nyxus descriptor. All entry bytes live in its exclusive blocks.57pub struct FrozenHashMap<K: FixedKey, V: Fixed> {58    collection: Collection,59    len: u64,60    buckets: u64,61    seed: u64,62    primary_entries: u64,63    attempts: u32,64    growth_steps: u8,65    types: PhantomData<(K, V)>,66}6768// SAFETY: Collection owns retained authority and its block directory. The other69// fields are inline integers and a zero-sized type marker; no decoded K or V,70// transient allocation, callback, or borrowed workspace is persisted.71unsafe impl<K: FixedKey, V: Fixed> NyxusData for FrozenHashMap<K, V> {72    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;73}7475impl<K: FixedKey, V: Fixed> FrozenHashMap<K, V> {76    pub const CONTRACT: [u8; 32] = crate::contract(77        "minima-frozen-hash-map-v1",78        &[79            "4096-byte nodes; 8-byte count header; full fixed keys then values",80            "two distinct buckets; primary-first placement; sorted by FixedKey Ord",81            "seeded word hash v1; bounded reseed/double; exact verified coverage",82        ],83        &[84            crate::MINIMA_POLICY,85            SOURCE_POLICY,86            K::CONTRACT,87            V::CONTRACT,88        ],89    );9091    /// Geometry is checked during monomorphization, before any builder runs.92    /// ```compile_fail93    /// use cdk_rsx_collections_minima::FrozenHashMap;94    /// const TOO_WIDE: usize = FrozenHashMap::<[u8; 4096], ()>::BUCKET_CAPACITY;95    /// ```96    pub const BUCKET_CAPACITY: usize = bucket_capacity(K::WIDTH, V::WIDTH);9798    /// Rejects duplicate keys; there is no order-dependent overwrite policy.99    ///100    /// The input and builder index are transient and bounded by `config`.101    /// Publication is moving the returned complete descriptor into owner Data.102    pub fn build(103        storage: &mut dyn Storage,104        entries: Vec<(K, V)>,105        config: HashBuildConfig,106        workspace: &mut Workspace,107    ) -> Result<Self> {108        Self::build_entries(109            storage,110            entries,111            config,112            workspace,113            |entry| &entry.0,114            |entry| &entry.1,115        )116    }117118    // Keep the caller's owned input allocation. A set supplies Vec<K> directly,119    // instead of allocating a second Vec<(K, ())> before placement starts.120    fn build_entries<T>(121        storage: &mut dyn Storage,122        mut entries: Vec<T>,123        config: HashBuildConfig,124        workspace: &mut Workspace,125        key_of: impl Fn(&T) -> &K,126        value_of: impl Fn(&T) -> &V,127    ) -> Result<Self> {128        let capacity = Self::BUCKET_CAPACITY;129        check_config(config, entries.len())?;130        entries.sort_unstable_by(|left, right| key_of(left).cmp(key_of(right)));131        if entries132            .windows(2)133            .any(|pair| key_of(&pair[0]) == key_of(&pair[1]))134        {135            return Err(Error::InvalidInput("duplicate frozen hash key"));136        }137        if entries.is_empty() {138            return Ok(Self {139                collection: Collection::new(storage)?,140                len: 0,141                buckets: 0,142                seed: config.seed,143                primary_entries: 0,144                attempts: 0,145                growth_steps: 0,146                types: PhantomData,147            });148        }149150        let mut buckets = initial_buckets(entries.len(), capacity, config.target_load_percent)?;151        let mut attempts = 0u32;152        for growth_steps in 0..=config.max_growth_steps {153            if buckets > config.max_buckets {154                return Err(Error::Capacity);155            }156            for reseed in 0..config.reseed_attempts {157                attempts += 1;158                let seed = attempt_seed(config.seed, growth_steps, reseed);159                let Some(placement) = place(&entries, buckets, capacity, seed, workspace, &key_of)?160                else {161                    continue;162                };163                verify(&entries, &placement, seed, workspace, &key_of)?;164165                // No stable payload allocation occurs until the complete166                // transient plan has passed the independent coverage check.167                let mut collection = Collection::new(storage)?;168                collection.ensure_nodes(storage, buckets)?;169                for bucket in 0..placement.counts.len() {170                    let count = placement.counts[bucket];171                    if count == 0 {172                        // Newly acquired blocks already contain the canonical173                        // empty header and zero payload, including reused blocks.174                        continue;175                    }176                    let node = workspace.bytes_mut();177                    node[..4].copy_from_slice(&(count as u32).to_le_bytes());178                    node[4..HEADER_BYTES].fill(0);179                    let values_at = HEADER_BYTES + capacity * K::WIDTH;180                    let end = if V::WIDTH == 0 {181                        HEADER_BYTES + count * K::WIDTH182                    } else {183                        node[HEADER_BYTES + count * K::WIDTH..values_at].fill(0);184                        values_at + count * V::WIDTH185                    };186                    for slot in 0..count {187                        let entry = &entries[placement.slots[bucket * capacity + slot]];188                        let at = HEADER_BYTES + slot * K::WIDTH;189                        key_of(entry).encode(&mut node[at..at + K::WIDTH]);190                        let at = HEADER_BYTES + capacity * K::WIDTH + slot * V::WIDTH;191                        value_of(entry).encode(&mut node[at..at + V::WIDTH]);192                    }193                    // Fixed encoders fill their complete occupied spans. The194                    // omitted node tail retains its initialized zero bytes.195                    collection.write_at(196                        storage,197                        bucket as u64 * NODE_BYTES as u64,198                        &node[..end],199                    )?;200                }201                return Ok(Self {202                    collection,203                    len: entries.len() as u64,204                    buckets,205                    seed,206                    primary_entries: placement.primary_entries,207                    attempts,208                    growth_steps,209                    types: PhantomData,210                });211            }212            if growth_steps != config.max_growth_steps {213                buckets = buckets.checked_mul(2).ok_or(Error::Capacity)?;214            }215        }216        Err(Error::Capacity)217    }218219    /// Exact lookup: no allocation and at most two whole aligned node fetches.220    pub fn get(221        &self,222        storage: &dyn Storage,223        key: &K,224        workspace: &mut Workspace,225    ) -> Result<Option<V>> {226        let Some(slot) = self.find_slot::<true>(storage, key, workspace)? else {227            return Ok(None);228        };229        let at = HEADER_BYTES + Self::BUCKET_CAPACITY * K::WIDTH + slot * V::WIDTH;230        V::decode(&workspace.bytes()[at..at + V::WIDTH]).map(Some)231    }232233    /// Look up arbitrary keys into their original caller-owned output positions.234    ///235    /// Requests are grouped by primary bucket, then primary misses are grouped236    /// by backup bucket. Each bucket is read once per pass; repeated keys still237    /// decode their values independently. All preparation is synchronous and238    /// uses one transient pair of bucket/index words per request. No stable239    /// bytes or borrowed values survive this call.240    ///241    /// Output length rejects before allocation, reads or output changes.242    /// Allocation failure returns Capacity. Later read/decode errors can leave243    /// completed output positions changed. Distant requests may not repay the244    /// grouping and sorting costs.245    pub fn get_many(246        &self,247        storage: &dyn Storage,248        keys: &[K],249        out: &mut [Option<V>],250        workspace: &mut Workspace,251    ) -> Result<()> {252        if keys.len() != out.len() {253            return Err(Error::InvalidInput("frozen hash batch output length"));254        }255        self.find_many::<true>(storage, keys, workspace, |index, slot, node| {256            out[index] = match slot {257                Some(slot) => {258                    let at = HEADER_BYTES + Self::BUCKET_CAPACITY * K::WIDTH + slot * V::WIDTH;259                    Some(V::decode(&node[at..at + V::WIDTH])?)260                }261                None => None,262            };263            Ok(())264        })265    }266267    fn find_many<const VALUES: bool>(268        &self,269        storage: &dyn Storage,270        keys: &[K],271        workspace: &mut Workspace,272        mut emit: impl FnMut(usize, Option<usize>, &[u8; NODE_BYTES]) -> Result<()>,273    ) -> Result<()> {274        if keys.is_empty() || self.len == 0 {275            self.collection.validate(storage)?;276            for index in 0..keys.len() {277                emit(index, None, workspace.bytes())?;278            }279            return Ok(());280        }281        if keys.len() == 1 {282            let slot = self.find_slot::<VALUES>(storage, &keys[0], workspace)?;283            return emit(0, slot, workspace.bytes());284        }285        let mut requests = Vec::new();286        requests287            .try_reserve_exact(keys.len())288            .map_err(|_| Error::Capacity)?;289        for (index, key) in keys.iter().enumerate() {290            let hash = hash_key(key, self.seed, workspace);291            requests.push(BucketRequest {292                index,293                bucket: mix(hash) % self.buckets,294            });295        }296        requests.sort_unstable_by_key(|request| request.bucket);297        let misses =298            self.probe_many::<VALUES>(storage, keys, &mut requests, true, workspace, &mut emit)?;299        // Primary node views have ended before hashing can overwrite workspace.300        // Reuse the same allocation for misses; common primary hits need no301        // saved hash or backup computation.302        let requests = &mut requests[..misses];303        for request in requests.iter_mut() {304            let hash = hash_key(&keys[request.index], self.seed, workspace);305            request.bucket = backup_choice(hash, self.buckets, request.bucket);306        }307        requests.sort_unstable_by_key(|request| request.bucket);308        self.probe_many::<VALUES>(storage, keys, requests, false, workspace, &mut emit)?;309        Ok(())310    }311312    fn probe_many<const VALUES: bool>(313        &self,314        storage: &dyn Storage,315        keys: &[K],316        requests: &mut [BucketRequest],317        retry_misses: bool,318        workspace: &mut Workspace,319        emit: &mut impl FnMut(usize, Option<usize>, &[u8; NODE_BYTES]) -> Result<()>,320    ) -> Result<usize> {321        let mut cursor = 0;322        let mut misses = 0;323        while cursor < requests.len() {324            let bucket = requests[cursor].bucket;325            let mut end = cursor + 1;326            while end < requests.len() && requests[end].bucket == bucket {327                end += 1;328            }329            let node = self.read_bucket::<VALUES>(storage, bucket, workspace)?;330            let count = read_count(node, Self::BUCKET_CAPACITY)?;331            for at in cursor..end {332                let request = requests[at];333                let slot = search::<K>(node, &keys[request.index], count)?;334                if retry_misses && slot.is_none() {335                    // misses <= at: compaction cannot overwrite an unvisited336                    // request, even when every preceding request missed.337                    requests[misses] = request;338                    misses += 1;339                } else {340                    emit(request.index, slot, node)?;341                }342            }343            cursor = end;344        }345        Ok(misses)346    }347348    /// Find a key while leaving its bucket in the caller's workspace. Computing349    /// the backup choice is unnecessary for the usual primary-bucket hit.350    #[inline(always)]351    fn find_slot<const VALUES: bool>(352        &self,353        storage: &dyn Storage,354        key: &K,355        workspace: &mut Workspace,356    ) -> Result<Option<usize>> {357        if self.len == 0 {358            self.collection.validate(storage)?;359            return Ok(None);360        }361        let hash = hash_key(key, self.seed, workspace);362        let primary = mix(hash) % self.buckets;363        if let Some(slot) = self.probe_bucket::<VALUES>(storage, key, primary, workspace)? {364            return Ok(Some(slot));365        }366        self.probe_bucket::<VALUES>(367            storage,368            key,369            backup_choice(hash, self.buckets, primary),370            workspace,371        )372    }373374    #[inline(always)]375    fn probe_bucket<const VALUES: bool>(376        &self,377        storage: &dyn Storage,378        key: &K,379        bucket: u64,380        workspace: &mut Workspace,381    ) -> Result<Option<usize>> {382        let node = self.read_bucket::<VALUES>(storage, bucket, workspace)?;383        let count = read_count(node, Self::BUCKET_CAPACITY)?;384        search::<K>(node, key, count)385    }386387    #[inline(always)]388    fn read_bucket<'w, const VALUES: bool>(389        &self,390        storage: &dyn Storage,391        bucket: u64,392        workspace: &'w mut Workspace,393    ) -> Result<&'w [u8; NODE_BYTES]> {394        if VALUES {395            self.collection.read_node(storage, bucket, workspace)396        } else {397            // Membership needs the count and complete fixed key area, never a398            // value. One covering prefix read retains first-read eligibility.399            let span = HEADER_BYTES + Self::BUCKET_CAPACITY * K::WIDTH;400            self.collection.read_at(401                storage,402                bucket403                    .checked_mul(NODE_BYTES as u64)404                    .ok_or(Error::Capacity)?,405                &mut workspace.bytes_mut()[..span],406            )?;407            Ok(workspace.bytes())408        }409    }410411    pub fn contains_key(412        &self,413        storage: &dyn Storage,414        key: &K,415        workspace: &mut Workspace,416    ) -> Result<bool> {417        self.find_slot::<false>(storage, key, workspace)418            .map(|slot| slot.is_some())419    }420421    pub fn len(&self) -> u64 {422        self.len423    }424425    pub fn is_empty(&self) -> bool {426        self.len == 0427    }428429    pub fn block_count(&self) -> usize {430        self.collection.block_count()431    }432433    pub fn stats(&self) -> HashBuildStats {434        HashBuildStats {435            entries: self.len,436            buckets: self.buckets,437            bucket_capacity: Self::BUCKET_CAPACITY,438            primary_entries: self.primary_entries,439            attempts: self.attempts,440            growth_steps: self.growth_steps,441        }442    }443444    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {445        self.collection.retire(storage)446    }447}448449/// An exact set: the map's fixed value width is zero, without entry tags.450pub struct FrozenHashSet<K: FixedKey>(FrozenHashMap<K, ()>);451452// SAFETY: the sole field satisfies the complete retained descriptor contract.453unsafe impl<K: FixedKey> NyxusData for FrozenHashSet<K> {454    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;455}456457impl<K: FixedKey> FrozenHashSet<K> {458    pub const CONTRACT: [u8; 32] = crate::contract(459        "minima-frozen-hash-set-v1",460        &[],461        &[462            SOURCE_POLICY,463            crate::MINIMA_POLICY,464            FrozenHashMap::<K, ()>::CONTRACT,465        ],466    );467468    pub fn build(469        storage: &mut dyn Storage,470        keys: Vec<K>,471        config: HashBuildConfig,472        workspace: &mut Workspace,473    ) -> Result<Self> {474        FrozenHashMap::build_entries(storage, keys, config, workspace, |key| key, |_| &()).map(Self)475    }476477    pub fn contains(478        &self,479        storage: &dyn Storage,480        key: &K,481        workspace: &mut Workspace,482    ) -> Result<bool> {483        self.0.contains_key(storage, key, workspace)484    }485486    /// Exact membership in original request order, grouped by primary then487    /// backup bucket. Scratch/error behavior matches FrozenHashMap::get_many.488    /// Output length rejects before any reads, allocation or output changes.489    pub fn contains_many(490        &self,491        storage: &dyn Storage,492        keys: &[K],493        out: &mut [bool],494        workspace: &mut Workspace,495    ) -> Result<()> {496        if keys.len() != out.len() {497            return Err(Error::InvalidInput("frozen hash batch output length"));498        }499        self.0500            .find_many::<false>(storage, keys, workspace, |index, slot, _| {501                out[index] = slot.is_some();502                Ok(())503            })504    }505506    pub fn len(&self) -> u64 {507        self.0.len()508    }509510    pub fn is_empty(&self) -> bool {511        self.0.is_empty()512    }513514    pub fn block_count(&self) -> usize {515        self.0.block_count()516    }517518    pub fn stats(&self) -> HashBuildStats {519        self.0.stats()520    }521522    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {523        self.0.retire(storage)524    }525}526527const fn bucket_capacity(key: usize, value: usize) -> usize {528    assert!(key != 0, "frozen hash keys must have positive fixed width");529    let Some(stride) = key.checked_add(value) else {530        panic!("frozen hash fixed stride overflow");531    };532    assert!(533        stride <= NODE_BYTES - HEADER_BYTES,534        "frozen hash entry exceeds one node"535    );536    (NODE_BYTES - HEADER_BYTES) / stride537}538539fn check_config(config: HashBuildConfig, entries: usize) -> Result<()> {540    if entries > config.max_entries {541        return Err(Error::Capacity);542    }543    if !(1..=95).contains(&config.target_load_percent)544        || config.reseed_attempts == 0545        || config.max_buckets < NODES_PER_BLOCK546        || !config.max_buckets.is_multiple_of(NODES_PER_BLOCK)547    {548        return Err(Error::InvalidInput("frozen hash build limits"));549    }550    Ok(())551}552553fn initial_buckets(entries: usize, capacity: usize, load: u8) -> Result<u64> {554    let numerator = (entries as u64).checked_mul(100).ok_or(Error::Capacity)?;555    let denominator = (capacity as u64) * u64::from(load);556    let nodes = numerator.div_ceil(denominator).max(2);557    nodes558        .div_ceil(NODES_PER_BLOCK)559        .checked_mul(NODES_PER_BLOCK)560        .ok_or(Error::Capacity)561}562563fn attempt_seed(seed: u64, growth: u8, reseed: u8) -> u64 {564    mix(seed.wrapping_add((u64::from(growth) << 8) | u64::from(reseed)))565}566567// This is an explicitly frozen, deterministic noncryptographic word hash.568// Construction checks actual placement; it assumes no probabilistic guarantee569// about an untrusted input chosen with knowledge of the saved seed.570fn mix(mut word: u64) -> u64 {571    word ^= word >> 30;572    word = word.wrapping_mul(0xbf58_476d_1ce4_e5b9);573    word ^= word >> 27;574    word = word.wrapping_mul(0x94d0_49bb_1331_11eb);575    word ^ (word >> 31)576}577578fn hash_key<K: FixedKey>(key: &K, seed: u64, workspace: &mut Workspace) -> u64 {579    let encoded = &mut workspace.bytes_mut()[..K::WIDTH];580    key.encode(encoded);581    let mut hash = seed ^ (K::WIDTH as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);582    let mut words = encoded.chunks_exact(8);583    for word in &mut words {584        hash = hash.wrapping_add(u64::from_le_bytes(word.try_into().unwrap()));585        hash = hash.rotate_left(27).wrapping_mul(0x3c79_ac49_2ba7_b653);586    }587    let mut tail = [0; 8];588    tail[..words.remainder().len()].copy_from_slice(words.remainder());589    hash ^ u64::from_le_bytes(tail)590}591592fn backup_choice(hash: u64, buckets: u64, primary: u64) -> u64 {593    let mut backup = mix(hash ^ 0xd1b5_4a32_d192_ed03) % buckets;594    if backup == primary {595        backup = (backup + 1) % buckets;596    }597    backup598}599600#[cfg(test)]601fn choices<K: FixedKey>(key: &K, seed: u64, buckets: u64, workspace: &mut Workspace) -> (u64, u64) {602    let hash = hash_key(key, seed, workspace);603    let primary = mix(hash) % buckets;604    (primary, backup_choice(hash, buckets, primary))605}606607struct Placement {608    slots: Vec<usize>,609    counts: Vec<usize>,610    capacity: usize,611    primary_entries: u64,612}613614#[derive(Clone, Copy)]615struct BucketRequest {616    index: usize,617    bucket: u64,618}619620fn filled<T: Clone>(len: usize, value: T) -> Result<Vec<T>> {621    let mut values = Vec::new();622    values.try_reserve_exact(len).map_err(|_| Error::Capacity)?;623    values.resize(len, value);624    Ok(values)625}626627fn place<K: FixedKey, T>(628    entries: &[T],629    buckets: u64,630    capacity: usize,631    seed: u64,632    workspace: &mut Workspace,633    key_of: &impl Fn(&T) -> &K,634) -> Result<Option<Placement>> {635    let buckets = usize::try_from(buckets).map_err(|_| Error::Capacity)?;636    let slots = buckets.checked_mul(capacity).ok_or(Error::Capacity)?;637    let mut placement = Placement {638        slots: filled(slots, EMPTY)?,639        counts: filled(buckets, 0)?,640        capacity,641        primary_entries: 0,642    };643    for (entry, item) in entries.iter().enumerate() {644        let hash = hash_key(key_of(item), seed, workspace);645        let primary = (mix(hash) % buckets as u64) as usize;646        let bucket = if placement.counts[primary] < capacity {647            placement.primary_entries += 1;648            primary649        } else {650            let backup = backup_choice(hash, buckets as u64, primary as u64) as usize;651            if placement.counts[backup] == capacity {652                return Ok(None);653            }654            backup655        };656        let slot = bucket * capacity + placement.counts[bucket];657        placement.slots[slot] = entry;658        placement.counts[bucket] += 1;659    }660    Ok(Some(placement))661}662663fn verify<K: FixedKey, T>(664    entries: &[T],665    placement: &Placement,666    seed: u64,667    workspace: &mut Workspace,668    key_of: &impl Fn(&T) -> &K,669) -> Result<()> {670    if placement.capacity == 0671        || placement.counts.len().checked_mul(placement.capacity) != Some(placement.slots.len())672    {673        return Err(Error::Corrupt("frozen hash placement dimensions"));674    }675    let mut seen = filled(entries.len(), false)?;676    let mut covered = 0usize;677    let mut primary_entries = 0u64;678    for (bucket, &count) in placement.counts.iter().enumerate() {679        if count > placement.capacity {680            return Err(Error::Corrupt("frozen hash placement count"));681        }682        let mut previous: Option<&K> = None;683        for slot in 0..count {684            let entry = placement.slots[bucket * placement.capacity + slot];685            if entry >= entries.len() || seen[entry] {686                return Err(Error::Corrupt("frozen hash placement coverage"));687            }688            let key = key_of(&entries[entry]);689            if previous.is_some_and(|previous| previous >= key) {690                return Err(Error::Corrupt("frozen hash placement ordering"));691            }692            previous = Some(key);693            let hash = hash_key(key, seed, workspace);694            let buckets = placement.counts.len() as u64;695            let primary = mix(hash) % buckets;696            if bucket as u64 != primary && bucket as u64 != backup_choice(hash, buckets, primary) {697                return Err(Error::Corrupt("frozen hash placement choice"));698            }699            primary_entries += u64::from(bucket as u64 == primary);700            seen[entry] = true;701            covered += 1;702        }703    }704    if covered != entries.len() || primary_entries != placement.primary_entries {705        return Err(Error::Corrupt("frozen hash placement coverage"));706    }707    Ok(())708}709710fn read_count(node: &[u8; NODE_BYTES], capacity: usize) -> Result<usize> {711    let count = u32::from_le_bytes(node[..4].try_into().unwrap()) as usize;712    if count > capacity {713        return Err(Error::Corrupt("frozen hash bucket count"));714    }715    Ok(count)716}717718fn search<K: FixedKey>(node: &[u8; NODE_BYTES], key: &K, count: usize) -> Result<Option<usize>> {719    let mut left = 0;720    let mut right = count;721    while left < right {722        let middle = left + (right - left) / 2;723        let at = HEADER_BYTES + middle * K::WIDTH;724        match K::decode(&node[at..at + K::WIDTH])?.cmp(key) {725            Ordering::Less => left = middle + 1,726            Ordering::Greater => right = middle,727            Ordering::Equal => return Ok(Some(middle)),728        }729    }730    Ok(None)731}732733#[cfg(test)]734mod tests {735    use super::*;736737    fn entry_key(entry: &(u64, u64)) -> &u64 {738        &entry.0739    }740741    #[test]742    fn grouped_backup_probes_preserve_every_payload_and_duplicate_position() -> Result<()> {743        let mut storage = crate::Arena::format(cdk_rsx_platform::memory::VecMemory::new())?;744        let mut buffer = crate::NodeBuffer::new();745        let mut workspace = buffer.workspace();746        let seed = attempt_seed(42, 0, 0);747        let entries: Vec<_> = (0..2_000_000u64)748            .filter(|key| choices(key, seed, 16, &mut workspace).0 == 0)749            .take(600)750            .map(|key| (key, !key))751            .collect();752        assert_eq!(entries.len(), 600);753        let config = HashBuildConfig {754            seed: 42,755            reseed_attempts: 1,756            max_growth_steps: 0,757            max_buckets: 16,758            ..HashBuildConfig::default()759        };760        let map = FrozenHashMap::build(&mut storage, entries.clone(), config, &mut workspace)?;761        let set = FrozenHashSet::build(762            &mut storage,763            entries.iter().map(|entry| entry.0).collect(),764            config,765            &mut workspace,766        )?;767        assert_eq!(768            map.stats().primary_entries,769            FrozenHashMap::<u64, u64>::BUCKET_CAPACITY as u64770        );771        assert_eq!(772            set.stats().primary_entries,773            FrozenHashMap::<u64, ()>::BUCKET_CAPACITY as u64774        );775        let mut keys: Vec<_> = entries.iter().rev().map(|entry| entry.0).collect();776        keys.extend([entries[0].0, entries[599].0, u64::MAX, u64::MAX]);777        let mut values = vec![None; keys.len()];778        let mut present = vec![false; keys.len()];779        map.get_many(&storage, &keys, &mut values, &mut workspace)?;780        set.contains_many(&storage, &keys, &mut present, &mut workspace)?;781        for ((key, actual), present) in keys.iter().zip(values).zip(present) {782            assert_eq!(actual, (*key != u64::MAX).then_some(!key));783            assert_eq!(present, *key != u64::MAX);784        }785        drop(map);786        drop(set);787        assert_eq!(storage.root().allocated_blocks(), 0);788        Ok(())789    }790791    fn adversarial_entries(workspace: &mut Workspace) -> Vec<(u64, u64)> {792        let seed = attempt_seed(42, 0, 0);793        let needed = FrozenHashMap::<u64, u64>::BUCKET_CAPACITY * 2 + 1;794        let mut colliding = Vec::new();795        for key in 0..2_000_000u64 {796            if choices(&key, seed, 16, workspace) == (0, 1) {797                colliding.push((key, !key));798                if colliding.len() == needed {799                    break;800                }801            }802        }803        assert_eq!(colliding.len(), needed);804        colliding805    }806807    #[test]808    fn coverage_verifier_rejects_missing_duplicate_and_illegal_placements() -> Result<()> {809        let entries: Vec<_> = (0..700u64).map(|key| (key, !key)).collect();810        let mut workspace_buffer = cdk_rsx_engine_minima::NodeBuffer::new();811        let mut workspace = workspace_buffer.workspace();812        let seed = attempt_seed(13, 0, 0);813        let mut plan = place(&entries, 16, 255, seed, &mut workspace, &entry_key)?.unwrap();814        verify(&entries, &plan, seed, &mut workspace, &entry_key)?;815816        let nonempty: Vec<_> = plan817            .counts818            .iter()819            .enumerate()820            .filter_map(|(bucket, count)| (*count > 0).then_some(bucket))821            .collect();822        let bucket = nonempty[0];823        let entry = plan.slots[bucket * plan.capacity];824        plan.counts[bucket] -= 1;825        assert!(verify(&entries, &plan, seed, &mut workspace, &entry_key).is_err());826        plan.counts[bucket] += 1;827828        let second = plan.slots[bucket * plan.capacity + 1];829        plan.slots[bucket * plan.capacity + 1] = entry;830        assert!(verify(&entries, &plan, seed, &mut workspace, &entry_key).is_err());831        plan.slots[bucket * plan.capacity + 1] = second;832833        let (primary, backup) = choices(&entries[entry].0, seed, 16, &mut workspace);834        let illegal = (0..16)835            .find(|bucket| *bucket != primary && *bucket != backup)836            .unwrap() as usize;837        let target = illegal * plan.capacity + plan.counts[illegal];838        let saved = plan.slots[target];839        plan.slots[target] = entry;840        plan.counts[illegal] += 1;841        assert!(verify(&entries, &plan, seed, &mut workspace, &entry_key).is_err());842        plan.slots[target] = saved;843        plan.counts[illegal] -= 1;844        verify(&entries, &plan, seed, &mut workspace, &entry_key)845    }846847    #[test]848    fn adversarial_pair_exceeds_capacity_and_reseeding_can_change_choices() -> Result<()> {849        let capacity = FrozenHashMap::<u64, u64>::BUCKET_CAPACITY;850        let mut workspace_buffer = cdk_rsx_engine_minima::NodeBuffer::new();851        let mut workspace = workspace_buffer.workspace();852        let seed = attempt_seed(42, 0, 0);853        let colliding = adversarial_entries(&mut workspace);854        assert!(place(&colliding, 16, capacity, seed, &mut workspace, &entry_key)?.is_none());855        let new_seed = attempt_seed(42, 0, 1);856        let repaired = place(857            &colliding,858            16,859            capacity,860            new_seed,861            &mut workspace,862            &entry_key,863        )?864        .unwrap();865        verify(&colliding, &repaired, new_seed, &mut workspace, &entry_key)866    }867868    #[test]869    fn failed_build_publishes_nothing_and_successful_retry_keeps_exact_values() -> Result<()> {870        use cdk_rsx_platform::memory::{Memory, VecMemory};871        let mut storage = crate::Arena::format(VecMemory::new())?;872        let mut workspace_buffer = cdk_rsx_engine_minima::NodeBuffer::new();873        let mut workspace = workspace_buffer.workspace();874        let existing = FrozenHashMap::build(875            &mut storage,876            vec![(7u64, 91u64)],877            HashBuildConfig::default(),878            &mut workspace,879        )?;880        let blocks = storage.root().allocated_blocks();881        let physical_bytes = storage.with_memory(Memory::len);882        let colliding = adversarial_entries(&mut workspace);883        let config = HashBuildConfig {884            seed: 42,885            reseed_attempts: 1,886            max_growth_steps: 0,887            max_buckets: 16,888            ..HashBuildConfig::default()889        };890        assert!(matches!(891            FrozenHashMap::build(&mut storage, colliding.clone(), config, &mut workspace),892            Err(Error::Capacity)893        ));894        assert_eq!(storage.root().allocated_blocks(), blocks);895        assert_eq!(storage.with_memory(Memory::len), physical_bytes);896        assert_eq!(existing.get(&storage, &7, &mut workspace)?, Some(91));897898        let repaired = FrozenHashMap::build(899            &mut storage,900            colliding.clone(),901            HashBuildConfig {902                reseed_attempts: 2,903                ..config904            },905            &mut workspace,906        )?;907        assert_eq!(repaired.stats().attempts, 2);908        for (key, value) in &colliding {909            assert_eq!(repaired.get(&storage, key, &mut workspace)?, Some(*value));910        }911        let grown = FrozenHashMap::build(912            &mut storage,913            colliding.clone(),914            HashBuildConfig {915                max_growth_steps: 1,916                max_buckets: 32,917                ..config918            },919            &mut workspace,920        )?;921        assert_eq!(grown.stats().attempts, 2);922        assert_eq!(grown.stats().growth_steps, 1);923        assert_eq!(grown.stats().buckets, 32);924        assert_eq!(grown.len(), colliding.len() as u64);925        for (key, value) in &colliding {926            assert_eq!(grown.get(&storage, key, &mut workspace)?, Some(*value));927        }928        Ok(())929    }930}