omni_sketch.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/omni_sketch.rs
1//! OmniSketch S1, the published append-only cash-register variant.2//!3//! Configured attributes each own a ROWS x WIDTH Count-Min array. A cell stores4//! its record count and the SAMPLES smallest common record-id hashes. Queries5//! select equality predicates on any subset of these attributes, intersect all6//! selected cell samples, and use Section 3.2 / equation (4)'s n_max/B scaling.7//! When n_max<B all selected streams are unsampled, so the scaling is one.8//!9//! Each append must have a fresh globally unique record identity with immutable10//! attributes. Repeated IDs, mutable rows and deletions are outside this S111//! model; there is no claim of S2's bounded-delete support or range predicates.12//! Merge requires disjoint record identities. The sketch cannot verify those13//! assumptions without retaining the original stream.14//!15//! Each fixed cell contains its header and sorted u64 signatures. Complete cells16//! are packed into aligned 4 KiB nodes without crossing a node boundary;17//! collection-owned stable allocation uses whole exclusive 64 KiB blocks.18//! The retained descriptor stores no ordinary19//! Vec/String or provider. Updates and queries use borrowed workspace last;20//! queries / merge also use at most SAMPLES*8 bytes of bounded stack scratch.21//! See `omni_sketch_provenance.md` for precise scope and primary sources.2223const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("omni_sketch.rs");2425use crate::hash::{XXH64_POLICY, Xxh64Word, hash_key};26use crate::{Collection, CollectionId, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};27use cdk_rsx_engine_nyxus::NyxusData;28use core::marker::PhantomData;2930const HEADER: usize = 16;31const MAX_SELECTED: usize = 64;3233/// One equality predicate. Each configured attribute may occur at most once in34/// a query. An empty predicate slice counts the entire append stream exactly.35#[derive(Clone, Copy, Debug, PartialEq, Eq)]36pub struct OmniPredicate<V> {37 pub attribute: usize,38 pub value: V,39}4041#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]42pub struct OmniUpdate {43 pub cells_read: u32,44 pub cells_written: u32,45 pub samples_changed: u32,46}4748#[derive(Clone, Copy, Debug, PartialEq)]49pub struct OmniEstimate {50 pub estimate: f64,51 pub intersection_samples: u32,52 pub max_cell_count: u64,53 pub sampled: bool,54 /// Logical selected cells, each inspected once. Packed cells can share one55 /// provider read without changing this count.56 pub cells_read: u32,57}5859/// S1 retained owner. ATTRS<=8, ROWS<=8, WIDTH<=256, SAMPLES<=510 and60/// ATTRS*ROWS*WIDTH<=4096 provide fixed work / stable-payload bounds.61/// The default geometry for three attributes uses 96 nodes / 6 whole blocks.62///63/// ```compile_fail64/// use cdk_rsx_collections_minima::{Arena, omni_sketch::OmniSketch};65/// use cdk_rsx_platform::VecMemory;66/// let mut arena = Arena::format(VecMemory::new()).unwrap();67/// let _ = OmniSketch::<u64,u64,3,3,32,511>::new(&mut arena, 0);68/// ```69#[repr(C)]70pub struct OmniSketch<71 K: FixedKey,72 V: FixedKey,73 const ATTRS: usize,74 const ROWS: usize = 3,75 const WIDTH: usize = 32,76 const SAMPLES: usize = 128,77> {78 collection: Collection,79 seed: u64,80 count: u64,81 types: PhantomData<fn() -> (K, V)>,82}83// SAFETY: Collection and inline scalars are the complete retained graph.84// PhantomData owns no K or V. No provider, borrowed bytes or ordinary Vec exists.85unsafe impl<86 K: FixedKey,87 V: FixedKey,88 const A: usize,89 const R: usize,90 const W: usize,91 const B: usize,92> NyxusData for OmniSketch<K, V, A, R, W, B>93{94 const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;95}9697impl<K: FixedKey, V: FixedKey, const A: usize, const R: usize, const W: usize, const B: usize>98 OmniSketch<K, V, A, R, W, B>99{100 pub const CELL_COUNT: usize = {101 assert!(A >= 1 && A <= 8, "OmniSketch attributes must be in 1..=8");102 assert!(R >= 1 && R <= 8, "OmniSketch rows must be in 1..=8");103 assert!(W >= 1 && W <= 256, "OmniSketch width must be in 1..=256");104 assert!(105 B >= 2 && HEADER + B * 8 <= NODE_BYTES,106 "OmniSketch samples must be in 2..=510"107 );108 assert!(A * R * W <= 4096, "OmniSketch exceeds 4096 cells");109 A * R * W110 };111 /// Fixed cell span, including all possible samples. The checked geometry112 /// guarantees at least one complete cell fits in each logical node.113 pub const CELL_BYTES: usize = {114 let _ = Self::CELL_COUNT;115 HEADER + B * 8116 };117 pub const CELLS_PER_NODE: usize = NODE_BYTES / Self::CELL_BYTES;118 pub const NODE_COUNT: usize = Self::CELL_COUNT.div_ceil(Self::CELLS_PER_NODE);119 pub const CONTRACT: [u8; 32] = crate::contract(120 "MinimaOmniSketch/S1/AppendOnly/EqualityConjunction/DisjointMerge/v1",121 &["4KiB-node/complete-packed-cells/LE-count-u64,len-u32,pad4,sorted-u64-samples/bottomB"],122 &[123 SOURCE_POLICY,124 K::CONTRACT,125 V::CONTRACT,126 XXH64_POLICY,127 crate::MINIMA_POLICY,128 crate::width_contract("omni-attributes", A, &[]),129 crate::width_contract("omni-rows", R, &[]),130 crate::width_contract("omni-width", W, &[]),131 crate::width_contract("omni-samples", B, &[]),132 crate::width_contract("omni-cell-count", Self::CELL_COUNT, &[]),133 crate::width_contract("omni-cell-bytes", Self::CELL_BYTES, &[]),134 crate::width_contract("omni-cells-per-node", Self::CELLS_PER_NODE, &[]),135 crate::width_contract("omni-node-count", Self::NODE_COUNT, &[]),136 ],137 );138139 pub fn new(storage: &mut dyn Storage, seed: u64) -> Result<Self> {140 const {141 assert!(A >= 1 && A <= 8, "OmniSketch attributes must be in 1..=8");142 assert!(R >= 1 && R <= 8, "OmniSketch rows must be in 1..=8");143 assert!(W >= 1 && W <= 256, "OmniSketch width must be in 1..=256");144 assert!(145 B >= 2 && HEADER + B * 8 <= NODE_BYTES,146 "OmniSketch samples must be in 2..=510"147 );148 assert!(A * R * W <= 4096, "OmniSketch exceeds 4096 cells");149 assert!(150 K::WIDTH <= NODE_BYTES && V::WIDTH <= NODE_BYTES,151 "OmniSketch fixed key exceeds workspace"152 );153 }154 Ok(Self {155 collection: Collection::new(storage)?,156 seed,157 count: 0,158 types: PhantomData,159 })160 }161 pub const fn identity(&self) -> CollectionId {162 self.collection.identity()163 }164 pub const fn seed(&self) -> u64 {165 self.seed166 }167 pub const fn count(&self) -> u64 {168 self.count169 }170 pub fn allocated_blocks(&self) -> usize {171 self.collection.block_count()172 }173174 /// Append one fresh record. The caller must never reuse its identity or175 /// change its attributes. Total count overflow rejects before allocation or176 /// writes; each cell count is bounded by that total, so cannot overflow.177 pub fn append(178 &mut self,179 storage: &mut dyn Storage,180 record_id: &K,181 attributes: &[V; A],182 workspace: &mut Workspace<'_>,183 ) -> Result<OmniUpdate> {184 self.collection.validate(storage)?;185 let next_count = self.count.checked_add(1).ok_or(Error::Overflow)?;186 let record_hash = hash_key(record_id, self.seed ^ 0x4f6d_6e69_5361_6d70, workspace);187 let mut cells = [0u64; MAX_SELECTED];188 for (attribute, value) in attributes.iter().enumerate() {189 let hash = Xxh64Word::new(hash_key(190 value,191 self.seed ^ 0x4f6d_6e69_4174_7472,192 workspace,193 ));194 for row in 0..R {195 cells[attribute * R + row] = Self::cell(&hash, attribute, row, self.seed);196 }197 }198 // Allocation failures are physical mutation faults, not normal business199 // rejection after a prefix of the fixed directory has been installed.200 self.collection201 .ensure_nodes(storage, Self::NODE_COUNT as u64)202 .expect("OmniSketch admitted payload allocation");203 let mut stats = OmniUpdate::default();204 for &cell in &cells[..A * R] {205 self.collection206 .read_at(207 storage,208 Self::cell_offset(cell),209 &mut workspace.bytes_mut()[..Self::CELL_BYTES],210 )211 .expect("OmniSketch admitted append read");212 let (count, len) = self213 .header(workspace.bytes())214 .expect("OmniSketch admitted cell header");215 stats.cells_read += 1;216 let bytes = workspace.bytes_mut();217 let write_len = if insert_sample::<B>(bytes, len, record_hash) {218 stats.samples_changed += 1;219 HEADER + (len + 1).min(B) * 8220 } else {221 8222 };223 bytes[..8].copy_from_slice(&(count + 1).to_le_bytes());224 self.collection225 .write_at(226 storage,227 Self::cell_offset(cell),228 &workspace.bytes()[..write_len],229 )230 .expect("OmniSketch admitted append write");231 stats.cells_written += 1;232 }233 self.count = next_count;234 Ok(stats)235 }236237 /// Estimate a conjunction over any configured subset of attributes. This238 /// is a statistical estimate, not a membership oracle or exact row query.239 /// Small intersections can have high relative error even with large B.240 pub fn query(241 &self,242 storage: &dyn Storage,243 predicates: &[OmniPredicate<V>],244 workspace: &mut Workspace<'_>,245 ) -> Result<OmniEstimate> {246 if predicates.len() > A {247 return Err(Error::Capacity);248 }249 let mut seen = 0u16;250 for predicate in predicates {251 if predicate.attribute >= A || seen & (1 << predicate.attribute) != 0 {252 return Err(Error::InvalidInput(253 "OmniSketch predicate attribute missing or repeated",254 ));255 }256 seen |= 1 << predicate.attribute;257 }258 self.collection.validate(storage)?;259 if predicates.is_empty() || self.count == 0 {260 return Ok(OmniEstimate {261 estimate: if predicates.is_empty() {262 self.count as f64263 } else {264 0.0265 },266 intersection_samples: 0,267 max_cell_count: self.count,268 sampled: false,269 cells_read: 0,270 });271 }272 let selected = predicates.len() * R;273 let mut cells = [0u64; MAX_SELECTED];274 for (index, predicate) in predicates.iter().enumerate() {275 let hash = Xxh64Word::new(hash_key(276 &predicate.value,277 self.seed ^ 0x4f6d_6e69_4174_7472,278 workspace,279 ));280 for row in 0..R {281 cells[index * R + row] = Self::cell(&hash, predicate.attribute, row, self.seed);282 }283 }284 // Valid predicates select distinct attribute/row cells. Sorting is285 // needed only when packed cells can share a logical source node;286 // bottom-B intersection and maximum count are independent of order.287 if Self::CELLS_PER_NODE > 1 {288 cells[..selected].sort_unstable();289 }290 let mut max_count = 0;291 let mut candidates = [0u64; B];292 let mut len = 0;293 let mut start = 0;294 while start < selected {295 let node = cells[start] / Self::CELLS_PER_NODE as u64;296 let mut end = start + 1;297 while end < selected && cells[end] / Self::CELLS_PER_NODE as u64 == node {298 end += 1;299 }300 let at = Self::cell_offset(cells[start]);301 let used = (Self::cell_offset(cells[end - 1]) - at) as usize + Self::CELL_BYTES;302 // Read the bounding complete-cell span once. Its source stays in303 // one logical node, preserving first-read eligibility when that304 // node was untouched. Unselected cells in a gap are not decoded.305 self.collection306 .read_at(storage, at, &mut workspace.bytes_mut()[..used])?;307 for (index, &cell) in cells[start..end].iter().enumerate() {308 let offset = (Self::cell_offset(cell) - at) as usize;309 let bytes = &workspace.bytes()[offset..offset + Self::CELL_BYTES];310 let (count, other_len) = self.header(bytes)?;311 max_count = max_count.max(count);312 if start == 0 && index == 0 {313 len = other_len;314 for (index, candidate) in candidates[..len].iter_mut().enumerate() {315 *candidate = sample(bytes, index);316 }317 } else if len != 0 {318 let (mut a, mut b, mut write) = (0, 0, 0);319 while a < len && b < other_len {320 match candidates[a].cmp(&sample(bytes, b)) {321 core::cmp::Ordering::Less => a += 1,322 core::cmp::Ordering::Greater => b += 1,323 core::cmp::Ordering::Equal => {324 candidates[write] = candidates[a];325 write += 1;326 a += 1;327 b += 1;328 }329 }330 }331 len = write;332 }333 }334 start = end;335 }336 let scale = (max_count as f64 / B as f64).max(1.0);337 Ok(OmniEstimate {338 estimate: len as f64 * scale,339 intersection_samples: len as u32,340 max_cell_count: max_count,341 sampled: max_count > B as u64,342 cells_read: selected as u32,343 })344 }345346 /// Merge S1 summaries of disjoint record streams. Disjointness is a caller347 /// precondition; the bounded sample cannot verify global record identity.348 /// All config/seed/authority checks and count overflow precede mutation.349 pub fn merge_disjoint<350 QK: FixedKey,351 QV: FixedKey,352 const QA: usize,353 const QR: usize,354 const QW: usize,355 const QB: usize,356 >(357 &mut self,358 storage: &mut dyn Storage,359 other: &OmniSketch<QK, QV, QA, QR, QW, QB>,360 other_workspace: &mut Workspace<'_>,361 workspace: &mut Workspace<'_>,362 ) -> Result<OmniUpdate> {363 if Self::CONTRACT != OmniSketch::<QK, QV, QA, QR, QW, QB>::CONTRACT364 || self.seed != other.seed365 {366 return Err(Error::InvalidInput(367 "incompatible OmniSketch contract or seed",368 ));369 }370 self.collection.validate(storage)?;371 other.collection.validate(storage)?;372 let next_count = self.count.checked_add(other.count).ok_or(Error::Overflow)?;373 let mut stats = OmniUpdate::default();374 if other.count == 0 {375 return Ok(stats);376 }377 self.collection378 .ensure_nodes(storage, Self::NODE_COUNT as u64)379 .expect("OmniSketch admitted merge allocation");380 let mut merged = [0u64; B];381 for cell in 0..Self::CELL_COUNT {382 self.collection383 .read_at(384 storage,385 Self::cell_offset(cell as u64),386 &mut workspace.bytes_mut()[..Self::CELL_BYTES],387 )388 .expect("OmniSketch admitted merge destination read");389 other390 .collection391 .read_at(392 storage,393 Self::cell_offset(cell as u64),394 &mut other_workspace.bytes_mut()[..Self::CELL_BYTES],395 )396 .expect("OmniSketch admitted merge source read");397 let source = other_workspace.bytes();398 let (a_count, a_len) = self399 .header(workspace.bytes())400 .expect("OmniSketch admitted destination header");401 let (b_count, b_len) = other402 .header(source)403 .expect("OmniSketch admitted source header");404 stats.cells_read += 2;405 if b_count == 0 {406 continue;407 }408 let (mut a, mut b, mut len) = (0, 0, 0);409 while len < B && (a < a_len || b < b_len) {410 let value = if b == b_len411 || (a < a_len && sample(workspace.bytes(), a) < sample(source, b))412 {413 let value = sample(workspace.bytes(), a);414 a += 1;415 value416 } else if a == a_len || sample(source, b) < sample(workspace.bytes(), a) {417 let value = sample(source, b);418 b += 1;419 value420 } else {421 let value = sample(source, b);422 a += 1;423 b += 1;424 value425 };426 merged[len] = value;427 len += 1;428 }429 let bytes = workspace.bytes_mut();430 bytes[..8].copy_from_slice(&(a_count + b_count).to_le_bytes());431 bytes[8..12].copy_from_slice(&(len as u32).to_le_bytes());432 for (index, value) in merged[..len].iter().enumerate() {433 set_sample(bytes, index, *value);434 }435 self.collection436 .write_at(437 storage,438 Self::cell_offset(cell as u64),439 &workspace.bytes()[..HEADER + len * 8],440 )441 .expect("OmniSketch admitted merge write");442 stats.cells_written += 1;443 stats.samples_changed += 1;444 }445 self.count = next_count;446 Ok(stats)447 }448449 pub fn clear(&mut self, storage: &mut dyn Storage) -> Result<()> {450 self.collection.truncate_nodes(storage, 0)?;451 self.count = 0;452 Ok(())453 }454 fn cell(value_hash: &Xxh64Word, attribute: usize, row: usize, seed: u64) -> u64 {455 let domain = (attribute * R + row) as u64;456 let hash = value_hash457 .hash(seed ^ 0x4f6d_6e69_4365_6c6c ^ domain.wrapping_mul(0x9e37_79b1_85eb_ca87));458 ((attribute * R + row) * W + (hash % W as u64) as usize) as u64459 }460 fn cell_offset(cell: u64) -> u64 {461 cell / Self::CELLS_PER_NODE as u64 * NODE_BYTES as u64462 + cell % Self::CELLS_PER_NODE as u64 * Self::CELL_BYTES as u64463 }464 fn header(&self, bytes: &[u8]) -> Result<(u64, usize)> {465 let count = u64::from_le_bytes(bytes[..8].try_into().unwrap());466 let len = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;467 if count > self.count || len > B || len as u64 > count || (count == 0) != (len == 0) {468 return Err(Error::Corrupt("OmniSketch cell count or sample length"));469 }470 Ok((count, len))471 }472}473474fn sample(bytes: &[u8], index: usize) -> u64 {475 let at = HEADER + index * 8;476 u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())477}478fn set_sample(bytes: &mut [u8; NODE_BYTES], index: usize, value: u64) {479 let at = HEADER + index * 8;480 bytes[at..at + 8].copy_from_slice(&value.to_le_bytes());481}482fn insert_sample<const B: usize>(bytes: &mut [u8; NODE_BYTES], len: usize, hash: u64) -> bool {483 let (mut low, mut high) = (0, len);484 while low < high {485 let mid = (low + high) / 2;486 if sample(bytes, mid) < hash {487 low = mid + 1;488 } else {489 high = mid;490 }491 }492 if low < len && sample(bytes, low) == hash {493 return false;494 }495 if low >= B {496 return false;497 }498 let next_len = (len + 1).min(B);499 bytes.copy_within(500 HEADER + low * 8..HEADER + (next_len - 1) * 8,501 HEADER + (low + 1) * 8,502 );503 set_sample(bytes, low, hash);504 bytes[8..12].copy_from_slice(&(next_len as u32).to_le_bytes());505 true506}507508#[cfg(test)]509#[path = "omni_sketch_tests.rs"]510mod tests;