exaloglog.rs

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

exaloglog.rs484 lines← SDK documentation
1//! Dense ExaLogLog (Ertl, EDBT 2025), the paper's (t=2,d=24) configuration.2//!3//! A LE u32 register holds the maximum update in its upper eight bits and the4//! occurrence bitmap of the 24 preceding updates below it. Hashes use the5//! paper's three-way split: two low bits refine the update, P following bits6//! address the register, and the leading zeros of the remaining bits select7//! its group. Observe implements Algorithm 2, union Algorithm 5, and estimation8//! Algorithm 3 / equation (15)'s maximum likelihood. This is not HLL relabeled.9//!10//! This first dense version has no sparse mode, precision reduction, martingale11//! estimate or optional finite-M bias correction. In particular, it makes no12//! claim of smaller IC cost: any allocated sketch owns a full aligned 64 KiB13//! block, regardless of payload. Observations borrow the caller's workspace and14//! access four register bytes. Estimation scans active register spans, with 65 small15//! coefficient counters on the stack. See `exaloglog_provenance.md`.1617const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("exaloglog.rs");1819use crate::hash::{XXH64_POLICY, hash_key};20use crate::{Collection, CollectionId, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};21use cdk_rsx_engine_nyxus::NyxusData;22use core::marker::PhantomData;2324const D: u32 = 24;25const T: u8 = 2;26const HISTORY_MASK: u32 = (1 << D) - 1;27pub const EXALOGLOG_MAX_BATCH: usize = 4096;2829#[derive(Clone, Copy, Debug, PartialEq, Eq)]30pub enum ExaLogLogStatus {31    Estimated,32    HashSpaceSaturated,33}3435#[derive(Clone, Copy, Debug, PartialEq)]36pub struct ExaLogLogEstimate {37    pub estimate: f64,38    pub zero_registers: u32,39    pub saturated_registers: u32,40    pub status: ExaLogLogStatus,41}4243#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]44pub struct ExaLogLogMerge {45    pub registers_changed: u32,46    pub pages_read: u32,47    pub pages_written: u32,48}4950/// Reusable transient grouping scratch, one entry per admitted observation.51/// Its fields confer no retained authority and are overwritten before use.52#[derive(Clone, Copy, Debug, Default)]53pub struct ExaLogLogBatchEntry {54    index: u16,55    update: u8,56}5758#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]59pub struct ExaLogLogBatch {60    pub observations: u32,61    /// Distinct registers whose final value differs from the pre-batch value.62    pub registers_changed: u32,63    pub pages_read: u32,64    pub pages_written: u32,65}6667/// Move-only rooted descriptor. P in 4..=14 selects 16..=16384 registers;68/// every allocated configuration owns one whole 64 KiB physical stable block.69///70/// ```compile_fail71/// use cdk_rsx_collections_minima::{Arena, exaloglog::ExaLogLog};72/// use cdk_rsx_platform::VecMemory;73/// let mut arena = Arena::format(VecMemory::new()).unwrap();74/// let _ = ExaLogLog::<u64, 15>::new(&mut arena, 0);75/// ```76#[repr(C)]77pub struct ExaLogLog<K: FixedKey, const P: u8 = 10> {78    collection: Collection,79    seed: u64,80    key: PhantomData<fn() -> K>,81}82// SAFETY: Collection is retained authority and owned blocks; other fields are83// inline/non-owning. There is no retained provider, buffer or ordinary Vec.84unsafe impl<K: FixedKey, const P: u8> NyxusData for ExaLogLog<K, P> {85    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;86}8788impl<K: FixedKey, const P: u8> ExaLogLog<K, P> {89    pub const REGISTER_COUNT: usize = {90        assert!(P >= 4 && P <= 14, "ExaLogLog precision must be in 4..=14");91        1 << P92    };93    pub const PAYLOAD_BYTES: usize = Self::REGISTER_COUNT * 4;94    pub const PAGE_COUNT: usize = Self::PAYLOAD_BYTES.div_ceil(NODE_BYTES);95    pub const MAX_UPDATE: u32 = (65 - P as u32 - T as u32) << T;96    pub const CONTRACT: [u8; 32] = crate::contract(97        "MinimaExaLogLog/t2d24/Dense/MaximumLikelihood/v1",98        &["LE-u32/t2/d24/XXH64/low2-update,nextP-index,high-NLZ/zero-sentinel"],99        &[100            SOURCE_POLICY,101            K::CONTRACT,102            XXH64_POLICY,103            crate::MINIMA_POLICY,104            crate::width_contract("exaloglog-registers", Self::REGISTER_COUNT, &[]),105        ],106    );107    pub fn new(storage: &mut dyn Storage, seed: u64) -> Result<Self> {108        const {109            assert!(P >= 4 && P <= 14, "ExaLogLog precision must be in 4..=14");110            assert!(K::WIDTH <= NODE_BYTES, "ExaLogLog key exceeds workspace");111        }112        Ok(Self {113            collection: Collection::new(storage)?,114            seed,115            key: PhantomData,116        })117    }118    pub const fn identity(&self) -> CollectionId {119        self.collection.identity()120    }121    pub const fn seed(&self) -> u64 {122        self.seed123    }124    pub fn allocated_blocks(&self) -> usize {125        self.collection.block_count()126    }127128    pub fn observe(129        &mut self,130        storage: &mut dyn Storage,131        key: &K,132        workspace: &mut Workspace<'_>,133    ) -> Result<bool> {134        self.collection.validate(storage)?;135        let (index, update) = Self::split_hash(hash_key(key, self.seed, workspace));136        self.collection137            .ensure_nodes(storage, Self::PAGE_COUNT as u64)?;138        let at = index as u64 * 4;139        let bytes = &mut workspace.bytes_mut()[..4];140        self.collection141            .read_at(storage, at, bytes)142            .expect("ExaLogLog admitted register read");143        let old = u32::from_le_bytes((&*bytes).try_into().unwrap());144        assert!(Self::valid_register(old), "corrupt ExaLogLog register");145        let new = update_register(old, update);146        if new == old {147            return Ok(false);148        }149        self.collection150            .write_at(storage, at, &new.to_le_bytes())151            .expect("ExaLogLog admitted register write");152        Ok(true)153    }154155    /// Apply at most 4096 observations using caller-owned grouping scratch.156    /// Hash/split and Algorithm 2 are unchanged. Every touched node is fetched157    /// once in its minimum bounding span, then at most one changed span is158    /// written. Equal-index observations commute as the same event-set union;159    /// statistics count final register changes, not intermediate scalar changes.160    pub fn observe_many(161        &mut self,162        storage: &mut dyn Storage,163        keys: &[K],164        scratch: &mut [ExaLogLogBatchEntry],165        workspace: &mut Workspace<'_>,166    ) -> Result<ExaLogLogBatch> {167        if keys.len() > EXALOGLOG_MAX_BATCH || scratch.len() < keys.len() {168            return Err(Error::Capacity);169        }170        self.collection.validate(storage)?;171        let mut stats = ExaLogLogBatch {172            observations: keys.len() as u32,173            ..ExaLogLogBatch::default()174        };175        if keys.is_empty() {176            return Ok(stats);177        }178        let scratch = &mut scratch[..keys.len()];179        for (entry, key) in scratch.iter_mut().zip(keys) {180            let (index, update) = Self::split_hash(hash_key(key, self.seed, workspace));181            entry.index = index as u16;182            entry.update = update as u8;183        }184        scratch.sort_unstable_by_key(|entry| entry.index);185        self.collection186            .ensure_nodes(storage, Self::PAGE_COUNT as u64)187            .expect("ExaLogLog admitted batch allocation");188        let mut cursor = 0;189        while cursor < scratch.len() {190            let first = scratch[cursor].index as usize;191            let page = first / (NODE_BYTES / 4);192            let mut end = cursor + 1;193            while end < scratch.len() && scratch[end].index as usize / (NODE_BYTES / 4) == page {194                end += 1;195            }196            let span = (scratch[end - 1].index as usize - first + 1) * 4;197            self.collection198                .read_at(199                    storage,200                    first as u64 * 4,201                    &mut workspace.bytes_mut()[..span],202                )203                .expect("ExaLogLog admitted batch read");204            stats.pages_read += 1;205            let mut first_changed = span;206            let mut changed_end = 0;207            while cursor < end {208                let index = scratch[cursor].index;209                let at = (index as usize - first) * 4;210                let bytes = &mut workspace.bytes_mut()[at..at + 4];211                let old = u32::from_le_bytes((&*bytes).try_into().unwrap());212                assert!(Self::valid_register(old), "corrupt ExaLogLog register");213                let mut new = old;214                while cursor < end && scratch[cursor].index == index {215                    new = update_register(new, u32::from(scratch[cursor].update));216                    cursor += 1;217                }218                if new != old {219                    bytes.copy_from_slice(&new.to_le_bytes());220                    first_changed = first_changed.min(at);221                    changed_end = at + 4;222                    stats.registers_changed += 1;223                }224            }225            if changed_end != 0 {226                self.collection227                    .write_at(228                        storage,229                        first as u64 * 4 + first_changed as u64,230                        &workspace.bytes()[first_changed..changed_end],231                    )232                    .expect("ExaLogLog admitted batch write");233                stats.pages_written += 1;234            }235        }236        Ok(stats)237    }238239    /// Scan once to form the paper's exact integer alpha' and beta240    /// coefficients. A bounded log-space solve maximizes equation (15).241    pub fn estimate(242        &self,243        storage: &dyn Storage,244        workspace: &mut Workspace<'_>,245    ) -> Result<ExaLogLogEstimate> {246        self.collection.validate(storage)?;247        let mut coefficients = Coefficients::default();248        let mut zero = 0;249        let mut saturated = 0;250        if self.allocated_blocks() == 0 {251            zero = Self::REGISTER_COUNT as u32;252        } else {253            for page in 0..Self::PAGE_COUNT {254                let used = (Self::REGISTER_COUNT - page * (NODE_BYTES / 4)).min(NODE_BYTES / 4);255                self.collection.read_at(256                    storage,257                    (page * NODE_BYTES) as u64,258                    &mut workspace.bytes_mut()[..used * 4],259                )?;260                for encoded in workspace.bytes()[..used * 4].chunks_exact(4) {261                    let register = u32::from_le_bytes(encoded.try_into().unwrap());262                    if !Self::valid_register(register) {263                        return Err(Error::Corrupt("ExaLogLog register"));264                    }265                    zero += u32::from(register == 0);266                    saturated += u32::from(register == (Self::MAX_UPDATE << D) | HISTORY_MASK);267                    Self::add_coefficients(register, &mut coefficients);268                }269            }270        }271        let (estimate, status) = if zero == Self::REGISTER_COUNT as u32 {272            (0.0, ExaLogLogStatus::Estimated)273        } else if coefficients.alpha == 0 {274            (f64::INFINITY, ExaLogLogStatus::HashSpaceSaturated)275        } else {276            (Self::solve(&coefficients), ExaLogLogStatus::Estimated)277        };278        Ok(ExaLogLogEstimate {279            estimate,280            zero_registers: zero,281            saturated_registers: saturated,282            status,283        })284    }285286    /// Paper Algorithm 5's aligned history union, not numeric maximum. Checks287    /// all merge configuration and authorities before allocation / writes.288    pub fn merge<Q: FixedKey, const R: u8>(289        &mut self,290        storage: &mut dyn Storage,291        other: &ExaLogLog<Q, R>,292        other_workspace: &mut Workspace<'_>,293        workspace: &mut Workspace<'_>,294    ) -> Result<ExaLogLogMerge> {295        if Self::CONTRACT != ExaLogLog::<Q, R>::CONTRACT || self.seed != other.seed {296            return Err(Error::InvalidInput(297                "incompatible ExaLogLog contract or seed",298            ));299        }300        self.collection.validate(storage)?;301        other.collection.validate(storage)?;302        let mut stats = ExaLogLogMerge::default();303        if other.allocated_blocks() == 0 {304            return Ok(stats);305        }306        self.collection307            .ensure_nodes(storage, Self::PAGE_COUNT as u64)?;308        for page in 0..Self::PAGE_COUNT {309            self.collection310                .read_node(storage, page as u64, workspace)311                .expect("ExaLogLog admitted merge destination read");312            let source = other313                .collection314                .read_node(storage, page as u64, other_workspace)315                .expect("ExaLogLog admitted merge source read");316            stats.pages_read += 2;317            let used = (Self::REGISTER_COUNT - page * (NODE_BYTES / 4)).min(NODE_BYTES / 4);318            let mut changed = false;319            for (destination, source) in workspace.bytes_mut()[..used * 4]320                .chunks_exact_mut(4)321                .zip(source[..used * 4].chunks_exact(4))322            {323                let old = u32::from_le_bytes((&*destination).try_into().unwrap());324                let from = u32::from_le_bytes(source.try_into().unwrap());325                assert!(326                    Self::valid_register(old) && Self::valid_register(from),327                    "corrupt ExaLogLog register"328                );329                let merged = merge_register(old, from);330                if merged != old {331                    destination.copy_from_slice(&merged.to_le_bytes());332                    changed = true;333                    stats.registers_changed += 1;334                }335            }336            if changed {337                self.collection338                    .write_node(storage, page as u64, workspace.bytes())339                    .expect("ExaLogLog admitted merge write");340                stats.pages_written += 1;341            }342        }343        Ok(stats)344    }345    pub fn clear(&mut self, storage: &mut dyn Storage) -> Result<()> {346        self.collection.truncate_nodes(storage, 0)347    }348349    fn split_hash(hash: u64) -> (usize, u32) {350        let lower_mask = (1u64 << (P + T)) - 1;351        let index = ((hash >> T) & ((1 << P) - 1)) as usize;352        let update = ((hash | lower_mask).leading_zeros() << T) + (hash & 3) as u32 + 1;353        (index, update)354    }355    fn valid_register(register: u32) -> bool {356        let u = register >> D;357        if u == 0 {358            return register == 0;359        }360        if u > Self::MAX_UPDATE {361            return false;362        }363        if u <= D {364            // Algorithm 2 carries an implicit initial update-zero sentinel.365            // It has no likelihood contribution; no negative update exists.366            let sentinel = 1u32 << (D - u);367            if register & sentinel == 0 || register & (sentinel - 1) != 0 {368                return false;369            }370        }371        true372    }373    fn phi(update: u32) -> u32 {374        (u32::from(T) + 1 + ((update - 1) >> T)).min(64 - u32::from(P))375    }376    fn add_coefficients(register: u32, out: &mut Coefficients) {377        let bits = 64 - u32::from(P);378        let u = register >> D;379        if u == 0 {380            out.alpha += 1u128 << bits;381            return;382        }383        let j = Self::phi(u);384        let remaining = ((1 - i32::from(T) + j as i32) << T) as u32 - u;385        out.alpha += u128::from(remaining) << (bits - j);386        out.beta[j as usize] += 1;387        let mut k = u.saturating_sub(D).max(1);388        while k < u {389            // t=2 gives four consecutive updates the same probability.390            // Count their observed/unobserved history bits together. Integer391            // coefficient addition is exact, including the capped last group;392            // the likelihood and its floating-point evaluation are unchanged.393            let j = Self::phi(k);394            let width = (4 - ((k - 1) & 3)).min(u - k);395            let present = ((register >> (D + k - u)) & ((1 << width) - 1)).count_ones();396            out.alpha += u128::from(width - present) << (bits - j);397            out.beta[j as usize] += present;398            k += width;399        }400    }401    fn solve(coefficients: &Coefficients) -> f64 {402        let alpha = coefficients.alpha as f64 / 2.0f64.powi(64 - i32::from(P));403        let first = (3..65).find(|&at| coefficients.beta[at] != 0).unwrap_or(65);404        let end = (first..65)405            .rev()406            .find(|&at| coefficients.beta[at] != 0)407            .map_or(first, |at| at + 1);408        let first_probability = 2.0f64.powi(-(first as i32));409        let (mut low, mut high) = (-128.0f64, 128.0f64);410        for _ in 0..100 {411            let mid = (low + high) * 0.5;412            if mid == low || mid == high {413                break;414            }415            let rate = 2.0f64.powf(mid);416            let mut score = -rate * alpha;417            let mut probability = first_probability;418            for &count in &coefficients.beta[first..end] {419                if count != 0 {420                    let z = rate * probability;421                    score += f64::from(count) * z / z.exp_m1();422                }423                probability *= 0.5;424            }425            if score > 0.0 {426                low = mid;427            } else {428                high = mid;429            }430        }431        Self::REGISTER_COUNT as f64 * 2.0f64.powf((low + high) * 0.5)432    }433}434435struct Coefficients {436    alpha: u128,437    beta: [u32; 65],438}439impl Default for Coefficients {440    fn default() -> Self {441        Self {442            alpha: 0,443            beta: [0; 65],444        }445    }446}447448fn update_register(register: u32, update: u32) -> u32 {449    let maximum = register >> D;450    match update.cmp(&maximum) {451        core::cmp::Ordering::Greater => {452            let distance = update - maximum;453            let history = if distance <= D {454                ((1 << D) | (register & HISTORY_MASK)) >> distance455            } else {456                0457            };458            (update << D) | history459        }460        core::cmp::Ordering::Less if maximum - update <= D => {461            register | (1 << (D - (maximum - update)))462        }463        _ => register,464    }465}466467fn merge_register(a: u32, b: u32) -> u32 {468    let (high, low) = if a >> D >= b >> D { (a, b) } else { (b, a) };469    let high_max = high >> D;470    let low_max = low >> D;471    if high_max == low_max || low_max == 0 {472        return a | b;473    }474    let distance = high_max - low_max;475    high | if distance <= D {476        ((1 << D) | (low & HISTORY_MASK)) >> distance477    } else {478        0479    }480}481482#[cfg(test)]483#[path = "exaloglog_tests.rs"]484mod tests;