frozen_sorted.rs
cdk-rsx/crates/cdk-rsx-collections-minima/src/frozen_sorted.rs
1//! Bulk-built sorted directory with densely packed, contiguous leaves.2//!3//! Point lookup reads one aligned node per level. A bounded ordered scan seeks4//! once and then streams adjacent leaves without directory or sibling reads.56const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("frozen_sorted.rs");78use crate::{Collection, Error, Fixed, FixedKey, Result, Storage, Workspace};9use cdk_rsx_engine_nyxus::NyxusData;10use core::{cmp::Ordering, marker::PhantomData};1112const NODE_BYTES: usize = 4096;13const HEADER_BYTES: usize = 8;1415#[derive(Clone, Copy, Debug)]16pub struct SortedBuildConfig {17 pub max_entries: usize,18}1920impl Default for SortedBuildConfig {21 fn default() -> Self {22 Self {23 max_entries: 16_777_216,24 }25 }26}2728/// Move-only Nyxus descriptor; keys and values never use retained heap objects.29pub struct FrozenSortedMap<K: FixedKey, V: Fixed> {30 collection: Collection,31 len: u64,32 leaves: u64,33 nodes: u64,34 root: u64,35 height: u8,36 types: PhantomData<(K, V)>,37}3839// SAFETY: the complete live ownership is Collection; all other fields are40// integers or a zero-sized type marker. No decoded key/value or loan persists.41unsafe impl<K: FixedKey, V: Fixed> NyxusData for FrozenSortedMap<K, V> {42 const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;43}4445impl<K: FixedKey, V: Fixed> FrozenSortedMap<K, V> {46 pub const CONTRACT: [u8; 32] = crate::contract(47 "minima-frozen-sorted-map-v1",48 &[49 "4096-byte nodes; 8-byte count header; fixed keys then values",50 "FixedKey Ord; unique keys; directory keys are child maxima",51 "contiguous full leaves; bottom-up directories; u64 child indices",52 ],53 &[54 crate::MINIMA_POLICY,55 SOURCE_POLICY,56 K::CONTRACT,57 V::CONTRACT,58 ],59 );6061 pub const LEAF_CAPACITY: usize = leaf_capacity(K::WIDTH, V::WIDTH);62 /// A directory must shrink each level; singleton fanout is inadmissible.63 /// ```compile_fail64 /// use cdk_rsx_collections_minima::FrozenSortedMap;65 /// const NO_FANOUT: usize = FrozenSortedMap::<[u8; 2040], ()>::DIRECTORY_CAPACITY;66 /// ```67 pub const DIRECTORY_CAPACITY: usize = directory_capacity(K::WIDTH);6869 /// Sorts the finite input and rejects duplicate keys before stable writes.70 pub fn build(71 storage: &mut dyn Storage,72 mut entries: Vec<(K, V)>,73 config: SortedBuildConfig,74 workspace: &mut Workspace,75 ) -> Result<Self> {76 let _ = (Self::LEAF_CAPACITY, Self::DIRECTORY_CAPACITY);77 if entries.len() > config.max_entries {78 return Err(Error::Capacity);79 }80 entries.sort_unstable_by(|left, right| left.0.cmp(&right.0));81 Self::from_sorted(storage, entries, config, workspace)82 }8384 /// A sorted input avoids sorting work; validation still checks every key.85 /// Equal or descending adjacent keys reject before stable allocation.86 pub fn from_sorted(87 storage: &mut dyn Storage,88 entries: Vec<(K, V)>,89 config: SortedBuildConfig,90 workspace: &mut Workspace,91 ) -> Result<Self> {92 let leaf_capacity = Self::LEAF_CAPACITY;93 let directory_capacity = Self::DIRECTORY_CAPACITY;94 if entries.len() > config.max_entries {95 return Err(Error::Capacity);96 }97 if entries.windows(2).any(|pair| pair[0].0 >= pair[1].0) {98 return Err(Error::InvalidInput("frozen sorted keys must increase"));99 }100 let leaves = entries.len().div_ceil(leaf_capacity) as u64;101 let (nodes, height) = shape(leaves, directory_capacity)?;102 let mut collection = Collection::new(storage)?;103 collection.ensure_nodes(storage, nodes)?;104 for (leaf, chunk) in entries.chunks(leaf_capacity).enumerate() {105 let node = workspace.bytes_mut();106 node[..4].copy_from_slice(&(chunk.len() as u32).to_le_bytes());107 node[4..HEADER_BYTES].fill(0);108 let values_at = HEADER_BYTES + leaf_capacity * K::WIDTH;109 let end = if V::WIDTH == 0 {110 HEADER_BYTES + chunk.len() * K::WIDTH111 } else {112 node[HEADER_BYTES + chunk.len() * K::WIDTH..values_at].fill(0);113 values_at + chunk.len() * V::WIDTH114 };115 for (slot, (key, value)) in chunk.iter().enumerate() {116 let at = HEADER_BYTES + slot * K::WIDTH;117 key.encode(&mut node[at..at + K::WIDTH]);118 let at = HEADER_BYTES + leaf_capacity * K::WIDTH + slot * V::WIDTH;119 value.encode(&mut node[at..at + V::WIDTH]);120 }121 // One exact occupied prefix; the initialized node tail stays zero.122 collection.write_at(storage, leaf as u64 * NODE_BYTES as u64, &node[..end])?;123 }124 // All leaves and each successive directory level are contiguous. Child125 // maxima are therefore borrowed directly from the original sorted input;126 // no cloned keys or temporary vectors are needed for directory levels.127 let mut level_start = 0;128 let mut level_nodes = leaves;129 let mut entries_per_child = leaf_capacity;130 let mut next_node = leaves;131 while level_nodes > 1 {132 let parent_start = next_node;133 let parents = level_nodes.div_ceil(directory_capacity as u64);134 for parent in 0..parents {135 let first_child = parent * directory_capacity as u64;136 let count = (level_nodes - first_child).min(directory_capacity as u64) as usize;137 let node = workspace.bytes_mut();138 node[..4].copy_from_slice(&(count as u32).to_le_bytes());139 node[4..HEADER_BYTES].fill(0);140 let children_at = HEADER_BYTES + directory_capacity * K::WIDTH;141 node[HEADER_BYTES + count * K::WIDTH..children_at].fill(0);142 let end = children_at + count * 8;143 for slot in 0..count {144 let child = first_child + slot as u64;145 // child+1 <= leaves <= entries.len(), so conversion/addition146 // fit usize. Saturation is the correct capped product: any147 // larger subtree ends at entries.len() as well.148 let end = (child as usize + 1)149 .saturating_mul(entries_per_child)150 .min(entries.len());151 let maximum = &entries[end - 1].0;152 let at = HEADER_BYTES + slot * K::WIDTH;153 maximum.encode(&mut node[at..at + K::WIDTH]);154 let at = HEADER_BYTES + directory_capacity * K::WIDTH + slot * 8;155 node[at..at + 8].copy_from_slice(&(level_start + child).to_le_bytes());156 }157 collection.write_at(storage, next_node * NODE_BYTES as u64, &node[..end])?;158 next_node += 1;159 }160 level_start = parent_start;161 level_nodes = parents;162 entries_per_child = entries_per_child163 .saturating_mul(directory_capacity)164 .min(entries.len());165 }166 if next_node != nodes {167 return Err(Error::Corrupt("frozen sorted construction shape"));168 }169 Ok(Self {170 collection,171 len: entries.len() as u64,172 leaves,173 nodes,174 root: nodes.saturating_sub(1),175 height,176 types: PhantomData,177 })178 }179180 pub fn get(181 &self,182 storage: &dyn Storage,183 key: &K,184 workspace: &mut Workspace,185 ) -> Result<Option<V>> {186 let Some(leaf) = self.seek(storage, key, workspace)? else {187 return Ok(None);188 };189 let node = self.collection.read_node(storage, leaf, workspace)?;190 let count = count(node, Self::LEAF_CAPACITY)?;191 let mut left = 0;192 let mut right = count;193 while left < right {194 let middle = left + (right - left) / 2;195 let at = HEADER_BYTES + middle * K::WIDTH;196 match K::decode(&node[at..at + K::WIDTH])?.cmp(key) {197 Ordering::Less => left = middle + 1,198 Ordering::Greater => right = middle,199 Ordering::Equal => {200 let at = HEADER_BYTES + Self::LEAF_CAPACITY * K::WIDTH + middle * V::WIDTH;201 return V::decode(&node[at..at + V::WIDTH]).map(Some);202 }203 }204 }205 Ok(None)206 }207208 /// Look up arbitrary keys into their corresponding caller-owned positions.209 ///210 /// A transient permutation sorts requests by key, leaving `keys` unchanged.211 /// Each selected leaf is read once; directory descent is repeated only for212 /// the first request in the next leaf. Duplicate requests retain distinct213 /// output positions and decode their stored values independently. No stable214 /// node cache or borrowed value survives the synchronous call.215 ///216 /// Output length rejects before allocation, reads or output changes. Scratch217 /// is one `usize` per key plus the caller's workspace; a singleton uses a218 /// stack index without allocating or sorting. Allocation failure219 /// returns Capacity; a later read/decode error can leave completed positions220 /// changed. Grouping and sorting can cost more than scalar distant lookups.221 pub fn get_many(222 &self,223 storage: &dyn Storage,224 keys: &[K],225 out: &mut [Option<V>],226 workspace: &mut Workspace,227 ) -> Result<()> {228 if keys.len() != out.len() {229 return Err(Error::InvalidInput("frozen sorted batch output length"));230 }231 if keys.is_empty() || self.len == 0 {232 self.collection.validate(storage)?;233 out.fill(None);234 return Ok(());235 }236 let singleton = [0];237 let mut permutation = Vec::new();238 let order = if keys.len() == 1 {239 &singleton[..]240 } else {241 permutation242 .try_reserve_exact(keys.len())243 .map_err(|_| Error::Capacity)?;244 permutation.extend(0..keys.len());245 permutation.sort_unstable_by(|&left, &right| {246 keys[left].cmp(&keys[right]).then_with(|| left.cmp(&right))247 });248 &permutation[..]249 };250 let mut cursor = 0;251 while cursor < order.len() {252 let Some(leaf) = self.seek(storage, &keys[order[cursor]], workspace)? else {253 // Requests are now nondecreasing, so all remaining keys exceed254 // the directory's maximum as well.255 for &index in &order[cursor..] {256 out[index] = None;257 }258 return Ok(());259 };260 let node = self.collection.read_node(storage, leaf, workspace)?;261 let count = count(node, Self::LEAF_CAPACITY)?;262 let maximum_at = HEADER_BYTES + (count - 1) * K::WIDTH;263 let maximum = K::decode(&node[maximum_at..maximum_at + K::WIDTH])?;264 if leaf == self.leaves - 1 && keys[order[cursor]] > maximum {265 for &index in &order[cursor..] {266 out[index] = None;267 }268 return Ok(());269 }270 let mut group_end = cursor + 1;271 while group_end < order.len() && keys[order[group_end]] <= maximum {272 group_end += 1;273 }274 let mut lower = 0;275 for &index in &order[cursor..group_end] {276 let key = &keys[index];277 let mut left = lower;278 let mut right = count;279 let mut found = None;280 while left < right {281 let middle = left + (right - left) / 2;282 let at = HEADER_BYTES + middle * K::WIDTH;283 match K::decode(&node[at..at + K::WIDTH])?.cmp(key) {284 Ordering::Less => left = middle + 1,285 Ordering::Greater => right = middle,286 Ordering::Equal => {287 found = Some(middle);288 left = middle;289 break;290 }291 }292 }293 lower = left;294 out[index] = match found {295 Some(slot) => {296 let at = HEADER_BYTES + Self::LEAF_CAPACITY * K::WIDTH + slot * V::WIDTH;297 Some(V::decode(&node[at..at + V::WIDTH])?)298 }299 None => None,300 };301 }302 cursor = group_end;303 if leaf == self.leaves - 1 {304 // The last leaf's maximum is already decoded. Do not fetch that305 // same source node again for a sorted above-maximum suffix.306 for &index in &order[cursor..] {307 out[index] = None;308 }309 return Ok(());310 }311 }312 Ok(())313 }314315 /// Calls `visit` in key order, starting at the first key >= `start`.316 ///317 /// At most `limit` owned records are decoded. `false` stops immediately.318 /// With no start, no directory nodes are read. The workspace is reused for319 /// each leaf and no node view escapes this synchronous operation.320 pub fn scan(321 &self,322 storage: &dyn Storage,323 start: Option<&K>,324 limit: usize,325 mut visit: impl FnMut(K, V) -> bool,326 workspace: &mut Workspace,327 ) -> Result<usize> {328 if self.len == 0 || limit == 0 {329 self.collection.validate(storage)?;330 return Ok(0);331 }332 let mut leaf = match start {333 Some(start) => match self.seek(storage, start, workspace)? {334 Some(leaf) => leaf,335 None => return Ok(0),336 },337 None => 0,338 };339 let mut first = true;340 let mut visited = 0;341 while leaf < self.leaves && visited < limit {342 let remaining = limit - visited;343 let node = if (!first || start.is_none()) && remaining < Self::LEAF_CAPACITY {344 // Starting at slot zero needs all searchable keys but only the345 // selected value prefix. One covering read preserves the source346 // node's first-read eligibility; the untouched tail is unused.347 let span = HEADER_BYTES + Self::LEAF_CAPACITY * K::WIDTH + remaining * V::WIDTH;348 self.collection.read_at(349 storage,350 leaf.checked_mul(NODE_BYTES as u64).ok_or(Error::Capacity)?,351 &mut workspace.bytes_mut()[..span],352 )?;353 workspace.bytes()354 } else {355 self.collection.read_node(storage, leaf, workspace)?356 };357 let count = count(node, Self::LEAF_CAPACITY)?;358 let begin = if first {359 match start {360 Some(start) => lower_bound::<K>(node, start, count)?,361 None => 0,362 }363 } else {364 0365 };366 first = false;367 for slot in begin..count {368 let at = HEADER_BYTES + slot * K::WIDTH;369 let key = K::decode(&node[at..at + K::WIDTH])?;370 let at = HEADER_BYTES + Self::LEAF_CAPACITY * K::WIDTH + slot * V::WIDTH;371 let value = V::decode(&node[at..at + V::WIDTH])?;372 visited += 1;373 if !visit(key, value) || visited == limit {374 return Ok(visited);375 }376 }377 leaf += 1;378 }379 Ok(visited)380 }381382 /// Descends directories only, leaving the leaf's first fetch to the caller.383 fn seek(384 &self,385 storage: &dyn Storage,386 key: &K,387 workspace: &mut Workspace,388 ) -> Result<Option<u64>> {389 if self.len == 0 {390 self.collection.validate(storage)?;391 return Ok(None);392 }393 let mut current = self.root;394 for remaining in (2..=self.height).rev() {395 let node = self.collection.read_node(storage, current, workspace)?;396 let count = count(node, Self::DIRECTORY_CAPACITY)?;397 let slot = lower_bound::<K>(node, key, count)?;398 if slot == count {399 return Ok(None);400 }401 let at = HEADER_BYTES + Self::DIRECTORY_CAPACITY * K::WIDTH + slot * 8;402 let child = u64::from_le_bytes(node[at..at + 8].try_into().unwrap());403 if child >= current404 || child >= self.nodes405 || (remaining == 2 && child >= self.leaves)406 || (remaining > 2 && child < self.leaves)407 {408 return Err(Error::Corrupt("frozen sorted child index"));409 }410 current = child;411 }412 if current >= self.leaves {413 return Err(Error::Corrupt("frozen sorted leaf index"));414 }415 Ok(Some(current))416 }417418 pub fn len(&self) -> u64 {419 self.len420 }421422 pub fn is_empty(&self) -> bool {423 self.len == 0424 }425426 pub fn height(&self) -> u8 {427 self.height428 }429430 pub fn node_count(&self) -> u64 {431 self.nodes432 }433434 pub fn leaf_count(&self) -> u64 {435 self.leaves436 }437438 pub fn block_count(&self) -> usize {439 self.collection.block_count()440 }441442 pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {443 self.collection.retire(storage)444 }445}446447const fn leaf_capacity(key: usize, value: usize) -> usize {448 assert!(449 key != 0,450 "frozen sorted keys must have positive fixed width"451 );452 let Some(stride) = key.checked_add(value) else {453 panic!("frozen sorted fixed stride overflow");454 };455 assert!(456 stride <= NODE_BYTES - HEADER_BYTES,457 "frozen sorted entry exceeds one node"458 );459 (NODE_BYTES - HEADER_BYTES) / stride460}461462const fn directory_capacity(key: usize) -> usize {463 let Some(stride) = key.checked_add(8) else {464 panic!("frozen sorted directory stride overflow");465 };466 assert!(467 key > 0 && stride <= (NODE_BYTES - HEADER_BYTES) / 2,468 "frozen sorted directory requires at least two children"469 );470 (NODE_BYTES - HEADER_BYTES) / stride471}472473fn shape(leaves: u64, capacity: usize) -> Result<(u64, u8)> {474 if leaves == 0 {475 return Ok((0, 0));476 }477 let mut nodes = leaves;478 let mut level = leaves;479 let mut height = 1u8;480 while level > 1 {481 level = level.div_ceil(capacity as u64);482 nodes = nodes.checked_add(level).ok_or(Error::Capacity)?;483 height = height.checked_add(1).ok_or(Error::Capacity)?;484 }485 Ok((nodes, height))486}487488fn count(node: &[u8; NODE_BYTES], capacity: usize) -> Result<usize> {489 let count = u32::from_le_bytes(node[..4].try_into().unwrap()) as usize;490 if count == 0 || count > capacity {491 return Err(Error::Corrupt("frozen sorted node count"));492 }493 Ok(count)494}495496// Directories and scan starts need only an insertion position, so keep their497// search free of exact-match status and its extra branch on each comparison.498fn lower_bound<K: FixedKey>(node: &[u8; NODE_BYTES], key: &K, count: usize) -> Result<usize> {499 let mut left = 0;500 let mut right = count;501 while left < right {502 let middle = left + (right - left) / 2;503 let at = HEADER_BYTES + middle * K::WIDTH;504 match K::decode(&node[at..at + K::WIDTH])?.cmp(key) {505 Ordering::Less => left = middle + 1,506 Ordering::Equal | Ordering::Greater => right = middle,507 }508 }509 Ok(left)510}