zor.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/zor.rs
1// SPDX-License-Identifier: Apache-2.02//! Complete ZOR membership filter: deterministic peeling plus exceptional keys.3//!4//! Antoine Limasset, *ZOR Filters: Fast and Smaller Than Fuse Filters*,5//! SEA 2026, 15 June 2026, DOI 10.4230/LIPIcs.SEA.2026.24:6//! <https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.SEA.2026.24>.7//! Reference reviewed: <https://github.com/Malfoy/ZOR>, revision8//! `2967cc4907de2af753a7208ef2c566fe045c8d41`. No license is supplied by9//! that repository; no reference source is copied here. This implementation is10//! independently written from paper Sections 2.1–2.4. The paper is CC-BY4.0.11//!12//! Each key touches five consecutive power-of-two segments. Degree-one edges13//! peel normally. When blocked, select a minimum-positive-degree cell, keep its14//! first active key in sorted hash order, and abandon its other incident keys.15//! Intrusive degree buckets avoid repeated whole-graph scans. Each intervention16//! and peel removes keys, so there is no probabilistic restart or retry loop.17//! Reversed peel order assigns LE u16 main fingerprints.18//!19//! **The auxiliary is mandatory.** Every abandoned hash missed by the completed20//! main filter is stored in a sorted 64-bit auxiliary. A retained page-maxima21//! directory selects one auxiliary node; a main miss consults that node. This22//! implements the paper's two-stage semantics, with a larger auxiliary than its23//! prototype's Fuse F+8-bit filter and without the interleaved prototype layout.24//! This module exposes no false-negative "pure ZOR" variant. Canonical hash25//! collisions can add positives but cannot lose admitted keys.26//!27//! Under uniform nonmember hashes, the nominal main error is 2^-16; the28//! auxiliary contributes at most auxiliary_len/2^64 by a union bound. These are29//! fingerprint-model estimates, not adversarial guarantees. Original keys are30//! not retained. A positive answer requires an authoritative exact lookup.3132const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("zor.rs");3334use crate::hash::{XXH64_POLICY, hash_key};35use crate::{Collection, CollectionId, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};36use cdk_rsx_engine_nyxus::{Nyxus, NyxusData};37use core::marker::PhantomData;3839type RetainedVec<T> = std::vec::Vec<T, Nyxus>;40const ARITY: usize = 5;41const MAIN_PER_NODE: u32 = (NODE_BYTES / 2) as u32;42const AUX_PER_NODE: usize = NODE_BYTES / 8;43const NONE: u32 = u32::MAX;44const _: () = assert!(NODE_BYTES.is_multiple_of(8));4546pub const ZOR_POLICY: [u8; 32] = crate::contract(47 "MinimaZOR/arity5/xxh64/splitmix-addresses/u16-main/u64-sorted-aux/min-degree-first/v1",48 &[],49 &[SOURCE_POLICY, crate::MINIMA_POLICY, XXH64_POLICY],50);5152#[derive(Clone, Copy, Debug)]53pub struct ZorBuildConfig {54 pub max_entries: usize,55 pub max_cells: u32,56 pub max_auxiliary_entries: usize,57 /// Extra backing upper bound: 49*n + 18*cells +58 /// 8*ceil(n/512) + 8 bytes. Excludes consumed input keys, allocator59 /// bookkeeping, fixed stack and the shared node workspace; includes60 /// retained auxiliary directory backing while scratch remains live.61 pub max_work_bytes: usize,62 /// Power of two in 1..=65536. Five consecutive segments per key.63 pub segment_length: u32,64 /// Main cell target in thousandths of n, rounded to whole segments and65 /// at least five segments. Lower targets increase mandatory auxiliary work.66 pub main_cells_per_mille: u16,67 pub seed: u64,68}69impl Default for ZorBuildConfig {70 fn default() -> Self {71 Self {72 max_entries: 1_048_576,73 max_cells: 2_097_152,74 max_auxiliary_entries: 1_048_576,75 max_work_bytes: 128 * 1024 * 1024,76 segment_length: 256,77 main_cells_per_mille: 1000,78 seed: 0x5a4f_5232_3032_3635,79 }80 }81}82#[derive(Clone, Debug, PartialEq, Eq)]83pub enum ZorBuildError {84 InvalidConfig,85 Capacity,86 WorkLimit,87 DuplicateKey,88 Storage(Error),89}90impl From<Error> for ZorBuildError {91 fn from(error: Error) -> Self {92 Self::Storage(error)93 }94}95impl core::fmt::Display for ZorBuildError {96 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {97 write!(f, "{self:?}")98 }99}100impl std::error::Error for ZorBuildError {}101pub type ZorBuildResult<T> = core::result::Result<T, ZorBuildError>;102#[derive(Clone, Copy, Debug, PartialEq, Eq)]103pub struct ZorBuildStats {104 pub entries: u64,105 pub main_cells: u32,106 pub main_bytes: u64,107 pub segment_length: u32,108 pub segments: u32,109 pub kept: u32,110 pub abandoned: u32,111 pub interventions: u32,112 pub auxiliary_entries: u32,113 pub auxiliary_bytes: u64,114 pub auxiliary_directory_bytes: usize,115 pub work_bytes: usize,116}117#[repr(C)]118#[derive(Clone, Copy)]119struct Geometry {120 length: u32,121 segments: u32,122 cells: u32,123}124impl Geometry {125 fn positions(self, hash: u64) -> [u32; ARITY] {126 let starts = self.segments - ARITY as u32 + 1;127 let first =128 ((u128::from(mixed(hash ^ 0x2f97_c583_84aa_0d11)) * u128::from(starts)) >> 64) as u32;129 core::array::from_fn(|i| {130 let lane = hash.wrapping_add((i as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15));131 (first + i as u32) * self.length + (mixed(lane) as u32 & (self.length - 1))132 })133 }134}135#[repr(C)]136#[derive(Clone, Copy)]137struct Link {138 key: u32,139 pivot: u32,140}141const _: () = assert!(core::mem::size_of::<Link>() == 8);142143/// Move-only owner of both the main and exceptional-key stable payloads.144/// The auxiliary page directory is retained metadata, separate from payload.145#[repr(C)]146pub struct FrozenZor<K: FixedKey> {147 collection: Collection,148 auxiliary_max: RetainedVec<u64>,149 seed: u64,150 entries: u64,151 geometry: Geometry,152 kept: u32,153 abandoned: u32,154 interventions: u32,155 auxiliary_entries: u32,156 work_bytes: usize,157 key: PhantomData<fn() -> K>,158}159// SAFETY: Collection and Nyxus auxiliary directory own complete retained160// backing. Remaining fields are inline scalars and a zero-size marker.161unsafe impl<K: FixedKey> NyxusData for FrozenZor<K> {162 const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;163}164impl<K: FixedKey> FrozenZor<K> {165 pub const CONTRACT: [u8; 32] = crate::contract(166 "MinimaFrozenZor/FixedKey/v1",167 &[],168 &[ZOR_POLICY, K::CONTRACT],169 );170171 /// Build a complete filter from the exact set. Every input key is verified172 /// against the completed main plus auxiliary before stable allocation.173 /// Expected admission failures leave any existing owner untouched. Once174 /// stable writes start, provider failures trap for IC rollback.175 pub fn build(176 storage: &mut dyn Storage,177 mut keys: Vec<K>,178 config: ZorBuildConfig,179 workspace: &mut Workspace,180 ) -> ZorBuildResult<Self> {181 const {182 assert!(K::WIDTH <= NODE_BYTES, "ZOR key exceeds workspace");183 }184 if !config.segment_length.is_power_of_two()185 || config.segment_length > 65536186 || !(1..=2000).contains(&config.main_cells_per_mille)187 {188 return Err(ZorBuildError::InvalidConfig);189 }190 if keys.len() > config.max_entries || keys.len() > u32::MAX as usize / ARITY {191 return Err(ZorBuildError::Capacity);192 }193 let geometry = geometry(keys.len(), config)?;194 if geometry.cells > config.max_cells {195 return Err(ZorBuildError::Capacity);196 }197 let work_bytes = work_bytes(keys.len(), geometry.cells)?;198 if work_bytes > config.max_work_bytes {199 return Err(ZorBuildError::WorkLimit);200 }201 keys.sort_unstable();202 if keys.windows(2).any(|pair| pair[0] == pair[1]) {203 return Err(ZorBuildError::DuplicateKey);204 }205 let mut hashes = reserved(keys.len())?;206 for key in &keys {207 hashes.push(hash_key(key, config.seed, workspace));208 }209 hashes.sort_unstable();210 let mut builder = Builder::new(hashes, geometry)?;211 builder.peel();212 builder.assign();213 let mut auxiliary = reserved(keys.len())?;214 for (index, &hash) in builder.hashes.iter().enumerate() {215 if builder.state[index] == 2216 && !main_matches(&builder.values, geometry, hash)217 && auxiliary.last() != Some(&hash)218 {219 auxiliary.push(hash);220 }221 }222 if auxiliary.len() > config.max_auxiliary_entries {223 return Err(ZorBuildError::Capacity);224 }225 for key in &keys {226 let hash = hash_key(key, config.seed, workspace);227 assert!(228 main_matches(&builder.values, geometry, hash)229 || auxiliary.binary_search(&hash).is_ok(),230 "complete ZOR verification failed"231 );232 }233 let mut auxiliary_max = RetainedVec::new_in(Nyxus);234 auxiliary_max235 .try_reserve_exact(auxiliary.len().div_ceil(AUX_PER_NODE))236 .map_err(|_| ZorBuildError::WorkLimit)?;237 for page in auxiliary.chunks(AUX_PER_NODE) {238 auxiliary_max.push(*page.last().unwrap());239 }240 let mut collection = Collection::new(storage)?;241 let main_nodes = u64::from(geometry.cells).div_ceil(MAIN_PER_NODE as u64);242 let auxiliary_nodes = auxiliary.len().div_ceil(AUX_PER_NODE) as u64;243 collection.ensure_nodes(storage, main_nodes + auxiliary_nodes)?;244 for (page, chunk) in builder.values.chunks(MAIN_PER_NODE as usize).enumerate() {245 let bytes = &mut workspace.bytes_mut()[..chunk.len() * 2];246 for (i, value) in chunk.iter().enumerate() {247 bytes[2 * i..2 * i + 2].copy_from_slice(&value.to_le_bytes());248 }249 collection250 .write_at(storage, page as u64 * NODE_BYTES as u64, bytes)251 .unwrap_or_else(|error| panic!("ZOR stable write failed: {error}"));252 }253 for (page, chunk) in auxiliary.chunks(AUX_PER_NODE).enumerate() {254 let bytes = &mut workspace.bytes_mut()[..chunk.len() * 8];255 for (i, value) in chunk.iter().enumerate() {256 bytes[8 * i..8 * i + 8].copy_from_slice(&value.to_le_bytes());257 }258 collection259 .write_at(260 storage,261 (main_nodes + page as u64) * NODE_BYTES as u64,262 bytes,263 )264 .unwrap_or_else(|error| panic!("ZOR auxiliary stable write failed: {error}"));265 }266 Ok(Self {267 collection,268 auxiliary_max,269 seed: config.seed,270 entries: keys.len() as u64,271 geometry,272 kept: builder.order.len() as u32,273 abandoned: builder.abandoned,274 interventions: builder.interventions,275 auxiliary_entries: auxiliary.len() as u32,276 work_bytes,277 key: PhantomData,278 })279 }280 pub fn replace(281 &mut self,282 storage: &mut dyn Storage,283 keys: Vec<K>,284 config: ZorBuildConfig,285 workspace: &mut Workspace,286 ) -> ZorBuildResult<()> {287 self.collection.validate(storage)?;288 *self = Self::build(storage, keys, config, workspace)?;289 Ok(())290 }291 /// No false negatives for admitted keys. A positive result, including an292 /// auxiliary match, must be confirmed using the authoritative exact set.293 pub fn may_contain(294 &self,295 storage: &dyn Storage,296 key: &K,297 workspace: &mut Workspace,298 ) -> Result<bool> {299 if self.is_empty() {300 self.collection.validate(storage)?;301 return Ok(false);302 }303 let hash = hash_key(key, self.seed, workspace);304 if self.main_match_hash(storage, hash, workspace)? {305 return Ok(true);306 }307 let page = self308 .auxiliary_max309 .partition_point(|&maximum| maximum < hash);310 if page == self.auxiliary_max.len() {311 return Ok(false);312 }313 let count = (self.auxiliary_entries as usize - page * AUX_PER_NODE).min(AUX_PER_NODE);314 let offset = (u64::from(self.geometry.cells).div_ceil(MAIN_PER_NODE as u64) + page as u64)315 * NODE_BYTES as u64;316 let bytes = &mut workspace.bytes_mut()[..count * 8];317 self.collection.read_at(storage, offset, bytes)?;318 let mut low = 0;319 let mut high = count;320 while low < high {321 let middle = low + (high - low) / 2;322 let value = u64::from_le_bytes(bytes[8 * middle..8 * middle + 8].try_into().unwrap());323 if value < hash {324 low = middle + 1;325 } else if value > hash {326 high = middle;327 } else {328 return Ok(true);329 }330 }331 Ok(false)332 }333 fn main_match_hash(334 &self,335 storage: &dyn Storage,336 hash: u64,337 workspace: &mut Workspace,338 ) -> Result<bool> {339 let cells = self.geometry.positions(hash);340 let mut answer = fingerprint(hash);341 let mut first = 0;342 while first < ARITY {343 let mut end = first + 1;344 while end < ARITY && cells[end] / MAIN_PER_NODE == cells[first] / MAIN_PER_NODE {345 end += 1;346 }347 let low = cells[first];348 let span = (cells[end - 1] - low + 1) as usize * 2;349 let bytes = &mut workspace.bytes_mut()[..span];350 self.collection351 .read_at(storage, u64::from(low) * 2, bytes)?;352 for &cell in &cells[first..end] {353 let at = (cell - low) as usize * 2;354 answer ^= u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap());355 }356 first = end;357 }358 Ok(answer == 0)359 }360 pub const fn len(&self) -> u64 {361 self.entries362 }363 pub const fn is_empty(&self) -> bool {364 self.entries == 0365 }366 pub const fn seed(&self) -> u64 {367 self.seed368 }369 pub const fn identity(&self) -> CollectionId {370 self.collection.identity()371 }372 pub fn block_count(&self) -> usize {373 self.collection.block_count()374 }375 pub fn stats(&self) -> ZorBuildStats {376 ZorBuildStats {377 entries: self.entries,378 main_cells: self.geometry.cells,379 main_bytes: u64::from(self.geometry.cells) * 2,380 segment_length: self.geometry.length,381 segments: self.geometry.segments,382 kept: self.kept,383 abandoned: self.abandoned,384 interventions: self.interventions,385 auxiliary_entries: self.auxiliary_entries,386 auxiliary_bytes: u64::from(self.auxiliary_entries) * 8,387 auxiliary_directory_bytes: self.auxiliary_max.capacity() * 8,388 work_bytes: self.work_bytes,389 }390 }391}392fn geometry(entries: usize, config: ZorBuildConfig) -> ZorBuildResult<Geometry> {393 if entries == 0 {394 return Ok(Geometry {395 length: config.segment_length,396 segments: 0,397 cells: 0,398 });399 }400 let requested = (entries as u64 * u64::from(config.main_cells_per_mille)).div_ceil(1000);401 let segments = requested402 .div_ceil(u64::from(config.segment_length))403 .max(ARITY as u64);404 let cells = segments * u64::from(config.segment_length);405 if cells >= u64::from(u32::MAX) {406 return Err(ZorBuildError::Capacity);407 }408 Ok(Geometry {409 length: config.segment_length,410 segments: segments as u32,411 cells: cells as u32,412 })413}414fn work_bytes(n: usize, cells: u32) -> ZorBuildResult<usize> {415 n.checked_mul(49)416 .and_then(|sum| sum.checked_add(cells as usize * 18))417 .and_then(|sum| sum.checked_add(n.div_ceil(AUX_PER_NODE) * 8 + 8))418 .ok_or(ZorBuildError::WorkLimit)419}420fn reserved<T>(len: usize) -> ZorBuildResult<Vec<T>> {421 let mut out = Vec::new();422 out.try_reserve_exact(len)423 .map_err(|_| ZorBuildError::WorkLimit)?;424 Ok(out)425}426fn zeroed<T: Copy>(len: usize, value: T) -> ZorBuildResult<Vec<T>> {427 let mut out = reserved(len)?;428 out.resize(len, value);429 Ok(out)430}431fn mixed(mut x: u64) -> u64 {432 x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);433 x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);434 x ^ (x >> 31)435}436fn fingerprint(hash: u64) -> u16 {437 (mixed(hash ^ 0x8267_9c38_d3f4_eaa9) >> 48) as u16438}439fn main_matches(values: &[u16], geometry: Geometry, hash: u64) -> bool {440 geometry441 .positions(hash)442 .into_iter()443 .fold(fingerprint(hash), |value, cell| {444 value ^ values[cell as usize]445 })446 == 0447}448449struct Builder {450 hashes: Vec<u64>,451 geometry: Geometry,452 degrees: Vec<u32>,453 offsets: Vec<u32>,454 incidence: Vec<u32>,455 previous: Vec<u32>,456 next: Vec<u32>,457 heads: Vec<u32>,458 state: Vec<u8>,459 order: Vec<Link>,460 values: Vec<u16>,461 minimum: usize,462 abandoned: u32,463 interventions: u32,464}465impl Builder {466 fn new(hashes: Vec<u64>, geometry: Geometry) -> ZorBuildResult<Self> {467 let cells = geometry.cells as usize;468 let mut degrees = zeroed(cells, 0u32)?;469 for &hash in &hashes {470 for cell in geometry.positions(hash) {471 degrees[cell as usize] += 1;472 }473 }474 let maximum = degrees.iter().copied().max().unwrap_or(0);475 let mut offsets = zeroed(cells + 1, 0u32)?;476 // Admission proves ARITY*n fits u32; incidence offsets cannot wrap.477 for i in 0..cells {478 offsets[i + 1] = offsets[i] + degrees[i];479 }480 let mut previous = reserved::<u32>(cells)?;481 previous.extend_from_slice(&offsets[..cells]);482 let mut incidence = zeroed(offsets[cells] as usize, 0u32)?;483 for (key, &hash) in hashes.iter().enumerate() {484 for cell in geometry.positions(hash) {485 let cursor = &mut previous[cell as usize];486 incidence[*cursor as usize] = key as u32;487 *cursor += 1;488 }489 }490 previous.fill(NONE);491 let mut result = Self {492 state: zeroed(hashes.len(), 1u8)?,493 order: reserved(hashes.len())?,494 values: zeroed(cells, 0u16)?,495 next: zeroed(cells, NONE)?,496 heads: zeroed(maximum as usize + 1, NONE)?,497 minimum: 1,498 abandoned: 0,499 interventions: 0,500 hashes,501 geometry,502 degrees,503 offsets,504 incidence,505 previous,506 };507 for vertex in 0..cells {508 if result.degrees[vertex] > 0 {509 result.add_vertex(vertex as u32);510 }511 }512 Ok(result)513 }514 fn add_vertex(&mut self, vertex: u32) {515 let at = vertex as usize;516 let degree = self.degrees[at] as usize;517 let old = self.heads[degree];518 self.next[at] = old;519 self.previous[at] = NONE;520 if old != NONE {521 self.previous[old as usize] = vertex;522 }523 self.heads[degree] = vertex;524 }525 fn decrement(&mut self, vertex: u32) {526 let at = vertex as usize;527 let degree = self.degrees[at] as usize;528 let previous = self.previous[at];529 let next = self.next[at];530 if previous == NONE {531 self.heads[degree] = next;532 } else {533 self.next[previous as usize] = next;534 }535 if next != NONE {536 self.previous[next as usize] = previous;537 }538 self.degrees[at] -= 1;539 if degree > 1 {540 self.add_vertex(vertex);541 self.minimum = self.minimum.min(degree - 1);542 }543 }544 fn remove_key(&mut self, key: u32, abandon: bool) {545 self.state[key as usize] = if abandon { 2 } else { 0 };546 if abandon {547 self.abandoned += 1;548 }549 for vertex in self.geometry.positions(self.hashes[key as usize]) {550 self.decrement(vertex);551 }552 }553 fn peel(&mut self) {554 let mut remaining = self.hashes.len();555 while remaining > 0 {556 while self.minimum < self.heads.len() && self.heads[self.minimum] == NONE {557 self.minimum += 1;558 }559 let vertex = self.heads[self.minimum];560 let begin = self.offsets[vertex as usize] as usize;561 let end = self.offsets[vertex as usize + 1] as usize;562 let keep = (begin..end)563 .map(|at| self.incidence[at])564 .find(|&key| self.state[key as usize] == 1)565 .expect("active ZOR incidence");566 if self.minimum > 1 {567 self.interventions += 1;568 for at in begin..end {569 let key = self.incidence[at];570 if key != keep && self.state[key as usize] == 1 {571 self.remove_key(key, true);572 remaining -= 1;573 }574 }575 }576 self.order.push(Link {577 key: keep,578 pivot: vertex,579 });580 self.remove_key(keep, false);581 remaining -= 1;582 }583 }584 fn assign(&mut self) {585 for link in self.order.iter().rev() {586 let hash = self.hashes[link.key as usize];587 let mut value = fingerprint(hash);588 for vertex in self.geometry.positions(hash) {589 if vertex != link.pivot {590 value ^= self.values[vertex as usize];591 }592 }593 self.values[link.pivot as usize] = value;594 }595 }596}597598#[cfg(test)]599#[path = "zor_tests.rs"]600mod tests;