breadcrumb.rs

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

breadcrumb.rs668 lines← SDK documentation
1//! Breadcrumb Filter: unary mini-filters, prefix eviction and CRUMB overflow.2//!3//! Independent scalar implementation of Krapivin et al., *Breadcrumb Filters:4//! Fast Fully Featured Filters*, §§3–4, <https://doi.org/10.1145/3786629>.5//! The power-of-two C=2 construction is used: every primary bucket has two6//! reversible overflow destinations, and each overflow tag carries a two-bit7//! breadcrumb. It is not cuckoo hashing and does not relocate overflow entries.8//! Mini-filter unary metadata replaces SIMD-specific implementation machinery.9//!10//! Counts refer to the stored fingerprint multiset: colliding exact keys share11//! their reported count. Insert/remove transitions require an authoritative12//! exact multiset. A positive result never authorizes deletion. Backend mutation13//! errors trap, relying on IC rollback; Full is checked before any mutation.1415const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("breadcrumb.rs");1617use crate::hash::{XXH64_POLICY, hash_key};18use crate::{Collection, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};19use cdk_rsx_engine_nyxus::NyxusData;20use core::marker::PhantomData;2122pub const BREADCRUMB_POLICY: [u8; 32] = crate::contract(23    "MinimaBreadcrumbC2Unary/v1",24    &[],25    &[SOURCE_POLICY, crate::MINIMA_POLICY, XXH64_POLICY],26);27pub const BREADCRUMB_PRIMARY_CAPACITY: usize = 48;28pub const BREADCRUMB_OVERFLOW_CAPACITY: usize = 24;29pub const BREADCRUMB_MINI_BUCKETS: usize = 16;30pub const BREADCRUMB_MAX_SCAN_BUCKETS: u32 = 256;31const BUCKET_BYTES: usize = 64;32const _: () = assert!(NODE_BYTES.is_multiple_of(BUCKET_BYTES));33const _: () = assert!(BREADCRUMB_PRIMARY_CAPACITY + BREADCRUMB_MINI_BUCKETS == 64);3435#[repr(C)]36#[derive(Clone, Copy, Debug, Eq, PartialEq)]37pub struct BreadcrumbConfig {38    /// Power of two in 4..=2^20. Overflow has half this many buckets.39    pub primary_buckets: u32,40    pub seed: u64,41}42// SAFETY: inline immutable interpretation configuration.43unsafe impl NyxusData for BreadcrumbConfig {44    const __NYXUS_POLICY: [u8; 32] = BREADCRUMB_POLICY;45}46impl BreadcrumbConfig {47    pub const fn contract(self) -> [u8; 32] {48        crate::contract(49            "MinimaBreadcrumbConfiguration/v1",50            &[],51            &[52                BREADCRUMB_POLICY,53                crate::width_contract("primary", self.primary_buckets as usize, &[]),54                crate::width_contract("seed", self.seed as usize, &[]),55            ],56        )57    }58}5960#[derive(Clone, Copy, Debug, Eq, PartialEq)]61#[must_use]62pub enum BreadcrumbInsert {63    Inserted,64    Full,65}6667/// Enumerable partial-hash identity, not an original key or ownership token.68#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]69pub struct BreadcrumbFingerprint {70    pub primary_bucket: u32,71    pub mini_bucket: u8,72    pub remainder: u8,73}7475#[repr(C)]76pub struct BreadcrumbFilter<K: FixedKey> {77    nodes: Collection,78    config: BreadcrumbConfig,79    len: u64,80    key: PhantomData<K>,81}82// SAFETY: Collection owns admitted retained backing; only scalars and a ZST83// marker accompany it. Bucket arrays and workspace never become persistent.84unsafe impl<K: FixedKey> NyxusData for BreadcrumbFilter<K> {85    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;86}8788#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd)]89struct Entry {90    mini: u8,91    tag: u16,92}93#[derive(Clone, Copy)]94struct Bucket {95    entries: [Entry; BREADCRUMB_PRIMARY_CAPACITY],96    len: usize,97}98impl Bucket {99    fn empty() -> Self {100        Self {101            entries: [Entry::default(); BREADCRUMB_PRIMARY_CAPACITY],102            len: 0,103        }104    }105    fn find(&self, entry: Entry) -> Option<usize> {106        self.entries[..self.len].iter().position(|e| *e == entry)107    }108    fn insert(&mut self, entry: Entry) {109        assert!(self.len < self.entries.len());110        let at = self.entries[..self.len].partition_point(|e| *e <= entry);111        self.entries.copy_within(at..self.len, at + 1);112        self.entries[at] = entry;113        self.len += 1;114    }115    fn remove(&mut self, at: usize) -> Entry {116        let out = self.entries[at];117        self.entries.copy_within(at + 1..self.len, at);118        self.len -= 1;119        self.entries[self.len] = Entry::default();120        out121    }122    fn minimum_crumb(&self, crumb: u16) -> Option<usize> {123        self.entries[..self.len]124            .iter()125            .position(|entry| entry.tag >> 8 == crumb)126    }127}128129impl<K: FixedKey> BreadcrumbFilter<K> {130    pub const CONTRACT: [u8; 32] = crate::contract(131        "MinimaBreadcrumbKey/v1",132        &[],133        &[BREADCRUMB_POLICY, K::CONTRACT],134    );135136    pub fn new(storage: &mut dyn Storage, config: BreadcrumbConfig) -> Result<Self> {137        const {138            assert!(K::WIDTH <= NODE_BYTES, "Breadcrumb key exceeds workspace");139        }140        if !config.primary_buckets.is_power_of_two()141            || !(4..=1 << 20).contains(&config.primary_buckets)142        {143            return Err(Error::InvalidInput("Breadcrumb power-of-two geometry"));144        }145        Ok(Self {146            nodes: Collection::new(storage)?,147            config,148            len: 0,149            key: PhantomData,150        })151    }152    pub fn len(&self) -> u64 {153        self.len154    }155    pub fn is_empty(&self) -> bool {156        self.len == 0157    }158    pub fn config(&self) -> BreadcrumbConfig {159        self.config160    }161    pub fn block_count(&self) -> usize {162        self.nodes.block_count()163    }164    pub fn capacity(&self) -> u64 {165        u64::from(self.config.primary_buckets) * BREADCRUMB_PRIMARY_CAPACITY as u64166            + u64::from(self.config.primary_buckets / 2) * BREADCRUMB_OVERFLOW_CAPACITY as u64167    }168    pub fn payload_bytes(&self) -> u64 {169        self.overflow_at()170            + (u64::from(self.config.primary_buckets / 2) * BUCKET_BYTES as u64)171                .div_ceil(NODE_BYTES as u64)172                * NODE_BYTES as u64173    }174175    pub fn may_contain(176        &self,177        storage: &dyn Storage,178        key: &K,179        workspace: &mut Workspace,180    ) -> Result<bool> {181        self.nodes.validate(storage)?;182        if self.is_empty() {183            return Ok(false);184        }185        let fingerprint = self.fingerprint(key, workspace);186        let entry = Entry {187            mini: fingerprint.mini_bucket,188            tag: u16::from(fingerprint.remainder),189        };190        let primary =191            self.probe_bucket(storage, false, fingerprint.primary_bucket, entry, workspace)?;192        if primary.count != 0 {193            return Ok(true);194        }195        if primary.len != BREADCRUMB_PRIMARY_CAPACITY || entry < primary.last {196            return Ok(false);197        }198        for (bucket, crumb) in self.destinations(fingerprint.primary_bucket) {199            let overflow = self.probe_bucket(200                storage,201                true,202                bucket,203                Entry {204                    tag: entry.tag | crumb << 8,205                    ..entry206                },207                workspace,208            )?;209            if overflow.count != 0 {210                return Ok(true);211            }212        }213        Ok(false)214    }215216    /// Fingerprint occurrence count, potentially overestimating an exact key's217    /// count. Both tiers are counted, including when the primary already matches.218    pub fn count(&self, storage: &dyn Storage, key: &K, workspace: &mut Workspace) -> Result<u64> {219        self.nodes.validate(storage)?;220        if self.is_empty() {221            return Ok(0);222        }223        let fingerprint = self.fingerprint(key, workspace);224        let entry = Entry {225            mini: fingerprint.mini_bucket,226            tag: u16::from(fingerprint.remainder),227        };228        let primary =229            self.probe_bucket(storage, false, fingerprint.primary_bucket, entry, workspace)?;230        let mut count = primary.count;231        if primary.len == BREADCRUMB_PRIMARY_CAPACITY && entry >= primary.last {232            for (bucket, crumb) in self.destinations(fingerprint.primary_bucket) {233                count += self234                    .probe_bucket(235                        storage,236                        true,237                        bucket,238                        Entry {239                            tag: entry.tag | crumb << 8,240                            ..entry241                        },242                        workspace,243                    )?244                    .count;245            }246        }247        Ok(count)248    }249250    pub fn try_insert(251        &mut self,252        storage: &mut dyn Storage,253        key: &K,254        workspace: &mut Workspace,255    ) -> Result<BreadcrumbInsert> {256        self.nodes.validate(storage)?;257        let fingerprint = self.fingerprint(key, workspace);258        let entry = Entry {259            mini: fingerprint.mini_bucket,260            tag: u16::from(fingerprint.remainder),261        };262        let mut primary =263            self.read_bucket(storage, false, fingerprint.primary_bucket, workspace)?;264        if primary.len < BREADCRUMB_PRIMARY_CAPACITY {265            primary.insert(entry);266            self.allocate(storage);267            self.write_bucket(storage, false, fingerprint.primary_bucket, &primary);268        } else {269            // Stage the prefix eviction before touching payload bytes.270            let primary_changed = entry < primary.entries[primary.len - 1];271            let overflow_entry = if !primary_changed {272                entry273            } else {274                let at = primary.len - 1;275                let overflow = primary.remove(at);276                primary.insert(entry);277                overflow278            };279            let destinations = self.destinations(fingerprint.primary_bucket);280            let mut candidates = [281                self.read_bucket(storage, true, destinations[0].0, workspace)?,282                self.read_bucket(storage, true, destinations[1].0, workspace)?,283            ];284            if candidates285                .iter()286                .all(|b| b.len == BREADCRUMB_OVERFLOW_CAPACITY)287            {288                return Ok(BreadcrumbInsert::Full);289            }290            let choice = usize::from(candidates[0].len >= candidates[1].len);291            candidates[choice].insert(Entry {292                tag: overflow_entry.tag | destinations[choice].1 << 8,293                ..overflow_entry294            });295            self.allocate(storage);296            if primary_changed {297                self.write_bucket(storage, false, fingerprint.primary_bucket, &primary);298            }299            self.write_bucket(storage, true, destinations[choice].0, &candidates[choice]);300        }301        self.len += 1;302        Ok(BreadcrumbInsert::Inserted)303    }304305    /// Remove one previously admitted occurrence. The caller must authorize306    /// exact presence; deleting from a filter positive alone is unsound.307    pub fn remove_known_present(308        &mut self,309        storage: &mut dyn Storage,310        key: &K,311        workspace: &mut Workspace,312    ) -> Result<bool> {313        self.nodes.validate(storage)?;314        if self.is_empty() {315            return Ok(false);316        }317        let fingerprint = self.fingerprint(key, workspace);318        let entry = Entry {319            mini: fingerprint.mini_bucket,320            tag: u16::from(fingerprint.remainder),321        };322        let mut primary =323            self.read_bucket(storage, false, fingerprint.primary_bucket, workspace)?;324        let found = primary.find(entry);325        if primary.len < BREADCRUMB_PRIMARY_CAPACITY {326            let Some(at) = found else {327                return Ok(false);328            };329            primary.remove(at);330            self.write_bucket(storage, false, fingerprint.primary_bucket, &primary);331        } else {332            let destinations = self.destinations(fingerprint.primary_bucket);333            let mut candidates = [334                self.read_bucket(storage, true, destinations[0].0, workspace)?,335                self.read_bucket(storage, true, destinations[1].0, workspace)?,336            ];337            if let Some(at) = found {338                primary.remove(at);339                let minima = [340                    candidates[0].minimum_crumb(destinations[0].1),341                    candidates[1].minimum_crumb(destinations[1].1),342                ];343                let choice = match minima {344                    [None, None] => None,345                    [Some(_), None] => Some(0),346                    [None, Some(_)] => Some(1),347                    [Some(a), Some(b)] => {348                        let a = candidates[0].entries[a];349                        let b = candidates[1].entries[b];350                        Some(usize::from((a.mini, a.tag & 255) >= (b.mini, b.tag & 255)))351                    }352                };353                if let Some(choice) = choice {354                    let promoted = candidates[choice].remove(minima[choice].unwrap());355                    primary.insert(Entry {356                        tag: promoted.tag & 255,357                        ..promoted358                    });359                    self.write_bucket(storage, true, destinations[choice].0, &candidates[choice]);360                }361                self.write_bucket(storage, false, fingerprint.primary_bucket, &primary);362            } else {363                let mut found = None;364                for choice in 0..2 {365                    if let Some(at) = candidates[choice].find(Entry {366                        tag: entry.tag | destinations[choice].1 << 8,367                        ..entry368                    }) {369                        found = Some((choice, at));370                        break;371                    }372                }373                let Some((choice, at)) = found else {374                    return Ok(false);375                };376                candidates[choice].remove(at);377                self.write_bucket(storage, true, destinations[choice].0, &candidates[choice]);378            }379        }380        self.len -= 1;381        Ok(true)382    }383384    /// Visit an explicitly bounded number of physical mini-filters. Returns the385    /// next bucket cursor, or None at the end. Enumeration preserves occurrence386    /// multiplicity and reconstructs exactly the original partial-hash identity.387    pub fn scan_fingerprints(388        &self,389        storage: &dyn Storage,390        first_bucket: u32,391        bucket_limit: u32,392        mut visit: impl FnMut(BreadcrumbFingerprint),393        workspace: &mut Workspace,394    ) -> Result<Option<u32>> {395        self.nodes.validate(storage)?;396        if bucket_limit == 0 || bucket_limit > BREADCRUMB_MAX_SCAN_BUCKETS {397            return Err(Error::InvalidInput("Breadcrumb scan bound"));398        }399        let total = self.config.primary_buckets + self.config.primary_buckets / 2;400        if first_bucket > total {401            return Err(Error::Bounds);402        }403        if self.is_empty() {404            return Ok(None);405        }406        let end = first_bucket.saturating_add(bucket_limit).min(total);407        let mut index = first_bucket;408        while index < end {409            let overflow = index >= self.config.primary_buckets;410            let bucket_index = if overflow {411                index - self.config.primary_buckets412            } else {413                index414            };415            let at = if overflow { self.overflow_at() } else { 0 }416                + u64::from(bucket_index) * BUCKET_BYTES as u64;417            let tier_end = if overflow {418                end419            } else {420                end.min(self.config.primary_buckets)421            };422            let count = (tier_end - index)423                .min(((NODE_BYTES as u64 - at % NODE_BYTES as u64) / BUCKET_BYTES as u64) as u32);424            let bytes = &mut workspace.bytes_mut()[..count as usize * BUCKET_BYTES];425            self.nodes.read_at(storage, at, bytes)?;426            for (offset, encoded) in bytes.chunks_exact(BUCKET_BYTES).enumerate() {427                let bucket = decode_bucket(encoded, overflow)?;428                let bucket_index = bucket_index + offset as u32;429                for entry in &bucket.entries[..bucket.len] {430                    let primary_bucket = if overflow {431                        self.invert(bucket_index, entry.tag >> 8)?432                    } else {433                        bucket_index434                    };435                    visit(BreadcrumbFingerprint {436                        primary_bucket,437                        mini_bucket: entry.mini,438                        remainder: entry.tag as u8,439                    });440                }441            }442            index += count;443        }444        Ok((end < total).then_some(end))445    }446    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {447        self.nodes.retire(storage)448    }449450    fn fingerprint(&self, key: &K, workspace: &mut Workspace) -> BreadcrumbFingerprint {451        let hash = hash_key(key, self.config.seed, workspace);452        BreadcrumbFingerprint {453            primary_bucket: (hash >> 12) as u32 & (self.config.primary_buckets - 1),454            mini_bucket: (hash >> 8) as u8 & 15,455            remainder: hash as u8,456        }457    }458    fn destinations(&self, primary: u32) -> [(u32, u16); 2] {459        let overflow = self.config.primary_buckets / 2;460        [461            (primary / 2, (primary % 2) as u16),462            (463                primary / 4 + (primary % 2) * (overflow / 2),464                2 + ((primary / 2) % 2) as u16,465            ),466        ]467    }468    fn invert(&self, bucket: u32, crumb: u16) -> Result<u32> {469        let primary = match crumb {470            0..=1 => bucket * 2 + u32::from(crumb),471            2..=3 => {472                let half = self.config.primary_buckets / 4;473                let low = bucket / half;474                let high = bucket % half;475                high * 4 + u32::from(crumb - 2) * 2 + low476            }477            _ => return Err(Error::InvalidInput("Breadcrumb crumb invariant")),478        };479        if primary >= self.config.primary_buckets {480            return Err(Error::InvalidInput("Breadcrumb origin invariant"));481        }482        Ok(primary)483    }484    fn overflow_at(&self) -> u64 {485        (u64::from(self.config.primary_buckets) * BUCKET_BYTES as u64).div_ceil(NODE_BYTES as u64)486            * NODE_BYTES as u64487    }488    fn allocate(&mut self, storage: &mut dyn Storage) {489        self.nodes490            .ensure_nodes(storage, self.payload_bytes() / NODE_BYTES as u64)491            .expect("admitted Breadcrumb allocation failed");492    }493    fn read_bucket(494        &self,495        storage: &dyn Storage,496        overflow: bool,497        index: u32,498        workspace: &mut Workspace,499    ) -> Result<Bucket> {500        if self.nodes.block_count() == 0 {501            return Ok(Bucket::empty());502        }503        let at =504            if overflow { self.overflow_at() } else { 0 } + u64::from(index) * BUCKET_BYTES as u64;505        let bytes = &mut workspace.bytes_mut()[..BUCKET_BYTES];506        self.nodes.read_at(storage, at, bytes)?;507        decode_bucket(bytes, overflow)508    }509    fn probe_bucket(510        &self,511        storage: &dyn Storage,512        overflow: bool,513        index: u32,514        entry: Entry,515        workspace: &mut Workspace,516    ) -> Result<BucketProbe> {517        let at =518            if overflow { self.overflow_at() } else { 0 } + u64::from(index) * BUCKET_BYTES as u64;519        let bytes = &mut workspace.bytes_mut()[..BUCKET_BYTES];520        self.nodes.read_at(storage, at, bytes)?;521        probe_bucket(bytes, overflow, entry)522    }523    fn write_bucket(&self, storage: &mut dyn Storage, overflow: bool, index: u32, bucket: &Bucket) {524        let at =525            if overflow { self.overflow_at() } else { 0 } + u64::from(index) * BUCKET_BYTES as u64;526        self.nodes527            .write_at(storage, at, &encode_bucket(bucket, overflow))528            .expect("admitted Breadcrumb write failed");529    }530}531532struct BucketProbe {533    len: usize,534    last: Entry,535    count: u64,536}537538/// Select unary delimiters to find one mini-bucket, then search its encoded539/// sorted tags directly. Querying never materializes the other 15 mini-buckets.540fn probe_bucket(bytes: &[u8], overflow: bool, entry: Entry) -> Result<BucketProbe> {541    let metadata = u64::from_le_bytes(bytes[..8].try_into().unwrap());542    let len = metadata.count_ones() as usize;543    let capacity = if overflow {544        BREADCRUMB_OVERFLOW_CAPACITY545    } else {546        BREADCRUMB_PRIMARY_CAPACITY547    };548    if len > capacity {549        return Err(Error::InvalidInput("Breadcrumb bucket capacity invariant"));550    }551    // All entries must precede the sixteenth delimiter. The last used bit is552    // that zero; the remaining bits are padding, including at full capacity.553    if metadata >> (len + BREADCRUMB_MINI_BUCKETS - 1) != 0 {554        return Err(Error::InvalidInput("Breadcrumb unary invariant"));555    }556    let width = if overflow { 2 } else { 1 };557    let tag = |at: usize| {558        let at = 8 + at * width;559        if overflow {560            u16::from_le_bytes([bytes[at], bytes[at + 1]])561        } else {562            u16::from(bytes[at])563        }564    };565    let last = if len == 0 {566        Entry::default()567    } else {568        let tag = tag(len - 1);569        if overflow && tag >= 1024 {570            return Err(Error::InvalidInput("Breadcrumb tag invariant"));571        }572        Entry {573            mini: (64 - metadata.leading_zeros() as usize - len) as u8,574            tag,575        }576    };577    let mut delimiters = !metadata;578    let mut start = 0;579    let mut end = 0;580    for mini in 0..=entry.mini {581        end = delimiters.trailing_zeros() as usize - mini as usize;582        if mini == entry.mini {583            break;584        }585        start = end;586        delimiters &= delimiters - 1;587    }588    let bound = |upper: bool| {589        let (mut low, mut high) = (start, end);590        while low < high {591            let mid = low + (high - low) / 2;592            let value = tag(mid);593            if value < entry.tag || (upper && value == entry.tag) {594                low = mid + 1;595            } else {596                high = mid;597            }598        }599        low600    };601    Ok(BucketProbe {602        len,603        last,604        count: (bound(true) - bound(false)) as u64,605    })606}607608fn decode_bucket(bytes: &[u8], overflow: bool) -> Result<Bucket> {609    let metadata = u64::from_le_bytes(bytes[..8].try_into().unwrap());610    let capacity = if overflow {611        BREADCRUMB_OVERFLOW_CAPACITY612    } else {613        BREADCRUMB_PRIMARY_CAPACITY614    };615    let width = if overflow { 2 } else { 1 };616    let mut bucket = Bucket::empty();617    let mut bit = 0;618    for mini in 0..BREADCRUMB_MINI_BUCKETS {619        while bit < 64 && metadata >> bit & 1 != 0 {620            if bucket.len == capacity {621                return Err(Error::InvalidInput("Breadcrumb bucket capacity invariant"));622            }623            let at = 8 + bucket.len * width;624            let tag = if overflow {625                u16::from_le_bytes([bytes[at], bytes[at + 1]])626            } else {627                u16::from(bytes[at])628            };629            if tag >= if overflow { 1024 } else { 256 } {630                return Err(Error::InvalidInput("Breadcrumb tag invariant"));631            }632            bucket.entries[bucket.len] = Entry {633                mini: mini as u8,634                tag,635            };636            bucket.len += 1;637            bit += 1;638        }639        if bit >= 64 {640            return Err(Error::InvalidInput("Breadcrumb unary invariant"));641        }642        bit += 1;643    }644    if (bit < 64 && metadata >> bit != 0)645        || bucket.entries[..bucket.len].windows(2).any(|e| e[0] > e[1])646    {647        return Err(Error::InvalidInput("Breadcrumb ordering invariant"));648    }649    Ok(bucket)650}651fn encode_bucket(bucket: &Bucket, overflow: bool) -> [u8; BUCKET_BYTES] {652    let mut out = [0; BUCKET_BYTES];653    let mut metadata = 0u64;654    for (i, entry) in bucket.entries[..bucket.len].iter().enumerate() {655        metadata |= 1u64 << (i + entry.mini as usize);656        let at = 8 + i * if overflow { 2 } else { 1 };657        out[at] = entry.tag as u8;658        if overflow {659            out[at + 1] = (entry.tag >> 8) as u8;660        }661    }662    out[..8].copy_from_slice(&metadata.to_le_bytes());663    out664}665666#[cfg(test)]667#[path = "breadcrumb_tests.rs"]668mod tests;