ribbon.rs

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

ribbon.rs451 lines← SDK documentation
1// SPDX-License-Identifier: Apache-2.02//! Standard Ribbon static retrieval with a 64-bit contiguous coefficient band.3//!4//! Implements Algorithms 1–3 of Dietzfelbinger, Dillinger, Hübschle, Sanders and5//! Walzer, *Ribbon: Fast Succinct Static Retrieval and Approximate Membership*,6//! JACM 73(1), February 2026, DOI 10.1145/3785417:7//! <https://publikationen.bibliothek.kit.edu/1000191446/177619178>.8//! The Apache-2.0 BuRR reference was reviewed at revision9//! `2ba071ab728f77d1cebbd14d1f0b9381575730ab`:10//! <https://github.com/lorenzhs/BuRR>. Its authors are Lorenz Hübschle-Schneider11//! and Facebook, Inc. This implementation is written from the paper; it does12//! not port BuRR's bump thresholds, multilevel construction or compression.13//!14//! Every key selects **one contiguous band** of 64 random coefficients. An15//! incremental banded Gaussian elimination followed by back substitution solves16//! the assigned byte strings exactly. This is Standard Ribbon, not an XOR3 map,17//! a membership filter, or the succinct bumped variant BuRR. Nonmembers return18//! arbitrary bytes; use a separate exact membership index when required.19//!20//! Values have 1–64 bytes, fixed at compilation. Unused rows are zero. Two21//! domain-separated, saved-seed XXH64 hashes select the start and coefficients22//! (the lowest coefficient is forced to one). This intentionally differs from23//! the reference hash and interleaved layout. Rows never straddle 4 KiB nodes;24//! node-tail padding and the mandatory whole-block allocation are extra space.25//! Queries fetch one minimum bounding span per touched node, at most two nodes.2627const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("ribbon.rs");2829use crate::hash::{XXH64_POLICY, Xxh64Word, xxh64};30use crate::{Collection, CollectionId, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};31use cdk_rsx_engine_nyxus::NyxusData;32use core::marker::PhantomData;3334const BAND: u32 = 64;35const COEFFICIENT_DOMAIN: u64 = 0xc1a4_32fe_77b8_09d5;3637/// Include this policy and the concrete `CONTRACT` in the owner's admission.38pub const RIBBON_POLICY: [u8; 32] = crate::contract(39    "MinimaStandardRibbon/band64/xxh64-two-domains/byte-rows/v1",40    &[],41    &[SOURCE_POLICY, crate::MINIMA_POLICY, XXH64_POLICY],42);4344#[derive(Clone, Copy, Debug)]45pub struct RibbonBuildConfig {46    pub max_entries: usize,47    pub max_rows: u32,48    pub max_attempts: u16,49    /// Extra vector backing, `rows * (8 + VALUE_BYTES)`. Excludes the consumed50    /// input Vec, allocator bookkeeping, node workspace and fixed stack.51    pub max_work_bytes: usize,52    /// Total occupied-pivot eliminations across all attempts. Other work is53    /// bounded by admitted entries, rows, attempts, the band and value width.54    pub max_reductions: u64,55    /// Paper epsilon in thousandths: rows = ceil(n/(1-epsilon)) + 63.56    /// Must be in 1..1000; construction may still exhaust its finite retries.57    pub slack_per_mille: u16,58    /// Initial SplitMix64 counter. The successful derived seed is persisted.59    pub seed: u64,60}61impl Default for RibbonBuildConfig {62    fn default() -> Self {63        Self {64            max_entries: 1_048_576,65            max_rows: 2_097_152,66            max_attempts: 16,67            max_work_bytes: 160 * 1024 * 1024,68            max_reductions: 128 * 1024 * 1024,69            slack_per_mille: 125,70            seed: 0x6d69_6e69_7269_6262,71        }72    }73}7475#[derive(Clone, Debug, PartialEq, Eq)]76pub enum RibbonBuildError {77    InvalidConfig,78    Capacity,79    WorkLimit,80    DuplicateKey,81    AttemptsExhausted { attempts: u16 },82    Storage(Error),83}84impl From<Error> for RibbonBuildError {85    fn from(error: Error) -> Self {86        Self::Storage(error)87    }88}89impl core::fmt::Display for RibbonBuildError {90    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {91        write!(f, "{self:?}")92    }93}94impl std::error::Error for RibbonBuildError {}95pub type RibbonBuildResult<T> = core::result::Result<T, RibbonBuildError>;9697#[derive(Clone, Copy, Debug, PartialEq, Eq)]98pub struct RibbonBuildStats {99    pub entries: u64,100    pub rows: u32,101    pub attempts: u16,102    pub reductions: u64,103    pub work_bytes: usize,104}105106/// Move-only retained descriptor. No original keys, values, builder, provider107/// or workspace are retained. Payload rows live in exclusive stable blocks.108#[repr(C)]109pub struct FrozenRibbon<K: FixedKey, const VALUE_BYTES: usize> {110    collection: Collection,111    entries: u64,112    seed: u64,113    reductions: u64,114    rows: u32,115    attempts: u16,116    key: PhantomData<fn() -> K>,117}118// SAFETY: Collection owns retained authority metadata; all other fields are119// inline integers or a zero-size marker. K and transient vectors are not saved.120unsafe impl<K: FixedKey, const V: usize> NyxusData for FrozenRibbon<K, V> {121    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;122}123124impl<K: FixedKey, const V: usize> FrozenRibbon<K, V> {125    const ROWS_PER_NODE: usize = NODE_BYTES / V;126    const GEOMETRY: () = {127        assert!(K::WIDTH <= NODE_BYTES, "Ribbon key exceeds workspace");128        assert!(V >= 1 && V <= 64, "Ribbon values require 1..=64 bytes");129    };130    pub const CONTRACT: [u8; 32] = {131        let () = Self::GEOMETRY;132        crate::width_contract(133            "MinimaFrozenRibbon/FixedKey/byte-value/v1",134            V,135            &[RIBBON_POLICY, K::CONTRACT],136        )137    };138139    /// Build and independently verify every original key before stable writes.140    /// Duplicate keys reject, even when their assigned values are equal.141    /// Expected rejection never changes any previously published collection.142    /// After stable writes begin, backend faults trap and rely on IC rollback.143    pub fn build(144        storage: &mut dyn Storage,145        mut entries: Vec<(K, [u8; V])>,146        config: RibbonBuildConfig,147        workspace: &mut Workspace,148    ) -> RibbonBuildResult<Self> {149        let () = Self::GEOMETRY;150        if config.max_attempts == 0 || !(1..1000).contains(&config.slack_per_mille) {151            return Err(RibbonBuildError::InvalidConfig);152        }153        if entries.len() > config.max_entries || entries.len() > u32::MAX as usize {154            return Err(RibbonBuildError::Capacity);155        }156        let rows = row_count(entries.len(), config.slack_per_mille)?;157        if rows > config.max_rows {158            return Err(RibbonBuildError::Capacity);159        }160        let work_bytes = work_bytes::<V>(rows)?;161        if work_bytes > config.max_work_bytes {162            return Err(RibbonBuildError::WorkLimit);163        }164        entries.sort_unstable_by(|left, right| left.0.cmp(&right.0));165        if entries.windows(2).any(|pair| pair[0].0 == pair[1].0) {166            return Err(RibbonBuildError::DuplicateKey);167        }168        let mut coefficients = zeroed(rows as usize, 0u64)?;169        let mut values = zeroed(rows as usize, [0u8; V])?;170        let mut counter = config.seed;171        let mut reductions = 0;172        let mut successful = None;173        for attempt in 1..=config.max_attempts {174            if entries.is_empty() {175                successful = Some((config.seed, 0));176                break;177            }178            let seed = next_seed(&mut counter);179            // The fallibly admitted scratch starts zeroed. Only a retry has180            // prior elimination state that must be cleared.181            if attempt > 1 {182                coefficients.fill(0);183                values.fill([0; V]);184            }185            let mut consistent = true;186            for (key, value) in &entries {187                let (start, coefficient) = equation(key, seed, rows, workspace);188                if !insert(189                    &mut coefficients,190                    &mut values,191                    start as usize,192                    coefficient,193                    *value,194                    &mut reductions,195                    config.max_reductions,196                )? {197                    consistent = false;198                    break;199                }200            }201            if !consistent {202                continue;203            }204            back_substitute(&coefficients, &mut values);205            // Re-encode the original keys independently of the inserted rows206            // and verify their complete assigned values, including all bits.207            for (key, expected) in &entries {208                let (start, coefficient) = equation(key, seed, rows, workspace);209                assert_eq!(210                    retrieve_rows(&values, start as usize, coefficient),211                    *expected,212                    "Ribbon construction verification failed"213                );214            }215            successful = Some((seed, attempt));216            break;217        }218        let (seed, attempts) = successful.ok_or(RibbonBuildError::AttemptsExhausted {219            attempts: config.max_attempts,220        })?;221        let mut collection = Collection::new(storage)?;222        collection.ensure_nodes(storage, (rows as u64).div_ceil(Self::ROWS_PER_NODE as u64))?;223        if NODE_BYTES.is_multiple_of(V) {224            // Rows are already their encoded bytes. The contiguous case needs225            // only one provider commit per physical block, with no node copy.226            collection227                .write_at(storage, 0, values.as_flattened())228                .unwrap_or_else(|error| panic!("Ribbon stable write failed: {error}"));229        } else {230            // Nondividing widths retain the original zero gap at every node.231            for (page, chunk) in values.chunks(Self::ROWS_PER_NODE).enumerate() {232                collection233                    .write_at(234                        storage,235                        page as u64 * NODE_BYTES as u64,236                        chunk.as_flattened(),237                    )238                    .unwrap_or_else(|error| panic!("Ribbon stable write failed: {error}"));239            }240        }241        Ok(Self {242            collection,243            entries: entries.len() as u64,244            seed,245            reductions,246            rows,247            attempts,248            key: PhantomData,249        })250    }251252    /// Move-publish a verified replacement. Peak space includes both owners.253    pub fn replace(254        &mut self,255        storage: &mut dyn Storage,256        entries: Vec<(K, [u8; V])>,257        config: RibbonBuildConfig,258        workspace: &mut Workspace,259    ) -> RibbonBuildResult<()> {260        self.collection.validate(storage)?;261        *self = Self::build(storage, entries, config, workspace)?;262        Ok(())263    }264265    /// Exact assigned bytes for an admitted key; arbitrary bytes for any other266    /// key. An empty retrieval returns zero bytes. This never tests membership.267    /// No allocation/cache/header fetch; at most two bounded node spans.268    pub fn retrieve(269        &self,270        storage: &dyn Storage,271        key: &K,272        workspace: &mut Workspace,273    ) -> Result<[u8; V]> {274        let () = Self::GEOMETRY;275        if self.entries == 0 {276            self.collection.validate(storage)?;277            return Ok([0; V]);278        }279        let (start, mut coefficient) = equation(key, self.seed, self.rows, workspace);280        let mut result = [0; V];281        while coefficient != 0 {282            let low = start as usize + coefficient.trailing_zeros() as usize;283            let page = low / Self::ROWS_PER_NODE;284            let page_end = ((page + 1) * Self::ROWS_PER_NODE).min(start as usize + BAND as usize);285            let bits = page_end - start as usize;286            let on_page = if bits >= 64 {287                coefficient288            } else {289                coefficient & ((1u64 << bits) - 1)290            };291            let high = start as usize + (63 - on_page.leading_zeros()) as usize;292            let offset = page as u64 * NODE_BYTES as u64 + (low % Self::ROWS_PER_NODE * V) as u64;293            let bytes = &mut workspace.bytes_mut()[..(high - low + 1) * V];294            self.collection.read_at(storage, offset, bytes)?;295            let mut selected = on_page;296            while selected != 0 {297                let row = start as usize + selected.trailing_zeros() as usize;298                for (out, byte) in result299                    .iter_mut()300                    .zip(&bytes[(row - low) * V..(row - low + 1) * V])301                {302                    *out ^= byte;303                }304                selected &= selected - 1;305            }306            coefficient ^= on_page;307        }308        Ok(result)309    }310311    pub const fn len(&self) -> u64 {312        self.entries313    }314    pub const fn is_empty(&self) -> bool {315        self.entries == 0316    }317    pub const fn identity(&self) -> CollectionId {318        self.collection.identity()319    }320    pub const fn seed(&self) -> u64 {321        self.seed322    }323    pub fn block_count(&self) -> usize {324        self.collection.block_count()325    }326    /// Useful solution bytes, excluding node padding and whole-block rounding.327    pub const fn solution_bytes(&self) -> u64 {328        self.rows as u64 * V as u64329    }330    pub fn stats(&self) -> RibbonBuildStats {331        RibbonBuildStats {332            entries: self.entries,333            rows: self.rows,334            attempts: self.attempts,335            reductions: self.reductions,336            work_bytes: work_bytes::<V>(self.rows).expect("admitted Ribbon work size"),337        }338    }339}340341fn row_count(entries: usize, slack: u16) -> RibbonBuildResult<u32> {342    if entries == 0 {343        return Ok(0);344    }345    let starts = (entries as u64 * 1000).div_ceil(u64::from(1000 - slack));346    u32::try_from(starts + u64::from(BAND - 1)).map_err(|_| RibbonBuildError::Capacity)347}348fn work_bytes<const V: usize>(rows: u32) -> RibbonBuildResult<usize> {349    (rows as usize)350        .checked_mul(8 + V)351        .ok_or(RibbonBuildError::WorkLimit)352}353fn zeroed<T: Copy>(len: usize, value: T) -> RibbonBuildResult<Vec<T>> {354    let mut result = Vec::new();355    result356        .try_reserve_exact(len)357        .map_err(|_| RibbonBuildError::WorkLimit)?;358    result.resize(len, value);359    Ok(result)360}361fn equation<K: FixedKey>(key: &K, seed: u64, rows: u32, workspace: &mut Workspace) -> (u32, u64) {362    let encoded = &mut workspace.bytes_mut()[..K::WIDTH];363    key.encode(encoded);364    let (position, coefficient) = if K::WIDTH == 8 {365        // The exact same encoded lane feeds both domain-separated hashes.366        let hash = Xxh64Word::new(u64::from_le_bytes((&*encoded).try_into().unwrap()));367        (hash.hash(seed), hash.hash(seed ^ COEFFICIENT_DOMAIN) | 1)368    } else {369        (370            xxh64(encoded, seed),371            xxh64(encoded, seed ^ COEFFICIENT_DOMAIN) | 1,372        )373    };374    let starts = rows - BAND + 1;375    let start = ((u128::from(position) * u128::from(starts)) >> 64) as u32;376    (start, coefficient)377}378fn next_seed(counter: &mut u64) -> u64 {379    *counter = counter.wrapping_add(0x9e37_79b9_7f4a_7c15);380    let mut value = *counter;381    value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);382    value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);383    value ^ (value >> 31)384}385fn insert<const V: usize>(386    coefficients: &mut [u64],387    values: &mut [[u8; V]],388    mut start: usize,389    mut coefficient: u64,390    mut value: [u8; V],391    reductions: &mut u64,392    max_reductions: u64,393) -> RibbonBuildResult<bool> {394    loop {395        if coefficients[start] == 0 {396            coefficients[start] = coefficient;397            values[start] = value;398            return Ok(true);399        }400        if *reductions == max_reductions {401            return Err(RibbonBuildError::WorkLimit);402        }403        *reductions += 1;404        coefficient ^= coefficients[start];405        for (out, byte) in value.iter_mut().zip(values[start]) {406            *out ^= byte;407        }408        if coefficient == 0 {409            return Ok(value.iter().all(|&byte| byte == 0));410        }411        let shift = coefficient.trailing_zeros();412        start += shift as usize;413        coefficient >>= shift;414    }415}416fn back_substitute<const V: usize>(coefficients: &[u64], values: &mut [[u8; V]]) {417    for start in (0..values.len()).rev() {418        if coefficients[start] == 0 {419            continue;420        }421        let mut coefficient = coefficients[start] & !1;422        let mut value = values[start];423        while coefficient != 0 {424            let row = start + coefficient.trailing_zeros() as usize;425            for (out, byte) in value.iter_mut().zip(values[row]) {426                *out ^= byte;427            }428            coefficient &= coefficient - 1;429        }430        values[start] = value;431    }432}433fn retrieve_rows<const V: usize>(434    values: &[[u8; V]],435    start: usize,436    mut coefficient: u64,437) -> [u8; V] {438    let mut result = [0; V];439    while coefficient != 0 {440        let row = start + coefficient.trailing_zeros() as usize;441        for (out, byte) in result.iter_mut().zip(values[row]) {442            *out ^= byte;443        }444        coefficient &= coefficient - 1;445    }446    result447}448449#[cfg(test)]450#[path = "ribbon_tests.rs"]451mod tests;