aeris.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/aeris.rs
1//! Aeris adaptive range filter with bounded growing fingerprints.2//!3//! Independent implementation of Chesetti et al., *Aeris Filter: A Strongly4//! and Monotonically Adaptive Range Filter*, §§3.1–3.2,5//! <https://doi.org/10.1145/3786621>. Quotient runs contain prefix-free keepsakes6//! with lexicographically ordered extension bits and distinct sorted mementos.7//! The three occupied/keepsake-end/extension bits retain the paper's meaning;8//! extension+end marks the last keepsake in a quotient run. Fingerprints grow9//! first by one memento width and thereafter by a whole slot width.10//!11//! Capacity is fixed. The pinned long hash is 128 bits, so adaptation can reject12//! unchanged at its length/slot limit. This bounded implementation makes no13//! infinite-expansion or unbounded-adversary guarantee. Rank/select scans and14//! proposed-image updates are scalar; a caller supplies bounded authoritative15//! backing keys instead of this collection owning the paper's B-epsilon tree.16//!17//! Refinement is an explicit mutable operation after a backing-key-confirmed18//! false positive. Read-only queries never adapt. Invoke refinement in a19//! committed update: IC query writes are discarded. Insertions and deletions20//! must be coupled synchronously to the exact set; positives never authorize21//! deletion. Mutation faults trap and use IC rollback, without an undo log.2223const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("aeris.rs");2425use crate::hash::{XXH64_POLICY, xxh64};26use crate::memento::{MEMENTO_POLICY, RunMetadata, SlotReader, bitmask, check_range};27use crate::{Collection, Error, NODE_BYTES, Result, Storage, Workspace};28use cdk_rsx_engine_nyxus::NyxusData;29use std::collections::{BTreeMap, BTreeSet};3031const HASH_EXTENSION_DOMAIN: u64 = 0x6165_7269_735f_0001;32pub const AERIS_POLICY: [u8; 32] = crate::contract(33 "MinimaAerisGrowingKeepsakes/v1",34 &[],35 &[36 SOURCE_POLICY,37 crate::MINIMA_POLICY,38 XXH64_POLICY,39 MEMENTO_POLICY,40 ],41);42pub const AERIS_MAX_KEYS: u32 = 1 << 20;43pub const AERIS_MAX_QUOTIENT_BITS: u8 = 16;44pub const AERIS_MAX_SHIFT: u32 = 4096;45/// Bounded input/results, separate from the configured complete backing bound.46pub const AERIS_MAX_BATCH_KEYS: usize = 1024;4748#[repr(C)]49#[derive(Clone, Copy, Debug, Eq, PartialEq)]50pub struct AerisConfig {51 pub quotient_bits: u8,52 pub remainder_bits: u8,53 /// Inclusive integer range length, in 1..=2^32.54 pub max_range_len: u64,55 pub max_keys: u32,56 pub max_shift_slots: u32,57 /// Maximum total fingerprint length, including the implicit quotient.58 pub max_fingerprint_bits: u8,59 pub seed: u64,60}61// SAFETY: entirely inline scalar interpretation configuration.62unsafe impl NyxusData for AerisConfig {63 const __NYXUS_POLICY: [u8; 32] = AERIS_POLICY;64}65impl AerisConfig {66 pub const fn contract(self) -> [u8; 32] {67 crate::contract(68 "MinimaAerisConfiguration/v1",69 &[],70 &[71 AERIS_POLICY,72 crate::width_contract("quotient", self.quotient_bits as usize, &[]),73 crate::width_contract("remainder", self.remainder_bits as usize, &[]),74 crate::width_contract("range", self.max_range_len as usize, &[]),75 crate::width_contract("keys", self.max_keys as usize, &[]),76 crate::width_contract("shift", self.max_shift_slots as usize, &[]),77 crate::width_contract("fingerprint-bound", self.max_fingerprint_bits as usize, &[]),78 crate::width_contract("seed", self.seed as usize, &[]),79 ],80 )81 }82 fn validate(self) -> Result<u8> {83 if !(1..=AERIS_MAX_QUOTIENT_BITS).contains(&self.quotient_bits)84 || !(1..=32).contains(&self.remainder_bits)85 || !(1..=1u64 << 32).contains(&self.max_range_len)86 || !(1..=AERIS_MAX_KEYS).contains(&self.max_keys)87 || !(1..=AERIS_MAX_SHIFT).contains(&self.max_shift_slots)88 || self.max_fingerprint_bits < self.quotient_bits + self.remainder_bits89 || self.max_fingerprint_bits > 12890 {91 return Err(Error::InvalidInput("Aeris configuration"));92 }93 // A one-bit memento also supports point-only instances and guarantees94 // a nonzero first extension quantum; no zero-width shift is performed.95 Ok(((u64::BITS - (self.max_range_len - 1).leading_zeros()) as u8).max(1))96 }97}9899#[derive(Clone, Copy, Debug, Eq, PartialEq)]100#[must_use]101pub enum AerisInsert {102 Inserted,103 Full,104 FingerprintLimit,105}106#[derive(Clone, Copy, Debug, Eq, PartialEq)]107#[must_use]108pub enum AerisRefinement {109 /// The query is empty-negative or has a real backing key in its range.110 NotFalsePositive,111 Refined,112 Full,113 FingerprintLimit,114}115116/// Nonowning high-bit hash prefix. Value is right aligned to its bit length.117#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]118pub struct AerisFingerprint {119 pub value: u128,120 pub bits: u8,121}122#[derive(Clone, Debug, Eq, PartialEq)]123struct Keepsake {124 fingerprint: AerisFingerprint,125 mementos: Vec<u64>,126}127128#[repr(C)]129pub struct AerisFilter {130 nodes: Collection,131 config: AerisConfig,132 len: u64,133 refinements: u64,134 used_slots: u32,135 memento_bits: u8,136}137// SAFETY: retained Collection authority and inline scalars only. Decoded138// fingerprints, backing-key lists and proposed images are bounded transients.139unsafe impl NyxusData for AerisFilter {140 const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;141}142143impl AerisFilter {144 pub const CONTRACT: [u8; 32] = AERIS_POLICY;145 pub fn new(storage: &mut dyn Storage, config: AerisConfig) -> Result<Self> {146 let memento_bits = config.validate()?;147 Ok(Self {148 nodes: Collection::new(storage)?,149 config,150 len: 0,151 refinements: 0,152 used_slots: 0,153 memento_bits,154 })155 }156 pub fn len(&self) -> u64 {157 self.len158 }159 pub fn is_empty(&self) -> bool {160 self.len == 0161 }162 pub fn config(&self) -> AerisConfig {163 self.config164 }165 pub fn block_count(&self) -> usize {166 self.nodes.block_count()167 }168 pub fn encoded_slots(&self) -> u32 {169 self.used_slots170 }171 pub fn refinement_count(&self) -> u64 {172 self.refinements173 }174 pub fn memento_bits(&self) -> u8 {175 self.memento_bits176 }177 pub fn payload_bytes(&self) -> u64 {178 self.geometry().bytes()179 }180181 pub fn may_contain(182 &self,183 storage: &dyn Storage,184 key: u64,185 workspace: &mut Workspace,186 ) -> Result<bool> {187 self.may_contain_range(storage, key, key, workspace)188 }189 pub fn may_contain_range(190 &self,191 storage: &dyn Storage,192 lower: u64,193 upper: u64,194 workspace: &mut Workspace,195 ) -> Result<bool> {196 check_range(lower, upper, self.config.max_range_len)?;197 self.nodes.validate(storage)?;198 if self.is_empty() {199 return Ok(false);200 }201 let g = self.geometry();202 let first = lower >> self.memento_bits;203 let last = upper >> self.memento_bits;204 let mask = bitmask(self.memento_bits);205 for partition in first..=last {206 let hash = self.partition_hash(partition);207 let canonical = (hash >> (128 - self.config.quotient_bits)) as u32;208 let run = {209 let mut metadata = RunMetadata::new(&self.nodes, storage, g.slots, 3, workspace);210 let Some((start, end)) = metadata.locate(canonical, self.config.max_shift_slots)?211 else {212 continue;213 };214 QueryRun::read(&mut metadata, start, end)?215 };216 let mut slots = SlotReader::new(217 &self.nodes,218 storage,219 workspace,220 g.data_at,221 run.start,222 run.end,223 g.width,224 );225 let low = if partition == first { lower & mask } else { 0 };226 let high = if partition == last {227 upper & mask228 } else {229 mask230 };231 if self.query_run(&mut slots, &run, canonical, hash, low, high)? {232 return Ok(true);233 }234 }235 Ok(false)236 }237238 /// Call exactly once per exact absent-to-present transition. Distinct239 /// colliding keys may share a memento; their multiplicity remains in the240 /// authoritative backing set and is consulted for safe removal/refinement.241 pub fn try_insert(242 &mut self,243 storage: &mut dyn Storage,244 key: u64,245 workspace: &mut Workspace,246 ) -> Result<AerisInsert> {247 self.nodes.validate(storage)?;248 if self.len >= u64::from(self.config.max_keys) {249 return Ok(AerisInsert::Full);250 }251 let mut boxes = self.read_boxes(storage, workspace)?;252 let hash = self.partition_hash(key >> self.memento_bits);253 let memento = key & bitmask(self.memento_bits);254 if let Some(at) = matching_box(&boxes, hash) {255 let b = &mut boxes[at];256 match b.mementos.binary_search(&memento) {257 Ok(_) => {258 // A distinct exact key can share this complete stored259 // identity. Only the retained admitted-key count changes.260 self.len += 1;261 return Ok(AerisInsert::Inserted);262 }263 Err(at) => b.mementos.insert(at, memento),264 }265 } else {266 let mut bits = self.initial_bits();267 while boxes268 .iter()269 .any(|b| overlaps(prefix(hash, bits), b.fingerprint))270 {271 let Some(next) = self.next_bits(bits) else {272 return Ok(AerisInsert::FingerprintLimit);273 };274 bits = next;275 }276 boxes.push(Keepsake {277 fingerprint: prefix(hash, bits),278 mementos: vec![memento],279 });280 }281 self.sort_boxes(&mut boxes);282 let Some(image) = self.encode(&boxes)? else {283 return Ok(AerisInsert::Full);284 };285 self.publish(storage, &image, workspace);286 self.len += 1;287 self.used_slots = image.used;288 Ok(AerisInsert::Inserted)289 }290291 /// `backing_keys` is the complete authoritative exact set BEFORE removal,292 /// including `key`, bounded by max_keys. It must describe this filter's293 /// admitted keys, not just filter positives or a sample. Remove from the294 /// exact set only after success, in the same synchronous committed update.295 pub fn remove_known_present(296 &mut self,297 storage: &mut dyn Storage,298 key: u64,299 backing_keys: &[u64],300 workspace: &mut Workspace,301 ) -> Result<bool> {302 let mut boxes = self.read_boxes(storage, workspace)?;303 self.validate_backing(&boxes, backing_keys)?;304 if !backing_keys.contains(&key) {305 return Ok(false);306 }307 let hash = self.partition_hash(key >> self.memento_bits);308 let at = matching_box(&boxes, hash).ok_or_else(corrupt)?;309 let memento = key & bitmask(self.memento_bits);310 let shared = backing_keys.iter().any(|other| {311 *other != key312 && *other & bitmask(self.memento_bits) == memento313 && matches(314 boxes[at].fingerprint,315 self.partition_hash(*other >> self.memento_bits),316 )317 });318 if !shared {319 let index = boxes[at]320 .mementos321 .binary_search(&memento)322 .map_err(|_| corrupt())?;323 boxes[at].mementos.remove(index);324 if boxes[at].mementos.is_empty() {325 boxes.remove(at);326 }327 let image = self328 .encode(&boxes)?329 .expect("Aeris deletion cannot exhaust capacity");330 self.publish(storage, &image, workspace);331 self.used_slots = image.used;332 }333 self.len -= 1;334 Ok(true)335 }336337 /// Confirm a false positive against the complete authoritative backing set,338 /// then split all affected keepsakes using the paper's extension quanta.339 /// A capacity/hash bound returns unchanged, so the original positive remains340 /// valid. A successful refinement makes this query negative for this dataset.341 pub fn refine_false_positive(342 &mut self,343 storage: &mut dyn Storage,344 lower: u64,345 upper: u64,346 backing_keys: &[u64],347 workspace: &mut Workspace,348 ) -> Result<AerisRefinement> {349 check_range(lower, upper, self.config.max_range_len)?;350 let boxes = self.read_boxes(storage, workspace)?;351 self.validate_backing(&boxes, backing_keys)?;352 if backing_keys353 .iter()354 .any(|key| lower <= *key && *key <= upper)355 || !self.query_boxes(&boxes, lower, upper)356 {357 return Ok(AerisRefinement::NotFalsePositive);358 }359 let first = lower >> self.memento_bits;360 let last = upper >> self.memento_bits;361 let mask = bitmask(self.memento_bits);362 let mut proposed = Vec::new();363 for b in boxes {364 let affected = (first..=last).any(|partition| {365 let low = if partition == first { lower & mask } else { 0 };366 let high = if partition == last {367 upper & mask368 } else {369 mask370 };371 matches(b.fingerprint, self.partition_hash(partition))372 && intersects(&b.mementos, low, high)373 });374 if !affected {375 proposed.push(b);376 continue;377 }378 let keys: Vec<_> = backing_keys379 .iter()380 .copied()381 .filter(|key| {382 matches(383 b.fingerprint,384 self.partition_hash(*key >> self.memento_bits),385 )386 })387 .collect();388 let mut bits = b.fingerprint.bits;389 loop {390 let collision = (first..=last).any(|partition| {391 let low = if partition == first { lower & mask } else { 0 };392 let high = if partition == last {393 upper & mask394 } else {395 mask396 };397 let query = prefix(self.partition_hash(partition), bits);398 keys.iter().any(|key| {399 let memento = *key & mask;400 low <= memento401 && memento <= high402 && prefix(self.partition_hash(*key >> self.memento_bits), bits) == query403 })404 });405 if !collision {406 break;407 }408 let Some(next) = self.next_bits(bits) else {409 return Ok(AerisRefinement::FingerprintLimit);410 };411 bits = next;412 }413 // Every partition in the old keepsake is redistributed, including414 // the query's own partition when its real keys lie outside the range.415 let mut split: BTreeMap<u128, Vec<u64>> = BTreeMap::new();416 for key in keys {417 split418 .entry(prefix(self.partition_hash(key >> self.memento_bits), bits).value)419 .or_default()420 .push(key & mask);421 }422 for (value, mut mementos) in split {423 mementos.sort_unstable();424 mementos.dedup();425 proposed.push(Keepsake {426 fingerprint: AerisFingerprint { value, bits },427 mementos,428 });429 }430 }431 self.sort_boxes(&mut proposed);432 let Some(image) = self.encode(&proposed)? else {433 return Ok(AerisRefinement::Full);434 };435 assert!(436 !self.query_boxes(&proposed, lower, upper),437 "Aeris refinement must resolve query"438 );439 self.publish(storage, &image, workspace);440 self.used_slots = image.used;441 self.refinements = self442 .refinements443 .checked_add(1)444 .expect("Aeris refinement count overflow");445 Ok(AerisRefinement::Refined)446 }447 /// Input-order exact-authorized insertions, with one source decode and at448 /// most one publication. Full/FingerprintLimit leave that attempted input449 /// unchanged. Every intermediate slot/load/displacement limit matches scalar450 /// insertion; a returned error leaves the published state unchanged.451 pub fn try_insert_many(452 &mut self,453 storage: &mut dyn Storage,454 keys: &[u64],455 workspace: &mut Workspace,456 ) -> Result<Vec<AerisInsert>> {457 if keys.len() > AERIS_MAX_BATCH_KEYS {458 return Err(Error::Capacity);459 }460 self.nodes.validate(storage)?;461 let mut results = Vec::new();462 results463 .try_reserve_exact(keys.len())464 .map_err(|_| Error::Capacity)?;465 if keys.is_empty() || self.len >= u64::from(self.config.max_keys) {466 results.resize(keys.len(), AerisInsert::Full);467 return Ok(results);468 }469 if let [key] = keys {470 results.push(self.try_insert(storage, *key, workspace)?);471 return Ok(results);472 }473 let mut boxes = self.read_boxes(storage, workspace)?;474 let mut len = self.len;475 let mut dirty = false;476 for &key in keys {477 if len >= u64::from(self.config.max_keys) {478 results.push(AerisInsert::Full);479 continue;480 }481 let hash = self.partition_hash(key >> self.memento_bits);482 let memento = key & bitmask(self.memento_bits);483 let (fingerprint, inserted) = if let Some(at) = matching_box(&boxes, hash) {484 match boxes[at].mementos.binary_search(&memento) {485 Ok(_) => {486 len += 1;487 results.push(AerisInsert::Inserted);488 continue;489 }490 Err(m) => boxes[at].mementos.insert(m, memento),491 }492 (boxes[at].fingerprint, false)493 } else {494 let mut bits = self.initial_bits();495 while boxes496 .iter()497 .any(|b| overlaps(prefix(hash, bits), b.fingerprint))498 {499 let Some(next) = self.next_bits(bits) else {500 break;501 };502 bits = next;503 }504 if boxes505 .iter()506 .any(|b| overlaps(prefix(hash, bits), b.fingerprint))507 {508 results.push(AerisInsert::FingerprintLimit);509 continue;510 }511 let fingerprint = prefix(hash, bits);512 boxes.push(Keepsake {513 fingerprint,514 mementos: vec![memento],515 });516 (fingerprint, true)517 };518 self.sort_boxes(&mut boxes);519 if self.bulk_fits_boxes(&boxes) {520 len += 1;521 dirty = true;522 results.push(AerisInsert::Inserted);523 } else {524 let at = boxes525 .iter()526 .position(|b| b.fingerprint == fingerprint)527 .unwrap();528 if inserted {529 boxes.remove(at);530 } else {531 let m = boxes[at].mementos.binary_search(&memento).unwrap();532 boxes[at].mementos.remove(m);533 }534 results.push(AerisInsert::Full);535 }536 }537 if dirty {538 let image = self.encode(&boxes)?.expect("preflighted Aeris batch image");539 self.publish(storage, &image, workspace);540 self.used_slots = image.used;541 }542 self.len = len;543 Ok(results)544 }545546 /// Remove in input order using the complete authoritative exact backing547 /// BEFORE this batch. Validate that backing once; retain a shared stored548 /// identity until its last remaining exact key is removed. Results match549 /// scalar calls with the backing updated after each successful removal.550 /// The caller commits its exact-set removals only after this succeeds.551 pub fn remove_known_present_many(552 &mut self,553 storage: &mut dyn Storage,554 keys: &[u64],555 backing_keys: &[u64],556 workspace: &mut Workspace,557 ) -> Result<Vec<bool>> {558 if keys.len() > AERIS_MAX_BATCH_KEYS {559 return Err(Error::Capacity);560 }561 let mut results = Vec::new();562 results563 .try_reserve_exact(keys.len())564 .map_err(|_| Error::Capacity)?;565 if let [key] = keys {566 results.push(self.remove_known_present(storage, *key, backing_keys, workspace)?);567 return Ok(results);568 }569 let mut boxes = self.read_boxes(storage, workspace)?;570 self.validate_backing(&boxes, backing_keys)?;571 if keys.is_empty() {572 return Ok(results);573 }574 let mut remaining: BTreeSet<_> = backing_keys.iter().copied().collect();575 let mut counts = BTreeMap::<(AerisFingerprint, u64), usize>::new();576 for &key in backing_keys {577 let hash = self.partition_hash(key >> self.memento_bits);578 let b = &boxes[matching_box(&boxes, hash).ok_or_else(corrupt)?];579 *counts580 .entry((b.fingerprint, key & bitmask(self.memento_bits)))581 .or_default() += 1;582 }583 let mut removed = 0;584 let mut dirty = false;585 for &key in keys {586 if !remaining.remove(&key) {587 results.push(false);588 continue;589 }590 let hash = self.partition_hash(key >> self.memento_bits);591 let at = matching_box(&boxes, hash).ok_or_else(corrupt)?;592 let memento = key & bitmask(self.memento_bits);593 let count = counts594 .get_mut(&(boxes[at].fingerprint, memento))595 .ok_or_else(corrupt)?;596 *count -= 1;597 if *count == 0 {598 let m = boxes[at]599 .mementos600 .binary_search(&memento)601 .map_err(|_| corrupt())?;602 boxes[at].mementos.remove(m);603 if boxes[at].mementos.is_empty() {604 boxes.remove(at);605 }606 dirty = true;607 }608 removed += 1;609 results.push(true);610 }611 if dirty {612 let image = self.encode(&boxes)?.expect("Aeris batch deletion capacity");613 self.publish(storage, &image, workspace);614 self.used_slots = image.used;615 }616 self.len -= removed;617 Ok(results)618 }619620 fn bulk_fits_boxes(&self, boxes: &[Keepsake]) -> bool {621 let g = self.geometry();622 let mut position = 0usize;623 let mut used = 0usize;624 for b in boxes {625 let canonical = self.canonical(b.fingerprint) as usize;626 position = position.max(canonical);627 let bits = self.config.remainder_bits as usize628 + (b.fingerprint.bits - self.initial_bits()) as usize629 + b.mementos.len() * self.memento_bits as usize;630 let count = bits.div_ceil(g.width as usize);631 let end = position + count;632 if b.mementos.is_empty()633 || end > g.slots as usize634 || end - 1 - canonical > self.config.max_shift_slots as usize635 {636 return false;637 }638 used += count;639 position = end;640 }641 used as u64 * 100 <= u64::from(g.canonical) * 95642 }643644 pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {645 self.nodes.retire(storage)646 }647648 fn initial_bits(&self) -> u8 {649 self.config.quotient_bits + self.config.remainder_bits650 }651 fn next_bits(&self, bits: u8) -> Option<u8> {652 let increment = if bits == self.initial_bits() {653 self.memento_bits654 } else {655 self.config.remainder_bits + self.memento_bits656 };657 bits.checked_add(increment)658 .filter(|next| *next <= self.config.max_fingerprint_bits)659 }660 fn partition_hash(&self, partition: u64) -> u128 {661 let bytes = partition.to_le_bytes();662 (u128::from(xxh64(&bytes, self.config.seed)) << 64)663 | u128::from(xxh64(&bytes, self.config.seed ^ HASH_EXTENSION_DOMAIN))664 }665 fn canonical(&self, fingerprint: AerisFingerprint) -> u32 {666 (fingerprint.value >> (fingerprint.bits - self.config.quotient_bits)) as u32667 }668 fn sort_boxes(&self, boxes: &mut [Keepsake]) {669 boxes.sort_by_key(|b| b.fingerprint.value << (128 - b.fingerprint.bits));670 }671 fn query_boxes(&self, boxes: &[Keepsake], lower: u64, upper: u64) -> bool {672 let first = lower >> self.memento_bits;673 let last = upper >> self.memento_bits;674 let mask = bitmask(self.memento_bits);675 (first..=last).any(|partition| {676 let hash = self.partition_hash(partition);677 let low = if partition == first { lower & mask } else { 0 };678 let high = if partition == last {679 upper & mask680 } else {681 mask682 };683 matching_box(boxes, hash).is_some_and(|at| intersects(&boxes[at].mementos, low, high))684 })685 }686 fn validate_backing(&self, boxes: &[Keepsake], keys: &[u64]) -> Result<()> {687 if keys.len() > self.config.max_keys as usize || keys.len() as u64 != self.len {688 return Err(Error::InvalidInput("Aeris complete backing-key bound"));689 }690 let mut sorted = keys.to_vec();691 sorted.sort_unstable();692 if sorted.windows(2).any(|pair| pair[0] == pair[1]) {693 return Err(Error::InvalidInput("Aeris exact-set duplicate"));694 }695 let mut expected = vec![Vec::new(); boxes.len()];696 for key in keys {697 let hash = self.partition_hash(*key >> self.memento_bits);698 let at = matching_box(boxes, hash).ok_or(Error::InvalidInput(699 "Aeris backing-key fingerprint mismatch",700 ))?;701 expected[at].push(*key & bitmask(self.memento_bits));702 }703 for (b, mut mementos) in boxes.iter().zip(expected) {704 mementos.sort_unstable();705 mementos.dedup();706 if mementos != b.mementos {707 return Err(Error::InvalidInput("Aeris backing-key memento mismatch"));708 }709 }710 Ok(())711 }712 fn geometry(&self) -> Geometry {713 Geometry::new(714 self.config.quotient_bits,715 self.config.max_shift_slots,716 self.config.remainder_bits + self.memento_bits,717 )718 }719720 fn read_boxes(721 &self,722 storage: &dyn Storage,723 workspace: &mut Workspace,724 ) -> Result<Vec<Keepsake>> {725 self.nodes.validate(storage)?;726 if self.is_empty() {727 return Ok(Vec::new());728 }729 let g = self.geometry();730 // Keep metadata separate while the one borrowed workspace streams731 // payload nodes. Neither the padded image nor a second decoded slot732 // array needs to coexist with the complete keepsake result.733 let mut metadata = vec![0; g.metadata_bytes()];734 self.nodes.read_at(storage, 0, &mut metadata)?;735 let mut slots = SlotReader::new(736 &self.nodes,737 storage,738 workspace,739 g.data_at,740 0,741 g.slots - 1,742 g.width,743 );744 let mut out = Vec::new();745 let mut position = 0u32;746 let mut used = 0u32;747 let mut mementos = 0u64;748 for canonical in 0..g.canonical {749 if !flag(&metadata, canonical, 0) {750 continue;751 }752 position = position.max(canonical);753 loop {754 let end = (position..g.slots)755 .find(|slot| flag(&metadata, *slot, 1))756 .ok_or_else(corrupt)?;757 let b = self.decode_box(canonical, &mut slots, &metadata, position, end)?;758 mementos += b.mementos.len() as u64;759 if mementos > self.len || out.len() >= self.config.max_keys as usize {760 return Err(corrupt());761 }762 out.push(b);763 used += end - position + 1;764 position = end + 1;765 if flag(&metadata, end, 2) {766 break;767 }768 if position == g.slots {769 return Err(corrupt());770 }771 }772 }773 if used != self.used_slots774 || out.windows(2).any(|pair| {775 overlaps(pair[0].fingerprint, pair[1].fingerprint)776 || pair[0].fingerprint.value << (128 - pair[0].fingerprint.bits)777 >= pair[1].fingerprint.value << (128 - pair[1].fingerprint.bits)778 })779 {780 return Err(corrupt());781 }782 Ok(out)783 }784785 /// Decode only the selected quotient run. Extension/end bits are a bounded786 /// copy of that run's metadata; payload bytes stream through the caller's787 /// one workspace, without building a proposed image or decoded containers.788 fn query_run(789 &self,790 slots: &mut SlotReader<'_, '_>,791 run: &QueryRun,792 canonical: u32,793 hash: u128,794 low: u64,795 high: u64,796 ) -> Result<bool> {797 let f = self.config.remainder_bits;798 let m = self.memento_bits;799 let w = f + m;800 let mut position = run.start;801 let mut previous_fingerprint = None;802 let mut total = 0u64;803 let mut found = false;804 while position <= run.end {805 let end = run.box_end(position)?;806 let relative = position - run.start;807 let count = end - position + 1;808 let first = slots.slot(relative)?;809 let mut fingerprint = AerisFingerprint {810 value: (u128::from(canonical) << f) | u128::from(first & bitmask(f)),811 bits: self.initial_bits(),812 };813 let mut at = f as usize;814 if run.flag(position, 1) && !run.flag(position, 0) {815 fingerprint.value = (fingerprint.value << m) | u128::from(first >> f);816 fingerprint.bits = fingerprint.bits.checked_add(m).ok_or_else(corrupt)?;817 let mut slot = 1;818 while slot < count - 1819 && run.flag(position + slot, 1)820 && !run.flag(position + slot, 0)821 {822 fingerprint.bits = fingerprint.bits.checked_add(w).ok_or_else(corrupt)?;823 if fingerprint.bits > self.config.max_fingerprint_bits {824 return Err(corrupt());825 }826 fingerprint.value =827 (fingerprint.value << w) | u128::from(slots.slot(relative + slot)?);828 slot += 1;829 }830 at = slot as usize * w as usize;831 }832 if fingerprint.bits > self.config.max_fingerprint_bits {833 return Err(corrupt());834 }835 if previous_fingerprint.is_some_and(|previous: AerisFingerprint| {836 overlaps(previous, fingerprint)837 || previous.value << (128 - previous.bits)838 >= fingerprint.value << (128 - fingerprint.bits)839 }) {840 return Err(corrupt());841 }842 previous_fingerprint = Some(fingerprint);843 let matching = matches(fingerprint, hash);844 let mut previous = None;845 let mut mementos = 0u64;846 while at + m as usize <= count as usize * w as usize {847 let memento = slots.bits(relative as usize * w as usize + at, m)?;848 // A nonincreasing value is the existing padding terminator.849 if previous.is_some_and(|old| old >= memento) {850 break;851 }852 found |= matching && low <= memento && memento <= high;853 previous = Some(memento);854 mementos += 1;855 at += m as usize;856 }857 if mementos == 0 || mementos > u64::from(self.config.max_keys) {858 return Err(corrupt());859 }860 total += mementos;861 if total > self.len {862 return Err(corrupt());863 }864 position = end + 1;865 }866 Ok(found)867 }868 fn decode_box(869 &self,870 canonical: u32,871 slots: &mut SlotReader<'_, '_>,872 metadata: &[u8],873 start: u32,874 end: u32,875 ) -> Result<Keepsake> {876 let f = self.config.remainder_bits;877 let m = self.memento_bits;878 let w = f + m;879 let count = end - start + 1;880 let first = slots.slot(start)?;881 let mut fingerprint = AerisFingerprint {882 value: (u128::from(canonical) << f) | u128::from(first & bitmask(f)),883 bits: self.initial_bits(),884 };885 let mut at = f as usize;886 if flag(metadata, start, 2) && !flag(metadata, start, 1) {887 fingerprint.value = (fingerprint.value << m) | u128::from(first >> f);888 fingerprint.bits = fingerprint.bits.checked_add(m).ok_or_else(corrupt)?;889 let mut slot = 1;890 while slot < count - 1891 && flag(metadata, start + slot, 2)892 && !flag(metadata, start + slot, 1)893 {894 fingerprint.bits = fingerprint.bits.checked_add(w).ok_or_else(corrupt)?;895 if fingerprint.bits > self.config.max_fingerprint_bits {896 return Err(corrupt());897 }898 fingerprint.value =899 (fingerprint.value << w) | u128::from(slots.slot(start + slot)?);900 slot += 1;901 }902 at = slot as usize * w as usize;903 }904 if fingerprint.bits > self.config.max_fingerprint_bits {905 return Err(corrupt());906 }907 let mut mementos = Vec::new();908 while at + m as usize <= count as usize * w as usize {909 let memento = slots.bits(start as usize * w as usize + at, m)?;910 if mementos.last().is_some_and(|previous| *previous >= memento) {911 break;912 }913 mementos.push(memento);914 at += m as usize;915 if mementos.len() > self.config.max_keys as usize {916 return Err(corrupt());917 }918 }919 if mementos.is_empty() {920 return Err(corrupt());921 }922 Ok(Keepsake {923 fingerprint,924 mementos,925 })926 }927928 fn encode(&self, boxes: &[Keepsake]) -> Result<Option<Image>> {929 let g = self.geometry();930 let mut image = Image {931 metadata: vec![0; g.metadata_bytes()],932 slots: vec![0; g.slots as usize],933 used: 0,934 };935 let mut position = 0usize;936 for (index, b) in boxes.iter().enumerate() {937 let canonical = self.canonical(b.fingerprint);938 position = position.max(canonical as usize);939 let extension = b.fingerprint.bits - self.initial_bits();940 let prefix_bits = self.config.remainder_bits as usize + extension as usize;941 let total_bits = prefix_bits + b.mementos.len() * self.memento_bits as usize;942 let count = total_bits.div_ceil(g.width as usize);943 let end = position + count;944 if b.mementos.is_empty()945 || end > image.slots.len()946 || end - 1 - canonical as usize > self.config.max_shift_slots as usize947 {948 return Ok(None);949 }950 let slots = &mut image.slots[position..end];951 let suffix =952 b.fingerprint.value & mask128(b.fingerprint.bits - self.config.quotient_bits);953 let remainder = (suffix >> extension) as u64;954 put_bits(slots, 0, self.config.remainder_bits, g.width, remainder);955 if extension > 0 {956 let mut left = extension;957 let mut at = self.config.remainder_bits as usize;958 while left > 0 {959 let bits = if at == self.config.remainder_bits as usize {960 self.memento_bits961 } else {962 g.width963 };964 left -= bits;965 put_bits(966 slots,967 at,968 bits,969 g.width,970 (suffix >> left) as u64 & bitmask(bits),971 );972 at += bits as usize;973 }974 for slot in 0..prefix_bits / g.width as usize {975 set_flag(&mut image.metadata, (position + slot) as u32, 2);976 }977 }978 for (i, memento) in b.mementos.iter().enumerate() {979 put_bits(980 slots,981 prefix_bits + i * self.memento_bits as usize,982 self.memento_bits,983 g.width,984 *memento,985 );986 }987 set_flag(&mut image.metadata, canonical, 0);988 set_flag(&mut image.metadata, (end - 1) as u32, 1);989 if boxes990 .get(index + 1)991 .is_none_or(|next| self.canonical(next.fingerprint) != canonical)992 {993 set_flag(&mut image.metadata, (end - 1) as u32, 2);994 }995 image.used += count as u32;996 position = end;997 }998 if u64::from(image.used) * 100 > u64::from(g.canonical) * 95 {999 return Ok(None);1000 }1001 Ok(Some(image))1002 }1003 fn publish(&mut self, storage: &mut dyn Storage, image: &Image, workspace: &mut Workspace) {1004 let g = self.geometry();1005 self.nodes1006 .ensure_nodes(storage, g.bytes() / NODE_BYTES as u64)1007 .expect("admitted Aeris allocation failed");1008 // Allocated blocks and the immutable metadata/payload gaps start zero.1009 // Publish the complete encoded metadata and every slot, including the1010 // zeros that clear removed keepsakes, without rewriting those gaps.1011 self.nodes1012 .write_at(storage, 0, &image.metadata)1013 .expect("admitted Aeris metadata write failed");1014 let slots_per_span = NODE_BYTES / g.slot_bytes;1015 for (span, slots) in image.slots.chunks(slots_per_span).enumerate() {1016 let out = &mut workspace.bytes_mut()[..slots.len() * g.slot_bytes];1017 for (slot, encoded) in slots.iter().zip(out.chunks_exact_mut(g.slot_bytes)) {1018 encoded.copy_from_slice(&slot.to_le_bytes()[..g.slot_bytes]);1019 }1020 self.nodes1021 .write_at(1022 storage,1023 g.data_at + (span * slots_per_span * g.slot_bytes) as u64,1024 out,1025 )1026 .expect("admitted Aeris write failed");1027 }1028 }1029}10301031#[derive(Clone, Copy)]1032struct Geometry {1033 canonical: u32,1034 slots: u32,1035 width: u8,1036 slot_bytes: usize,1037 data_at: u64,1038}1039impl Geometry {1040 fn new(quotient: u8, shift: u32, width: u8) -> Self {1041 let slots = (1u32 << quotient) + shift;1042 let metadata = (slots as u64).div_ceil(64) * 24;1043 Self {1044 canonical: 1u32 << quotient,1045 slots,1046 width,1047 slot_bytes: (width as usize).div_ceil(8),1048 data_at: metadata.div_ceil(NODE_BYTES as u64) * NODE_BYTES as u64,1049 }1050 }1051 fn metadata_bytes(self) -> usize {1052 (self.slots as usize).div_ceil(64) * 241053 }1054 fn bytes(self) -> u64 {1055 (self.data_at + self.slots as u64 * self.slot_bytes as u64).div_ceil(NODE_BYTES as u64)1056 * NODE_BYTES as u641057 }1058}1059struct Image {1060 metadata: Vec<u8>,1061 slots: Vec<u64>,1062 used: u32,1063}1064const QUERY_METADATA_GROUPS: usize = (AERIS_MAX_SHIFT as usize).div_ceil(64) + 1;1065struct QueryRun {1066 start: u32,1067 end: u32,1068 // At most max_shift+1 slots, including an unaligned first metadata word.1069 flags: [[u64; 2]; QUERY_METADATA_GROUPS],1070}1071impl QueryRun {1072 fn read(metadata: &mut RunMetadata<'_, '_>, start: u32, end: u32) -> Result<Self> {1073 let mut out = Self {1074 start,1075 end,1076 flags: [[0; 2]; QUERY_METADATA_GROUPS],1077 };1078 for group in start / 64..=end / 64 {1079 let at = (group - start / 64) as usize;1080 out.flags[at] = [metadata.word(group, 1)?, metadata.word(group, 2)?];1081 }1082 Ok(out)1083 }1084 fn flag(&self, slot: u32, lane: usize) -> bool {1085 self.flags[(slot / 64 - self.start / 64) as usize][lane] & (1u64 << (slot % 64)) != 01086 }1087 fn box_end(&self, start: u32) -> Result<u32> {1088 for group in start / 64..=self.end / 64 {1089 let mut ends = self.flags[(group - self.start / 64) as usize][0];1090 if group == start / 64 {1091 ends &= !bitmask((start % 64) as u8);1092 }1093 if group == self.end / 64 {1094 ends &= bitmask((self.end % 64 + 1) as u8);1095 }1096 if ends != 0 {1097 return Ok(group * 64 + ends.trailing_zeros());1098 }1099 }1100 Err(corrupt())1101 }1102}1103fn corrupt() -> Error {1104 Error::InvalidInput("Aeris payload invariant")1105}1106fn prefix(hash: u128, bits: u8) -> AerisFingerprint {1107 AerisFingerprint {1108 value: hash >> (128 - bits),1109 bits,1110 }1111}1112fn matches(fingerprint: AerisFingerprint, hash: u128) -> bool {1113 prefix(hash, fingerprint.bits) == fingerprint1114}1115// Valid keepsakes are prefix-free and sorted by their left-aligned hash1116// prefixes. Their disjoint hash intervals therefore have increasing starts;1117// only the predecessor of hash can contain it, including at 128-bit widths.1118fn matching_box(boxes: &[Keepsake], hash: u128) -> Option<usize> {1119 boxes1120 .partition_point(|b| b.fingerprint.value << (128 - b.fingerprint.bits) <= hash)1121 .checked_sub(1)1122 .filter(|at| matches(boxes[*at].fingerprint, hash))1123}1124fn overlaps(a: AerisFingerprint, b: AerisFingerprint) -> bool {1125 if a.bits <= b.bits {1126 b.value >> (b.bits - a.bits) == a.value1127 } else {1128 a.value >> (a.bits - b.bits) == b.value1129 }1130}1131fn mask128(bits: u8) -> u128 {1132 if bits == 128 {1133 u128::MAX1134 } else {1135 (1u128 << bits) - 11136 }1137}1138fn intersects(mementos: &[u64], lower: u64, upper: u64) -> bool {1139 mementos.partition_point(|m| *m < lower) < mementos.partition_point(|m| *m <= upper)1140}1141fn flag(metadata: &[u8], slot: u32, kind: usize) -> bool {1142 let at = slot as usize / 64 * 24 + kind * 8 + slot as usize % 64 / 8;1143 metadata[at] & (1 << (slot % 8)) != 01144}1145fn set_flag(metadata: &mut [u8], slot: u32, kind: usize) {1146 let at = slot as usize / 64 * 24 + kind * 8 + slot as usize % 64 / 8;1147 metadata[at] |= 1 << (slot % 8);1148}1149fn put_bits(slots: &mut [u64], at: usize, bits: u8, width: u8, value: u64) {1150 for bit in 0..bits as usize {1151 let at = at + bit;1152 slots[at / width as usize] |= ((value >> bit) & 1) << (at % width as usize);1153 }1154}1155#[cfg(test)]1156#[path = "aeris_tests.rs"]1157mod tests;11581159#[cfg(test)]1160#[path = "range_filter_fault_tests.rs"]1161mod faults;