rateless_iblt.rs

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

rateless_iblt.rs681 lines← SDK documentation
1//! Rateless IBLT streams for immutable sets of fixed-width `u64` identities.2//!3//! Implements the alpha=1/2 inverse-CDF mapping and signed XOR/checksum/count4//! peeling of Yang, Gilad and Alizadeh, *Practical Rateless Set Reconciliation*,5//! sections 3–4: <https://arxiv.org/html/2402.02668v3>.6//! The mapping follows the authors' Go reference (MIT), pinned in7//! `rateless_iblt_provenance.md`. This is a rateless symbol sequence, not a fixed8//! table retried at successively larger capacities.9//!10//! Descriptors, partial symbols, heap cursors and peeling progress belong in11//! private root-attached Nyxus Data alongside the shared Minima Root. Payloads12//! use three ordinary Minima FixedVec owners; no provider, workspace, Global13//! allocation or borrowed slice is retained. Exact sorted IDs are imported once14//! before encoding. Versions identify immutable snapshots; changing a snapshot15//! requires a new encoder/session. Transport/authentication is the caller's job.16//!17//! The pinned XXH64 checksum is noncryptographic: success is probabilistic and18//! assumes honest compatible streams and nonadversarial hash inputs. It is not19//! the paper's keyed-SipHash defense. A forged stream can describe a different20//! set; checksums cannot authenticate it. Collision/stalled/capacity outcomes21//! never authorize a replacement snapshot or claim complete recovery.22//!23//! Work budgets count mapping events, cell inspections and state transitions,24//! not instructions. A heap event touches O(log(admitted IDs)) fixed records;25//! the bounded decoder scans its received prefix after each peel. This trades26//! computation for compact persistent state and does not inherit the reference27//! decoder's asymptotic running-time or complete-inventory cost claims. Physical28//! 4 KiB access fees reset each execution; narrow reads are not automatically29//! free. Backend faults after admission trap and rely on IC rollback.3031const SOURCE_POLICY: [u8; 32] =32    cdk_rsx_source_policy::source_policy!("rateless_iblt.rs", "indexed.rs");3334use crate::hash::{XXH64_POLICY, xxh64};35use crate::{Error, Fixed, FixedVec, Result, Storage, Workspace};36use cdk_rsx_engine_nyxus::NyxusData;3738pub const RATELESS_MAX_ITEMS: u32 = 1_048_576;39pub const RATELESS_MAX_SYMBOLS: u32 = 4_194_304;40pub const RATELESS_MAX_WORK: u32 = 4096;41pub const RATELESS_MAX_IMPORT: usize = 4096;4243/// Complete algorithm, fixed encoding, heap and progress interpretation.44pub const RATELESS_IBLT_POLICY: [u8; 32] = crate::contract(45    "MinimaRatelessIblt/u64/alpha-half/reference-mapping/v1",46    &[],47    &[crate::MINIMA_POLICY, SOURCE_POLICY, XXH64_POLICY],48);4950/// Fixed-width coded symbol. XOR is its own inverse; counts subtract normally.51#[repr(C)]52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]53pub struct CodedSymbol {54    pub xor: u64,55    pub checksum: u64,56    pub count: i64,57}58impl Fixed for CodedSymbol {59    const WIDTH: usize = 24;60    const CONTRACT: [u8; 32] = RATELESS_IBLT_POLICY;61    fn encode(&self, out: &mut [u8]) {62        (self.xor, self.checksum, self.count).encode(out);63    }64    fn decode(bytes: &[u8]) -> Result<Self> {65        let (xor, checksum, count) = <(u64, u64, i64)>::decode(bytes)?;66        Ok(Self {67            xor,68            checksum,69            count,70        })71    }72}73impl CodedSymbol {74    fn is_zero(self) -> bool {75        self == Self::default()76    }77    fn apply(&mut self, entry: Entry, direction: i64) {78        self.xor ^= entry.0;79        self.checksum ^= entry.1;80        self.count += direction;81    }82}8384/// Owned transport DTO. The source count is the exact immutable set size.85#[derive(Clone, Copy, Debug, PartialEq, Eq)]86pub struct RatelessSymbol {87    pub version: u64,88    pub seed: u64,89    pub index: u32,90    pub source_items: u32,91    pub coded: CodedSymbol,92}9394#[derive(Clone, Copy, Debug, PartialEq, Eq)]95pub struct EncodeProgress {96    pub work: u32,97    pub symbol: Option<RatelessSymbol>,98}99100// ID, checksum, PRNG state, next mapped index, sign. The heap is keyed by .3.101// All fields are encoded as exact eight-byte LE words, without Rust padding.102type Entry = (u64, u64, u64, u64, i64);103type Difference = (u64, i64);104const PRNG_MULTIPLIER: u64 = 0xda94_2042_e4dd_58b5;105106fn checksum(id: u64, seed: u64) -> u64 {107    xxh64(&id.to_le_bytes(), seed)108}109110fn advance(entry: &mut Entry) {111    entry.2 = entry.2.wrapping_mul(PRNG_MULTIPLIER);112    // Authors' alpha=1/2 approximation. Strictly increasing/saturating indices113    // define zero/rounding/overflow edges absent from the unbounded model.114    // Admitted emitted indices stay <= 2^22, exactly representable in f64.115    let jump = ((entry.3 as f64 + 1.5) * (4_294_967_296.0 / (entry.2 as f64 + 1.0).sqrt() - 1.0))116        .ceil() as u64;117    entry.3 = entry.3.saturating_add(jump.max(1));118}119120fn admitted<T: Fixed>(121    values: &FixedVec<T>,122    storage: &dyn Storage,123    w: &mut Workspace<'_>,124) -> Result<()> {125    // Out-of-range access validates authority without fetching payload.126    values.get(storage, values.len(), w).map(|_| ())127}128fn get<T: Fixed>(129    values: &FixedVec<T>,130    storage: &dyn Storage,131    index: u64,132    w: &mut Workspace<'_>,133) -> T {134    values135        .get(storage, index, w)136        .expect("Rateless admitted read")137        .expect("Rateless live index")138}139fn set<T: Fixed>(140    values: &mut FixedVec<T>,141    storage: &mut dyn Storage,142    index: u64,143    value: &T,144    w: &mut Workspace<'_>,145) {146    values147        .set(storage, index, value, w)148        .expect("Rateless admitted write");149}150fn push<T: Fixed>(151    values: &mut FixedVec<T>,152    storage: &mut dyn Storage,153    value: &T,154    w: &mut Workspace<'_>,155) {156    values157        .push(storage, value, w)158        .expect("Rateless admitted append");159}160fn fix_head(161    heap: &mut FixedVec<Entry>,162    storage: &mut dyn Storage,163    value: Entry,164    w: &mut Workspace<'_>,165) {166    let mut at = 0;167    while at * 2 + 1 < heap.len() {168        let left = at * 2 + 1;169        let mut child = left;170        let mut candidate = (0, 0, 0, 0, 0);171        // Siblings are adjacent fixed-width records. Read one covering span172        // when they share a node, rather than consuming first-read eligibility173        // with a separate read for each child. Ties still choose the left.174        heap.scan(175            storage,176            left..(left + 2).min(heap.len()),177            |index, entry| {178                if index == left || entry.3 < candidate.3 {179                    child = index;180                    candidate = entry;181                }182                true183            },184            w,185        )186        .expect("Rateless admitted sibling read");187        if candidate.3 >= value.3 {188            break;189        }190        set(heap, storage, at, &candidate, w);191        at = child;192    }193    set(heap, storage, at, &value, w);194}195fn heap_push(196    heap: &mut FixedVec<Entry>,197    storage: &mut dyn Storage,198    value: Entry,199    w: &mut Workspace<'_>,200) {201    let inserted = heap.len();202    let mut at = inserted;203    push(heap, storage, &value, w);204    while at > 0 {205        let parent = (at - 1) / 2;206        let candidate = get(heap, storage, parent, w);207        if candidate.3 <= value.3 {208            break;209        }210        set(heap, storage, at, &candidate, w);211        at = parent;212    }213    if at != inserted {214        set(heap, storage, at, &value, w);215    }216}217fn budget(work: u32) -> Result<()> {218    if work == 0 || work > RATELESS_MAX_WORK {219        Err(Error::Capacity)220    } else {221        Ok(())222    }223}224225/// Move-only rooted encoder. Import batches must be globally strictly sorted.226#[repr(C)]227pub struct RatelessEncoder {228    heap: FixedVec<Entry>,229    version: u64,230    seed: u64,231    last_id: u64,232    pending: CodedSymbol,233    max_items: u32,234    max_symbols: u32,235    index: u32,236    started: bool,237}238// SAFETY: retained FixedVec authority plus inline scalars only.239unsafe impl NyxusData for RatelessEncoder {240    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;241}242impl RatelessEncoder {243    pub const CONTRACT: [u8; 32] = RATELESS_IBLT_POLICY;244    pub fn new(245        storage: &mut dyn Storage,246        version: u64,247        seed: u64,248        max_items: u32,249        max_symbols: u32,250    ) -> Result<Self> {251        if max_items > RATELESS_MAX_ITEMS || max_symbols == 0 || max_symbols > RATELESS_MAX_SYMBOLS252        {253            return Err(Error::Capacity);254        }255        Ok(Self {256            heap: FixedVec::new(storage)?,257            version,258            seed,259            last_id: 0,260            pending: CodedSymbol::default(),261            max_items,262            max_symbols,263            index: 0,264            started: false,265        })266    }267    pub fn source_items(&self) -> u32 {268        self.heap.len() as u32269    }270    pub fn next_index(&self) -> u32 {271        self.index272    }273    pub fn allocated_blocks(&self) -> usize {274        self.heap.block_count()275    }276277    /// Preflight an entire bounded batch before appending. Duplicate IDs reject;278    /// source identities must include any application content/version identity.279    pub fn add_sorted(280        &mut self,281        storage: &mut dyn Storage,282        ids: &[u64],283        w: &mut Workspace<'_>,284    ) -> Result<()> {285        if self.started {286            return Err(Error::InvalidInput("Rateless snapshot already sealed"));287        }288        if ids.len() > RATELESS_MAX_IMPORT289            || ids.len() as u64 + self.heap.len() > u64::from(self.max_items)290        {291            return Err(Error::Capacity);292        }293        if ids.windows(2).any(|p| p[0] >= p[1])294            || (!self.heap.is_empty() && ids.first().is_some_and(|id| *id <= self.last_id))295        {296            return Err(Error::InvalidInput("Rateless IDs must be strictly sorted"));297        }298        admitted(&self.heap, storage, w)?;299        if ids.len() == 1 {300            let id = ids[0];301            let hash = checksum(id, self.seed);302            push(&mut self.heap, storage, &(id, hash, hash, 0, 1), w);303        } else if !ids.is_empty() {304            // Before sealing every mapped index is zero, so contiguous import305            // preserves exactly the scalar heap order. Bounded transient typed306            // scratch lets FixedVec encode one span instead of one write/ID.307            let mut entries = [(0, 0, 0, 0, 0); 32];308            for chunk in ids.chunks(entries.len()) {309                for (&id, entry) in chunk.iter().zip(&mut entries) {310                    let hash = checksum(id, self.seed);311                    *entry = (id, hash, hash, 0, 1);312                }313                self.heap314                    .extend_from_slice(storage, &entries[..chunk.len()], w)315                    .expect("Rateless admitted import");316            }317        }318        if let Some(&id) = ids.last() {319            self.last_id = id;320        }321        Ok(())322    }323324    /// Emit at most one next symbol. At most `max_work` source mappings are325    /// consumed; an unfinished partial symbol is retained for the next call.326    /// Empty gaps emit a zero symbol without scanning the source inventory.327    pub fn next(328        &mut self,329        storage: &mut dyn Storage,330        max_work: u32,331        w: &mut Workspace<'_>,332    ) -> Result<EncodeProgress> {333        budget(max_work)?;334        if self.index >= self.max_symbols {335            return Err(Error::Capacity);336        }337        admitted(&self.heap, storage, w)?;338        self.started = true;339        let mut work = 0;340        loop {341            let head = if self.heap.is_empty() {342                None343            } else {344                Some(get(&self.heap, storage, 0, w))345            };346            if head.is_none_or(|e| e.3 != u64::from(self.index)) {347                let symbol = RatelessSymbol {348                    version: self.version,349                    seed: self.seed,350                    index: self.index,351                    source_items: self.source_items(),352                    coded: self.pending,353                };354                self.pending = CodedSymbol::default();355                self.index += 1;356                return Ok(EncodeProgress {357                    work,358                    symbol: Some(symbol),359                });360            }361            if work == max_work {362                return Ok(EncodeProgress { work, symbol: None });363            }364            let mut entry = head.unwrap();365            self.pending.apply(entry, 1);366            advance(&mut entry);367            fix_head(&mut self.heap, storage, entry, w);368            work += 1;369        }370    }371}372373/// Bounds and immutable snapshot identities admitted before creating a decoder.374#[repr(C)]375#[derive(Clone, Copy, Debug, PartialEq, Eq)]376pub struct DecodeConfig {377    pub source_version: u64,378    pub target_version: u64,379    pub seed: u64,380    pub source_items: u32,381    pub target_items: u32,382    pub max_symbols: u32,383    pub max_differences: u32,384}385#[derive(Clone, Copy, Debug, PartialEq, Eq)]386pub enum DecodeStatus {387    AwaitingSymbol,388    Working,389    Complete,390    SymbolLimit,391    DifferenceLimit,392    InvalidStream,393}394#[derive(Clone, Copy, Debug, PartialEq, Eq)]395pub struct DecodeProgress {396    pub work: u32,397    pub status: DecodeStatus,398    pub received: u32,399    pub recovered: u32,400}401const WAIT: u8 = 0;402const STRIP: u8 = 1;403const SCAN: u8 = 2;404const VERIFY: u8 = 3;405const PEEL: u8 = 4;406const COMPLETE: u8 = 5;407const SYMBOL_LIMIT: u8 = 6;408const DIFFERENCE_LIMIT: u8 = 7;409const INVALID: u8 = 8;410411/// Persistent incremental peeling session. Supply paired source/target symbols412/// in exact sequence from encoders sealed to the configured snapshots. Reading413/// signed differences is allowed only after Complete. `+1` means source-only;414/// `-1` means target-only. Incomplete sessions retain their original identities.415#[repr(C)]416pub struct RatelessDecoder {417    cells: FixedVec<CodedSymbol>,418    future: FixedVec<Entry>,419    differences: FixedVec<Difference>,420    config: DecodeConfig,421    pending: CodedSymbol,422    active: Entry,423    scan: u64,424    positive: u32,425    negative: u32,426    phase: u8,427    nonzero: bool,428}429// SAFETY: three owning retained FixedVecs and complete inline progress/config.430// No Global-owned storage, workspace, provider or callback crosses a call.431unsafe impl NyxusData for RatelessDecoder {432    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;433}434impl RatelessDecoder {435    pub const CONTRACT: [u8; 32] = RATELESS_IBLT_POLICY;436    pub fn new(storage: &mut dyn Storage, config: DecodeConfig) -> Result<Self> {437        let total = config.source_items.saturating_add(config.target_items);438        if config.source_items > RATELESS_MAX_ITEMS439            || config.target_items > RATELESS_MAX_ITEMS440            || config.max_symbols == 0441            || config.max_symbols > RATELESS_MAX_SYMBOLS442            || config.max_differences > total443        {444            return Err(Error::Capacity);445        }446        Ok(Self {447            cells: FixedVec::new(storage)?,448            future: FixedVec::new(storage)?,449            differences: FixedVec::new(storage)?,450            config,451            pending: CodedSymbol::default(),452            active: (0, 0, 0, 0, 0),453            scan: 0,454            positive: 0,455            negative: 0,456            phase: WAIT,457            nonzero: false,458        })459    }460    pub fn config(&self) -> DecodeConfig {461        self.config462    }463    pub fn received(&self) -> u32 {464        self.cells.len() as u32465    }466    pub fn recovered(&self) -> u32 {467        self.differences.len() as u32468    }469    pub fn allocated_blocks(&self) -> usize {470        self.cells.block_count() + self.future.block_count() + self.differences.block_count()471    }472    pub fn status(&self) -> DecodeStatus {473        match self.phase {474            WAIT => DecodeStatus::AwaitingSymbol,475            COMPLETE => DecodeStatus::Complete,476            SYMBOL_LIMIT => DecodeStatus::SymbolLimit,477            DIFFERENCE_LIMIT => DecodeStatus::DifferenceLimit,478            INVALID => DecodeStatus::InvalidStream,479            _ => DecodeStatus::Working,480        }481    }482    fn validate(&self, storage: &dyn Storage, w: &mut Workspace<'_>) -> Result<()> {483        admitted(&self.cells, storage, w)?;484        admitted(&self.future, storage, w)?;485        admitted(&self.differences, storage, w)486    }487488    /// Admit one paired symbol without unbounded decoding. Metadata/count/bounds489    /// rejections leave the session unchanged. Finish advance() before feeding490    /// another symbol; neither side's inventory is provided to the decoder.491    pub fn feed(492        &mut self,493        storage: &dyn Storage,494        source: RatelessSymbol,495        target: RatelessSymbol,496        w: &mut Workspace<'_>,497    ) -> Result<()> {498        if self.phase != WAIT {499            return Err(Error::InvalidInput(500                "Rateless decoder is not awaiting a symbol",501            ));502        }503        if self.received() >= self.config.max_symbols {504            return Err(Error::Capacity);505        }506        for (symbol, version, items) in [507            (source, self.config.source_version, self.config.source_items),508            (target, self.config.target_version, self.config.target_items),509        ] {510            if symbol.version != version511                || symbol.seed != self.config.seed512                || symbol.index != self.received()513                || symbol.source_items != items514                || symbol.coded.count < 0515                || symbol.coded.count > i64::from(items)516                || (symbol.index == 0 && symbol.coded.count != i64::from(items))517                || (symbol.coded.count == 0 && !symbol.coded.is_zero())518            {519                return Err(Error::InvalidInput("Rateless incompatible symbol"));520            }521        }522        self.validate(storage, w)?;523        self.pending = CodedSymbol {524            xor: source.coded.xor ^ target.coded.xor,525            checksum: source.coded.checksum ^ target.coded.checksum,526            count: source.coded.count - target.coded.count,527        };528        self.phase = STRIP;529        Ok(())530    }531532    /// Perform bounded persistent progress. Each work unit is one mapping event,533    /// one inspected record or one phase transition. Heap repair has at most 21534    /// levels (admitted at most 2,097,152 differences). Allocation/zeroing remains535    /// additional real work; at most one append occurs in a work unit.536    pub fn advance(537        &mut self,538        storage: &mut dyn Storage,539        max_work: u32,540        w: &mut Workspace<'_>,541    ) -> Result<DecodeProgress> {542        budget(max_work)?;543        self.validate(storage, w)?;544        let mut work = 0;545        while work < max_work && matches!(self.phase, STRIP | SCAN | VERIFY | PEEL) {546            work += 1;547            match self.phase {548                STRIP => {549                    let head = if self.future.is_empty() {550                        None551                    } else {552                        Some(get(&self.future, storage, 0, w))553                    };554                    if let Some(mut entry) = head.filter(|e| e.3 == self.cells.len()) {555                        self.pending.apply(entry, -entry.4);556                        if !self.valid_count(self.pending) {557                            self.phase = INVALID;558                            continue;559                        }560                        advance(&mut entry);561                        fix_head(&mut self.future, storage, entry, w);562                    } else {563                        push(&mut self.cells, storage, &self.pending, w);564                        self.scan = 0;565                        self.nonzero = false;566                        self.phase = SCAN;567                    }568                }569                SCAN => {570                    if self.scan == self.cells.len() {571                        self.phase = if !self.nonzero {572                            if i64::from(self.positive) - i64::from(self.negative)573                                == i64::from(self.config.source_items)574                                    - i64::from(self.config.target_items)575                            {576                                COMPLETE577                            } else {578                                INVALID579                            }580                        } else if self.received() == self.config.max_symbols {581                            SYMBOL_LIMIT582                        } else {583                            WAIT584                        };585                        continue;586                    }587                    let cell = get(&self.cells, storage, self.scan, w);588                    self.scan += 1;589                    if cell.is_zero() {590                        continue;591                    }592                    self.nonzero = true;593                    if (cell.count == 1 || cell.count == -1)594                        && checksum(cell.xor, self.config.seed) == cell.checksum595                    {596                        if self.recovered() == self.config.max_differences {597                            self.phase = DIFFERENCE_LIMIT;598                            continue;599                        }600                        if (cell.count == 1 && self.positive == self.config.source_items)601                            || (cell.count == -1 && self.negative == self.config.target_items)602                        {603                            self.phase = INVALID;604                            continue;605                        }606                        self.active = (cell.xor, cell.checksum, cell.checksum, 0, cell.count);607                        self.scan = 0;608                        self.phase = VERIFY;609                    }610                }611                VERIFY => {612                    if self.scan < self.differences.len() {613                        if get(&self.differences, storage, self.scan, w).0 == self.active.0 {614                            self.phase = INVALID;615                        }616                        self.scan += 1;617                    } else {618                        push(619                            &mut self.differences,620                            storage,621                            &(self.active.0, self.active.4),622                            w,623                        );624                        if self.active.4 == 1 {625                            self.positive += 1;626                        } else {627                            self.negative += 1;628                        }629                        self.phase = PEEL;630                    }631                }632                PEEL => {633                    if self.active.3 < self.cells.len() {634                        let mut cell = get(&self.cells, storage, self.active.3, w);635                        cell.apply(self.active, -self.active.4);636                        if !self.valid_count(cell) {637                            self.phase = INVALID;638                            continue;639                        }640                        set(&mut self.cells, storage, self.active.3, &cell, w);641                        advance(&mut self.active);642                    } else {643                        heap_push(&mut self.future, storage, self.active, w);644                        self.scan = 0;645                        self.nonzero = false;646                        self.phase = SCAN;647                    }648                }649                _ => unreachable!(),650            }651        }652        Ok(DecodeProgress {653            work,654            status: self.status(),655            received: self.received(),656            recovered: self.recovered(),657        })658    }659    fn valid_count(&self, cell: CodedSymbol) -> bool {660        cell.count.unsigned_abs()661            <= u64::from(self.config.source_items) + u64::from(self.config.target_items)662    }663664    /// Complete signed difference only. Each result reads exactly 16 bytes;665    /// callers bound output by requesting a bounded range of indices.666    pub fn difference(667        &self,668        storage: &dyn Storage,669        index: u32,670        w: &mut Workspace<'_>,671    ) -> Result<Option<(u64, i64)>> {672        if self.phase != COMPLETE {673            return Err(Error::InvalidInput("Rateless difference is incomplete"));674        }675        self.differences.get(storage, u64::from(index), w)676    }677}678679#[cfg(test)]680#[path = "rateless_iblt_tests.rs"]681mod tests;