set_sketch.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/set_sketch.rs
1//! SetSketch with independent exponential hashes (Ertl, 2021, equation 6).2//!3//! This is the uncorrelated SetSketch distribution, without the ordered-update4//! acceleration. An observation hashes every register; a conservative page5//! bound skips logarithms for candidates that cannot increase it. Registers are LE u16;6//! the base is `BASE_MILLI / 1000`, the exponential rate is 20, and values are7//! clamped to `0..=MAX_RANK`. Estimation uses Appendix B's corrected estimator8//! and Section 3.2's one-dimensional joint likelihood, not HLL or inclusion /9//! exclusion. There is no membership, enumeration, deletion or exact count API.10//!11//! The 52-bit midpoint exponential variates are deterministic from pinned12//! XXH64. Statistical accuracy assumes uniform hashes and is not an adversarial13//! bound. Very large cardinalities eventually exhaust that finite hash source.14//! Every nonempty allocation owns at least one complete 64 KiB block, regardless15//! of the register payload. Scratch is exactly the caller's borrowed workspace;16//! joint queries / merges require a second borrowed node buffer.17//!18//! Independently implemented from <https://arxiv.org/abs/2101.00314v3>.19//! See `set_sketch_provenance.md`; no research-only reference code is included.2021const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("set_sketch.rs");2223use crate::hash::{XXH64_POLICY, Xxh64Pair, Xxh64Word, hash_key};24use crate::{Collection, CollectionId, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};25use cdk_rsx_engine_nyxus::NyxusData;26use core::marker::PhantomData;2728#[derive(Clone, Copy, Debug, PartialEq, Eq)]29pub enum SetSketchStatus {30 Estimated,31 RegisterRangeSaturated,32}3334#[derive(Clone, Copy, Debug, PartialEq)]35pub struct SetSketchEstimate {36 pub estimate: f64,37 pub nominal_relative_error: f64,38 pub zero_registers: u32,39 pub saturated_registers: u32,40 pub status: SetSketchStatus,41}4243#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]44pub struct SetSketchUpdate {45 pub registers_increased: u32,46 pub pages_read: u32,47 pub pages_written: u32,48}4950pub const SET_SKETCH_MAX_BATCH: usize = 4096;51pub const SET_SKETCH_MAX_JOINT_BATCH: usize = 4096;5253/// Caller-owned transient preparation, overwritten for every admitted key.54/// It holds only a prepared hash lane, with no retained collection authority.55pub struct SetSketchBatchEntry {56 hashes: Xxh64Pair,57}58impl Default for SetSketchBatchEntry {59 fn default() -> Self {60 Self {61 hashes: Xxh64Pair::new(0, 0),62 }63 }64}6566#[derive(Clone, Copy, Debug, Default, PartialEq)]67pub struct SetSketchJointEstimate {68 pub left: f64,69 pub right: f64,70 pub union: f64,71 pub intersection: f64,72 /// By convention two empty sets have Jaccard similarity one.73 pub jaccard: f64,74 pub left_greater_registers: u32,75 pub right_greater_registers: u32,76 pub equal_registers: u32,77}7879/// Move-only retained descriptor; no provider, ordinary allocator container,80/// register cache, function pointer or borrowed workspace is retained.81/// `M` is bounded to 32,768, so the LE u16 payload is at most one 64 KiB block.82///83/// ```compile_fail84/// use cdk_rsx_collections_minima::{Arena, set_sketch::SetSketch};85/// use cdk_rsx_platform::VecMemory;86/// let mut arena = Arena::format(VecMemory::new()).unwrap();87/// let _ = SetSketch::<u64, 0>::new(&mut arena, 0);88/// ```89#[repr(C)]90pub struct SetSketch<91 K: FixedKey,92 const M: usize = 1024,93 const BASE_MILLI: u32 = 1001,94 const MAX_RANK: u16 = 65_535,95> {96 collection: Collection,97 seed: u64,98 key: PhantomData<fn() -> K>,99}100101// SAFETY: Collection owns retained Nyxus authority and blocks; remaining fields102// are inline integers / a non-owning phantom. No K instance is persisted.103unsafe impl<K: FixedKey, const M: usize, const B: u32, const Q: u16> NyxusData104 for SetSketch<K, M, B, Q>105{106 const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;107}108109impl<K: FixedKey, const M: usize, const B: u32, const Q: u16> SetSketch<K, M, B, Q> {110 pub const REGISTER_COUNT: usize = {111 assert!(M >= 16 && M <= 32_768, "SetSketch M must be in 16..=32768");112 assert!(113 B >= 1001 && B <= 2000,114 "SetSketch base must be in 1.001..=2"115 );116 assert!(Q >= 2, "SetSketch maximum rank must be at least two");117 M118 };119 pub const PAYLOAD_BYTES: usize = Self::REGISTER_COUNT * 2;120 pub const PAGE_COUNT: usize = Self::PAYLOAD_BYTES.div_ceil(NODE_BYTES);121 pub const CONTRACT: [u8; 32] = crate::contract(122 "MinimaSetSketch/IndependentExponential/CorrectedCardinality/JointML/v1",123 &["LE-u16/register-max/rate20/xxh64(key);xxh64(LE-keyhash,LE-register)/52-midpoint"],124 &[125 SOURCE_POLICY,126 K::CONTRACT,127 XXH64_POLICY,128 crate::width_contract("set-sketch-registers", Self::REGISTER_COUNT, &[]),129 crate::width_contract("set-sketch-base-milli", B as usize, &[]),130 crate::width_contract("set-sketch-max-rank", Q as usize, &[]),131 crate::MINIMA_POLICY,132 ],133 );134135 pub fn new(storage: &mut dyn Storage, seed: u64) -> Result<Self> {136 const {137 assert!(M >= 16 && M <= 32_768, "SetSketch M must be in 16..=32768");138 assert!(139 B >= 1001 && B <= 2000,140 "SetSketch base must be in 1.001..=2"141 );142 assert!(Q >= 2, "SetSketch maximum rank must be at least two");143 assert!(K::WIDTH <= NODE_BYTES, "SetSketch key exceeds workspace");144 }145 Ok(Self {146 collection: Collection::new(storage)?,147 seed,148 key: PhantomData,149 })150 }151152 pub const fn identity(&self) -> CollectionId {153 self.collection.identity()154 }155 pub const fn seed(&self) -> u64 {156 self.seed157 }158 pub fn allocated_blocks(&self) -> usize {159 self.collection.block_count()160 }161 pub fn base() -> f64 {162 B as f64 / 1000.0163 }164 pub fn nominal_relative_error() -> f64 {165 let b = Self::base();166 (((b + 1.0) / (b - 1.0) * b.ln() - 1.0) / M as f64).sqrt()167 }168169 /// O(M) independent-hash update. Reads each used node once; only changed170 /// nodes are written. Duplicate observations produce no further writes.171 pub fn observe(172 &mut self,173 storage: &mut dyn Storage,174 key: &K,175 workspace: &mut Workspace<'_>,176 ) -> Result<SetSketchUpdate> {177 self.collection.validate(storage)?;178 let key_hash = hash_key(key, self.seed, workspace);179 let hashes = Xxh64Pair::new(key_hash, self.seed ^ 0x5365_7453_6b65_7463);180 self.collection181 .ensure_nodes(storage, Self::PAGE_COUNT as u64)?;182 let mut stats = SetSketchUpdate::default();183 let log_base = Self::base().ln();184 for page in 0..Self::PAGE_COUNT {185 let first = page * (NODE_BYTES / 2);186 let used = (M - first).min(NODE_BYTES / 2);187 self.collection188 .read_at(189 storage,190 (page * NODE_BYTES) as u64,191 &mut workspace.bytes_mut()[..used * 2],192 )193 .expect("SetSketch admitted observation read");194 stats.pages_read += 1;195 let bytes = workspace.bytes_mut();196 let minimum = bytes[..used * 2]197 .chunks_exact(2)198 .map(|pair| u16::from_le_bytes(pair.try_into().unwrap()))199 .min()200 .unwrap();201 let cutoff = Self::uniform_cutoff(minimum, log_base);202 let mut changed = false;203 for register in 0..used {204 let offset = register * 2;205 let old = u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap());206 assert!(old <= Q, "corrupt SetSketch rank");207 if old == Q {208 continue;209 }210 let hash = hashes.hash((first + register) as u64);211 let uniform = ((hash >> 12) as f64 + 0.5) * (1.0 / 4_503_599_627_370_496.0);212 if uniform > cutoff {213 continue;214 }215 let rank = Self::rank(uniform, log_base);216 if rank > old {217 bytes[offset..offset + 2].copy_from_slice(&rank.to_le_bytes());218 stats.registers_increased += 1;219 changed = true;220 }221 }222 if changed {223 self.collection224 .write_at(225 storage,226 (page * NODE_BYTES) as u64,227 &workspace.bytes()[..used * 2],228 )229 .expect("SetSketch admitted observation write");230 stats.pages_written += 1;231 }232 }233 Ok(stats)234 }235236 /// Apply at most 4096 keys with reusable caller-owned preparation. Each237 /// active payload page is read/written at most once. For every register,238 /// keys retain their input order, so `registers_increased` equals the sum239 /// of the scalar increases, including intermediate increases. Page counts240 /// describe actual batch traffic. Hashes/ranks and max-union are unchanged.241 pub fn observe_many(242 &mut self,243 storage: &mut dyn Storage,244 keys: &[K],245 scratch: &mut [SetSketchBatchEntry],246 workspace: &mut Workspace<'_>,247 ) -> Result<SetSketchUpdate> {248 if keys.len() > SET_SKETCH_MAX_BATCH || scratch.len() < keys.len() {249 return Err(Error::Capacity);250 }251 self.collection.validate(storage)?;252 let scratch = &mut scratch[..keys.len()];253 for (entry, key) in scratch.iter_mut().zip(keys) {254 let key_hash = hash_key(key, self.seed, workspace);255 entry.hashes = Xxh64Pair::new(key_hash, self.seed ^ 0x5365_7453_6b65_7463);256 }257 let mut stats = SetSketchUpdate::default();258 if keys.is_empty() {259 return Ok(stats);260 }261 self.collection262 .ensure_nodes(storage, Self::PAGE_COUNT as u64)263 .expect("SetSketch admitted batch allocation");264 let log_base = Self::base().ln();265 for page in 0..Self::PAGE_COUNT {266 let first = page * (NODE_BYTES / 2);267 let used = (M - first).min(NODE_BYTES / 2);268 self.collection269 .read_at(270 storage,271 (page * NODE_BYTES) as u64,272 &mut workspace.bytes_mut()[..used * 2],273 )274 .expect("SetSketch admitted batch read");275 stats.pages_read += 1;276 let bytes = workspace.bytes_mut();277 let minimum = bytes[..used * 2]278 .chunks_exact(2)279 .map(|pair| u16::from_le_bytes(pair.try_into().unwrap()))280 .min()281 .unwrap();282 let page_cutoff = Self::uniform_cutoff(minimum, log_base);283 let mut changed = false;284 for register in 0..used {285 let at = register * 2;286 let mut old = u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap());287 assert!(old <= Q, "corrupt SetSketch rank");288 let index_hash = Xxh64Word::new((first + register) as u64);289 // Start with the already computed page bound. Tighten only290 // after an actual increase: duplicate batches add no exp calls291 // or rank-indexed cache, while fresh batches need not keep292 // evaluating logarithms against their initial zero minimum.293 let mut cutoff = page_cutoff;294 for entry in scratch.iter() {295 if old == Q {296 break;297 }298 let hash = entry.hashes.hash_prepared_second(&index_hash);299 let uniform = ((hash >> 12) as f64 + 0.5) * (1.0 / 4_503_599_627_370_496.0);300 if uniform > cutoff {301 continue;302 }303 let rank = Self::rank(uniform, log_base);304 if rank > old {305 old = rank;306 stats.registers_increased += 1;307 changed = true;308 if rank == Q {309 break;310 }311 if keys.len() > 1 {312 cutoff = Self::uniform_cutoff(rank, log_base);313 }314 }315 }316 bytes[at..at + 2].copy_from_slice(&old.to_le_bytes());317 }318 if changed {319 self.collection320 .write_at(321 storage,322 (page * NODE_BYTES) as u64,323 &workspace.bytes()[..used * 2],324 )325 .expect("SetSketch admitted batch write");326 stats.pages_written += 1;327 }328 }329 Ok(stats)330 }331332 /// Appendix B's finite-register corrected cardinality estimator. No333 /// histogram or heap scratch is needed: one scan collects its sufficient334 /// sum, zero count and saturated count. Series have an explicit work bound.335 pub fn estimate(336 &self,337 storage: &dyn Storage,338 workspace: &mut Workspace<'_>,339 ) -> Result<SetSketchEstimate> {340 self.collection.validate(storage)?;341 let mut sums = EstimateSums::default();342 if self.allocated_blocks() == 0 {343 sums.zero = M as u32;344 } else {345 let log_base = Self::base().ln();346 for page in 0..Self::PAGE_COUNT {347 let used = (M - page * (NODE_BYTES / 2)).min(NODE_BYTES / 2);348 self.collection.read_at(349 storage,350 (page * NODE_BYTES) as u64,351 &mut workspace.bytes_mut()[..used * 2],352 )?;353 for pair in workspace.bytes()[..used * 2].chunks_exact(2) {354 let rank = u16::from_le_bytes(pair.try_into().unwrap());355 sums.add(rank, Q, log_base)?;356 }357 }358 }359 Ok(Self::estimate_sums(sums))360 }361362 fn estimate_sums(sums: EstimateSums) -> SetSketchEstimate {363 let (estimate, status) = if sums.zero == M as u32 {364 (0.0, SetSketchStatus::Estimated)365 } else if sums.saturated == M as u32 {366 (f64::INFINITY, SetSketchStatus::RegisterRangeSaturated)367 } else {368 let b = Self::base();369 let m = M as f64;370 let denominator = m * sigma(b, f64::from(sums.zero) / m)371 + sums.sum372 + m * (-f64::from(Q - 1) * b.ln()).exp()373 * tau(b, 1.0 - f64::from(sums.saturated) / m);374 (375 m * (1.0 - 1.0 / b) / (20.0 * b.ln() * denominator),376 SetSketchStatus::Estimated,377 )378 };379 SetSketchEstimate {380 estimate,381 nominal_relative_error: Self::nominal_relative_error(),382 zero_registers: sums.zero,383 saturated_registers: sums.saturated,384 status,385 }386 }387388 /// Section 3.2's joint likelihood, using the two corrected cardinalities.389 /// Returns a bounded optimization result, with the paper's approximation390 /// for b<=2. Joint estimation rejects register saturation before interpreting391 /// the comparisons; it does not infer overlap by inclusion / exclusion.392 pub fn joint<QK: FixedKey, const N: usize, const C: u32, const R: u16>(393 &self,394 storage: &dyn Storage,395 other: &SetSketch<QK, N, C, R>,396 other_workspace: &mut Workspace<'_>,397 workspace: &mut Workspace<'_>,398 ) -> Result<SetSketchJointEstimate> {399 self.compatible(other)?;400 self.collection.validate(storage)?;401 other.collection.validate(storage)?;402 let mut left_sums = EstimateSums::default();403 let mut right_sums = EstimateSums::default();404 let log_base = Self::base().ln();405 let mut counts = [0u32; 3];406 let mut equal_prefix = true;407 for page in 0..Self::PAGE_COUNT {408 let used = (M - page * (NODE_BYTES / 2)).min(NODE_BYTES / 2);409 let left_bytes = if self.allocated_blocks() == 0 {410 None411 } else {412 self.collection.read_at(413 storage,414 (page * NODE_BYTES) as u64,415 &mut workspace.bytes_mut()[..used * 2],416 )?;417 Some(workspace.bytes())418 };419 let right_bytes = if other.allocated_blocks() == 0 {420 None421 } else {422 other.collection.read_at(423 storage,424 (page * NODE_BYTES) as u64,425 &mut other_workspace.bytes_mut()[..used * 2],426 )?;427 Some(other_workspace.bytes())428 };429 if equal_prefix430 && match (left_bytes, right_bytes) {431 (Some(left), Some(right)) => left[..used * 2] == right[..used * 2],432 (None, None) => true,433 _ => false,434 }435 {436 // Byte equality proves the same register terms. Accumulate437 // only the left prefix, retaining its original addition order.438 if let Some(bytes) = left_bytes {439 for pair in bytes[..used * 2].chunks_exact(2) {440 left_sums.add(u16::from_le_bytes(pair.try_into().unwrap()), Q, log_base)?;441 }442 } else {443 left_sums.zero += used as u32;444 }445 counts[2] += used as u32;446 continue;447 }448 if equal_prefix {449 // The skipped right prefix is bit-for-bit this exact partial450 // sum, not a reassociated sum of per-page cardinalities.451 right_sums = left_sums;452 equal_prefix = false;453 }454 for register in 0..used {455 let at = register * 2;456 let a = left_bytes.map_or(0, |bytes| {457 u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap())458 });459 let b = right_bytes.map_or(0, |bytes| {460 u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap())461 });462 left_sums.add(a, Q, log_base)?;463 right_sums.add(b, Q, log_base)?;464 counts[match a.cmp(&b) {465 core::cmp::Ordering::Greater => 0,466 core::cmp::Ordering::Less => 1,467 core::cmp::Ordering::Equal => 2,468 }] += 1;469 }470 }471 if equal_prefix {472 right_sums = left_sums;473 }474 if left_sums.saturated != 0 || right_sums.saturated != 0 {475 return Err(Error::InvalidInput("SetSketch joint saturated registers"));476 }477 let left = Self::estimate_sums(left_sums);478 let right = if equal_prefix {479 left480 } else {481 Self::estimate_sums(right_sums)482 };483 Ok(Self::joint_estimate(left.estimate, right.estimate, counts))484 }485486 /// Compare one cohort with at most 4096 others, preserving their order and487 /// duplicates. The reference payload and corrected cardinality are read and488 /// calculated once. Each peer retains the scalar joint estimator's register489 /// order, comparisons and likelihood; no stable payload is cached.490 ///491 /// A singleton uses `joint`. References fitting one node reuse the supplied492 /// second workspace; larger references allocate at most 64 KiB of transient493 /// bytes. The explicit scratch form lets callers reuse those bytes too.494 pub fn joint_many<QK: FixedKey, const N: usize, const C: u32, const R: u16>(495 &self,496 storage: &dyn Storage,497 others: &[&SetSketch<QK, N, C, R>],498 output: &mut [SetSketchJointEstimate],499 other_workspace: &mut Workspace<'_>,500 workspace: &mut Workspace<'_>,501 ) -> Result<()> {502 if others.len() > SET_SKETCH_MAX_JOINT_BATCH {503 return Err(Error::Capacity);504 }505 if output.len() != others.len() {506 return Err(Error::Bounds);507 }508 if others.is_empty() {509 return self.collection.validate(storage);510 }511 if others.len() == 1 {512 output[0] = self.joint(storage, others[0], other_workspace, workspace)?;513 return Ok(());514 }515 if Self::PAYLOAD_BYTES <= NODE_BYTES {516 return self.joint_many_with_scratch(517 storage,518 others,519 output,520 other_workspace.bytes_mut(),521 workspace,522 );523 }524 let mut reference = Vec::new();525 reference526 .try_reserve_exact(Self::PAYLOAD_BYTES)527 .map_err(|_| Error::Capacity)?;528 reference.resize(Self::PAYLOAD_BYTES, 0);529 self.joint_many_with_scratch(storage, others, output, &mut reference, workspace)530 }531532 /// Joint estimates with at least `PAYLOAD_BYTES` reusable reference bytes.533 /// Only that scratch prefix is overwritten; no authority is retained in it.534 /// Capacity, lengths, all contracts, seeds and providers are checked before535 /// output changes. A later read, corrupt rank or saturation error can leave536 /// a completed prefix in output. The operation never writes stable state.537 pub fn joint_many_with_scratch<QK: FixedKey, const N: usize, const C: u32, const R: u16>(538 &self,539 storage: &dyn Storage,540 others: &[&SetSketch<QK, N, C, R>],541 output: &mut [SetSketchJointEstimate],542 reference: &mut [u8],543 workspace: &mut Workspace<'_>,544 ) -> Result<()> {545 if others.len() > SET_SKETCH_MAX_JOINT_BATCH {546 return Err(Error::Capacity);547 }548 if output.len() != others.len() || reference.len() < Self::PAYLOAD_BYTES {549 return Err(Error::Bounds);550 }551 self.collection.validate(storage)?;552 for other in others {553 self.compatible(other)?;554 other.collection.validate(storage)?;555 }556 if others.is_empty() {557 return Ok(());558 }559 let reference = &mut reference[..Self::PAYLOAD_BYTES];560 if self.allocated_blocks() == 0 {561 reference.fill(0);562 } else {563 for (page, bytes) in reference.chunks_mut(NODE_BYTES).enumerate() {564 self.collection565 .read_at(storage, (page * NODE_BYTES) as u64, bytes)?;566 }567 }568 let log_base = Self::base().ln();569 let mut left_sums = EstimateSums::default();570 for pair in reference.chunks_exact(2) {571 left_sums.add(u16::from_le_bytes(pair.try_into().unwrap()), Q, log_base)?;572 }573 if left_sums.saturated != 0 {574 return Err(Error::InvalidInput("SetSketch joint saturated registers"));575 }576 let left = Self::estimate_sums(left_sums).estimate;577 for (other, result) in others.iter().zip(output) {578 let mut right_sums = EstimateSums::default();579 let mut counts = [0u32; 3];580 let mut equal_prefix = true;581 for (page, left_bytes) in reference.chunks(NODE_BYTES).enumerate() {582 let right_bytes = if other.allocated_blocks() == 0 {583 None584 } else {585 other.collection.read_at(586 storage,587 (page * NODE_BYTES) as u64,588 &mut workspace.bytes_mut()[..left_bytes.len()],589 )?;590 Some(workspace.bytes())591 };592 if equal_prefix593 && right_bytes.is_some_and(|bytes| bytes[..left_bytes.len()] == *left_bytes)594 {595 // Reference validation already proved every equal rank.596 // No stable reread, exponential table or peer copy needed.597 counts[2] += (left_bytes.len() / 2) as u32;598 continue;599 }600 if equal_prefix {601 // Only a later differing page needs the omitted terms.602 // Replay saved bytes once in the old register order; every603 // right-hand exponential is still evaluated at most once.604 for pair in reference[..page * NODE_BYTES].chunks_exact(2) {605 right_sums.add(606 u16::from_le_bytes(pair.try_into().unwrap()),607 Q,608 log_base,609 )?;610 }611 equal_prefix = false;612 }613 for (register, pair) in left_bytes.chunks_exact(2).enumerate() {614 let a = u16::from_le_bytes(pair.try_into().unwrap());615 let at = register * 2;616 let b = right_bytes.map_or(0, |bytes| {617 u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap())618 });619 right_sums.add(b, Q, log_base)?;620 counts[match a.cmp(&b) {621 core::cmp::Ordering::Greater => 0,622 core::cmp::Ordering::Less => 1,623 core::cmp::Ordering::Equal => 2,624 }] += 1;625 }626 }627 if equal_prefix {628 right_sums = left_sums;629 }630 if right_sums.saturated != 0 {631 return Err(Error::InvalidInput("SetSketch joint saturated registers"));632 }633 let right = if equal_prefix {634 left635 } else {636 Self::estimate_sums(right_sums).estimate637 };638 *result = Self::joint_estimate(left, right, counts);639 }640 Ok(())641 }642643 fn joint_estimate(a: f64, b: f64, counts: [u32; 3]) -> SetSketchJointEstimate {644 let jaccard = if a == 0.0 || b == 0.0 {645 if a == b { 1.0 } else { 0.0 }646 } else {647 joint_maximum(Self::base(), a / (a + b), counts)648 };649 let union = (a + b) / (1.0 + jaccard);650 SetSketchJointEstimate {651 left: a,652 right: b,653 union,654 intersection: union * jaccard,655 jaccard,656 left_greater_registers: counts[0],657 right_greater_registers: counts[1],658 equal_registers: counts[2],659 }660 }661662 /// Exact register union. Contract, seed and both authorities are checked663 /// before allocation or mutation. Two borrowed buffers bound transient work.664 pub fn merge<QK: FixedKey, const N: usize, const C: u32, const R: u16>(665 &mut self,666 storage: &mut dyn Storage,667 other: &SetSketch<QK, N, C, R>,668 other_workspace: &mut Workspace<'_>,669 workspace: &mut Workspace<'_>,670 ) -> Result<SetSketchUpdate> {671 self.compatible(other)?;672 self.collection.validate(storage)?;673 other.collection.validate(storage)?;674 let mut stats = SetSketchUpdate::default();675 if other.allocated_blocks() == 0 {676 return Ok(stats);677 }678 self.collection679 .ensure_nodes(storage, Self::PAGE_COUNT as u64)?;680 for page in 0..Self::PAGE_COUNT {681 let used = (M - page * (NODE_BYTES / 2)).min(NODE_BYTES / 2);682 self.collection683 .read_at(684 storage,685 (page * NODE_BYTES) as u64,686 &mut workspace.bytes_mut()[..used * 2],687 )688 .expect("SetSketch admitted merge destination read");689 other690 .collection691 .read_at(692 storage,693 (page * NODE_BYTES) as u64,694 &mut other_workspace.bytes_mut()[..used * 2],695 )696 .expect("SetSketch admitted merge source read");697 let source = other_workspace.bytes();698 stats.pages_read += 2;699 let destination = workspace.bytes_mut();700 let mut changed = false;701 for (old, new) in destination[..used * 2]702 .chunks_exact_mut(2)703 .zip(source[..used * 2].chunks_exact(2))704 {705 let a = u16::from_le_bytes((&*old).try_into().unwrap());706 let b = u16::from_le_bytes(new.try_into().unwrap());707 assert!(a <= Q && b <= Q, "corrupt SetSketch rank");708 if b > a {709 old.copy_from_slice(&b.to_le_bytes());710 stats.registers_increased += 1;711 changed = true;712 }713 }714 if changed {715 self.collection716 .write_at(717 storage,718 (page * NODE_BYTES) as u64,719 &workspace.bytes()[..used * 2],720 )721 .expect("SetSketch admitted merge write");722 stats.pages_written += 1;723 }724 }725 Ok(stats)726 }727728 pub fn clear(&mut self, storage: &mut dyn Storage) -> Result<()> {729 self.collection.truncate_nodes(storage, 0)730 }731732 fn compatible<QK: FixedKey, const N: usize, const C: u32, const R: u16>(733 &self,734 other: &SetSketch<QK, N, C, R>,735 ) -> Result<()> {736 if Self::CONTRACT != SetSketch::<QK, N, C, R>::CONTRACT || self.seed != other.seed {737 Err(Error::InvalidInput(738 "incompatible SetSketch contract or seed",739 ))740 } else {741 Ok(())742 }743 }744745 fn uniform_cutoff(minimum: u16, log_base: f64) -> f64 {746 // -ln(1-u) >= u. If u > 20*b^(-(minimum-1)), the exact747 // candidate is below minimum. One rank of slack protects the748 // floating-point comparison; possible increases keep the original749 // logarithms and rounding. No sampled values or keys are cached.750 20.0 * (-f64::from(minimum.saturating_sub(1)) * log_base).exp()751 }752753 fn rank(uniform: f64, log_base: f64) -> u16 {754 // The 52-bit midpoints avoid both endpoints, including the largest755 // value 1-2^-53. Use U through -ln(1-U).756 let exponential = -(-uniform).ln_1p() / 20.0;757 (1.0 - exponential.ln() / log_base)758 .floor()759 .clamp(0.0, f64::from(Q)) as u16760 }761}762763#[derive(Clone, Copy, Default)]764struct EstimateSums {765 sum: f64,766 zero: u32,767 saturated: u32,768}769impl EstimateSums {770 fn add(&mut self, rank: u16, maximum: u16, log_base: f64) -> Result<()> {771 if rank > maximum {772 return Err(Error::Corrupt("SetSketch rank"));773 }774 if rank == 0 {775 self.zero += 1;776 } else if rank == maximum {777 self.saturated += 1;778 } else {779 self.sum += (-f64::from(rank) * log_base).exp();780 }781 Ok(())782 }783}784785// Appendix B, positive series forms. A minimum base of 1.001 and bounded M786// imply convergence well before 131,072 terms. There is no data-dependent787// unbounded retry or hidden lookup table.788fn sigma(b: f64, x: f64) -> f64 {789 if x == 0.0 {790 return 0.0;791 }792 if x == 1.0 {793 return f64::INFINITY;794 }795 let log_x = x.ln();796 let mut factor = 1.0;797 let mut sum = 0.0;798 for _ in 0..131_072 {799 let term = factor * (log_x * factor).exp() * (-(log_x * factor * (b - 1.0)).exp_m1());800 let next = sum + term;801 if next == sum {802 return sum;803 }804 sum = next;805 factor *= b;806 }807 panic!("SetSketch sigma convergence contract")808}809810fn tau(b: f64, x: f64) -> f64 {811 if x == 0.0 || x == 1.0 {812 return 0.0;813 }814 let log_x = x.ln();815 let mut factor = 1.0 / b;816 let mut sum = 0.0;817 for _ in 0..131_072 {818 let term = factor * (log_x * factor).exp() * (-(log_x * factor * (b - 1.0)).exp_m1());819 let next = sum + term;820 if next == sum {821 return sum;822 }823 sum = next;824 factor /= b;825 }826 panic!("SetSketch tau convergence contract")827}828829fn joint_maximum(b: f64, u: f64, counts: [u32; 3]) -> f64 {830 let v = 1.0 - u;831 let upper = (u / v).min(v / u);832 // Identical finite register estimates produce u=1/2. With only equality833 // observations, J=1 gives probability one and log-likelihood zero, the834 // exact upper bound. The old endpoint/tie loop therefore also selects 1.835 // Keep non-finite/extreme cardinality ratios on the ordinary arithmetic.836 if u == 0.5 && counts[0] == 0 && counts[1] == 0 && counts[2] != 0 {837 return 1.0;838 }839 let log_base = b.ln();840 let likelihood = |j: f64| {841 let p = |x: f64| -(-x.max(0.0) * (1.0 - 1.0 / b)).ln_1p() / log_base;842 let greater = p(u - v * j);843 let less = p(v - u * j);844 let probabilities = [greater, less, (1.0 - greater - less).max(0.0)];845 let mut value = 0.0;846 for (count, probability) in counts.into_iter().zip(probabilities) {847 if count != 0 {848 value += f64::from(count) * probability.ln();849 }850 }851 value852 };853 // Fixed-iteration ternary search is sufficient for the concave likelihood.854 // Endpoints are explicitly compared to retain exact empty/identical limits.855 let (mut low, mut high) = (0.0, upper);856 for _ in 0..100 {857 let a = low + (high - low) / 3.0;858 let c = high - (high - low) / 3.0;859 if likelihood(a) < likelihood(c) {860 if a.to_bits() == low.to_bits() && a.is_finite() {861 // The selected update leaves both bounds unchanged. All862 // remaining old iterations repeat the same comparison.863 break;864 }865 low = a;866 } else {867 if c.to_bits() == high.to_bits() && c.is_finite() {868 // Preserve the old '<' tie branch before checking its fixed869 // point; stopping on equal scores alone would be incorrect.870 break;871 }872 high = c;873 }874 }875 let mut best = (low + high) / 2.0;876 let mut best_value = likelihood(best);877 for candidate in [0.0, upper] {878 let value = likelihood(candidate);879 if value >= best_value {880 best = candidate;881 best_value = value;882 }883 }884 best885}886887#[cfg(test)]888#[path = "set_sketch_tests.rs"]889mod tests;