storage.rs

cdk-rsx/crates/cdk-rsx-engine-minima/src/storage.rs

storage.rs1,687 lines← SDK documentation
1use crate::{2    BLOCK_BYTES, Error, Fixed, NODE_BYTES, NODES_PER_BLOCK, Result, Workspace, width_contract,3};4use cdk_rsx_engine_nyxus::{Nyxus, NyxusData};5use cdk_rsx_platform::memory::Memory;6use core::cell::{Cell, RefCell};7use std::rc::Rc;8use std::sync::atomic::{AtomicU64, Ordering};910type RetainedVec<T> = std::vec::Vec<T, Nyxus>;11const FORMAT: [u8; 8] = *b"MINIMA01";12const HEADER_BYTES: usize = 16;13const LIVE: u64 = u64::MAX;14static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1);1516/// Nonowning collection identity. Fields are private; copying an identity never17/// creates a descriptor or grants byte access. Generation changes on owner reuse.18#[repr(C)]19#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]20pub struct CollectionId {21    domain: u64,22    owner: u64,23    generation: u64,24}25// SAFETY: inline identity, no owned backing or mutable capability.26unsafe impl NyxusData for CollectionId {27    const __NYXUS_POLICY: [u8; 32] = <Self as Fixed>::CONTRACT;28}29impl Fixed for CollectionId {30    const WIDTH: usize = 24;31    const CONTRACT: [u8; 32] = width_contract("minima-collection-identity-le-v1", 24, &[]);32    fn encode(&self, out: &mut [u8]) {33        assert_eq!(out.len(), Self::WIDTH);34        self.domain.encode(&mut out[..8]);35        self.owner.encode(&mut out[8..16]);36        self.generation.encode(&mut out[16..]);37    }38    fn decode(bytes: &[u8]) -> Result<Self> {39        if bytes.len() != Self::WIDTH {40            return Err(Error::Bounds);41        }42        Ok(Self {43            domain: u64::decode(&bytes[..8])?,44            owner: u64::decode(&bytes[8..16])?,45            generation: u64::decode(&bytes[16..])?,46        })47    }48}49// SAFETY: the three integer fields have canonical identity and lexicographic Ord.50unsafe impl crate::FixedKey for CollectionId {}5152#[repr(C)]53#[derive(Clone, Copy)]54struct Owner {55    generation: u64,56    // Live entries use LIVE. Retired entries link to the next free owner, with57    // one-based indices and zero terminating the list. The generation remains58    // intact for the next incarnation; exhausted entries are never linked.59    next_free: u64,60}61#[repr(C)]62#[derive(Clone, Copy)]63struct Slot {64    generation: u64,65    // Physical addresses are already one-based; zero terminates the free list.66    next_free: u64,67}68#[repr(C)]69#[derive(Clone, Copy)]70struct Page {71    physical: u64,72    generation: u64,73}74impl Page {75    const EMPTY: Self = Self {76        physical: 0,77        generation: 0,78    };79}8081/// All allocator metadata is retained heap data, physically separate from every82/// collection payload block. The linear mapping belongs to the Hylix adapter.83struct Authority {84    slots: RetainedVec<Slot>,85    free: u64,86    owners: RetainedVec<Owner>,87    free_owners: u64,88    linear: RetainedVec<Page>,89}90struct RootInner {91    domain: u64,92    provider_live: Cell<bool>,93    authority: RefCell<Authority>,94}9596/// Retained root for one physical stable address space. Keep this in private97/// root-attached Nyxus Data; cloning it shares the same allocator authority.98/// It contains no physical provider, code pointer, transient buffer or vtable.99#[repr(transparent)]100#[derive(Clone)]101pub struct Root {102    inner: Rc<RootInner, Nyxus>,103}104// SAFETY: Root owns only Nyxus Rc/Vec metadata. Interior mutation is private105// allocator bookkeeping, not application data access. No loans are persisted.106unsafe impl NyxusData for Root {107    const __NYXUS_POLICY: [u8; 32] = crate::MINIMA_POLICY;108}109impl core::fmt::Debug for Root {110    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {111        f.debug_struct("Root")112            .field("domain", &self.inner.domain)113            .finish_non_exhaustive()114    }115}116impl Root {117    /// Compare authorities without changing a retained reference count.118    pub fn same_authority(&self, other: &Self) -> bool {119        self.same(other)120    }121    fn same(&self, other: &Self) -> bool {122        Rc::ptr_eq(&self.inner, &other.inner)123    }124    fn owner(&self) -> Result<CollectionId> {125        let mut authority = self.inner.authority.borrow_mut();126        let index = if authority.free_owners != 0 {127            let index = authority.free_owners - 1;128            let owner = &mut authority.owners[index as usize];129            owner.generation = owner.generation.checked_add(1).ok_or(Error::Overflow)?;130            let next = owner.next_free;131            owner.next_free = LIVE;132            authority.free_owners = next;133            index134        } else {135            let index = u64::try_from(authority.owners.len()).map_err(|_| Error::Capacity)?;136            if index >= LIVE - 1 {137                return Err(Error::Capacity);138            }139            authority.owners.push(Owner {140                generation: 1,141                next_free: LIVE,142            });143            index144        };145        Ok(CollectionId {146            domain: self.inner.domain,147            owner: index,148            generation: authority.owners[index as usize].generation,149        })150    }151    fn validate(&self, id: CollectionId) -> Result<()> {152        if id.domain != self.inner.domain {153            return Err(Error::InvalidInput("foreign Minima owner"));154        }155        let authority = self.inner.authority.borrow();156        if id.owner >= authority.owners.len() as u64 {157            return Err(Error::InvalidInput("retired Minima owner"));158        }159        let owner = &authority.owners[id.owner as usize];160        if owner.next_free == LIVE && owner.generation == id.generation {161            Ok(())162        } else {163            Err(Error::InvalidInput("retired Minima owner"))164        }165    }166    fn validate_block(&self, block: BlockRef<'_>) -> Result<()> {167        // Only a raw owning Block can produce this header/Page borrow. Its168        // physical slot stays owned, but its Collection may already be retired.169        let owner = block.authority.owner;170        if !self.same(&block.authority.root) || owner.domain != self.inner.domain {171            return Err(Error::InvalidInput("foreign Minima block"));172        }173        let authority = self.inner.authority.borrow();174        if !authority175            .owners176            .get(owner.owner as usize)177            .is_some_and(|entry| entry.next_free == LIVE && entry.generation == owner.generation)178        {179            return Err(Error::InvalidInput("retired Minima owner"));180        }181        // BlockRef borrows a private Page inside an owning Block. Its lifetime182        // excludes Drop, and only that Block releases its Page. This proves183        // physical ownership and generation without a184        // duplicate slot lookup. No constructor accepts externally supplied Page185        // fields or an unowned physical address.186        // The owner check above is different: a separately allocated Block can187        // outlive its Collection, whose Drop retires the owner's generation.188        Ok(())189    }190    fn release(&self, page: Page) {191        let mut authority = self.inner.authority.borrow_mut();192        let next_free = authority.free;193        let slot = authority194            .slots195            .get_mut(page.physical as usize - 1)196            .expect("Minima block slot");197        assert!(198            slot.next_free == LIVE && slot.generation == page.generation,199            "Minima block retirement"200        );201        // The owning Block or Collection directory supplies physical ownership.202        // Slot metadata needs no duplicate owner identity, only reuse generation.203        slot.next_free = next_free;204        if page.generation != u64::MAX {205            authority.free = page.physical;206        }207    }208    fn retire_owner(&self, id: CollectionId) {209        let mut authority = self.inner.authority.borrow_mut();210        let next_free = authority.free_owners;211        let owner = &mut authority.owners[id.owner as usize];212        assert!(213            owner.next_free == LIVE && owner.generation == id.generation,214            "Minima owner retirement"215        );216        owner.next_free = next_free;217        if id.generation != u64::MAX {218            authority.free_owners = id.owner + 1;219        }220    }221    /// Number of live physical payload blocks, including Hylix's virtual pages.222    /// This is a diagnostic traversal, never part of collection node access.223    pub fn allocated_blocks(&self) -> u64 {224        self.inner225            .authority226            .borrow()227            .slots228            .iter()229            .filter(|slot| slot.next_free == LIVE)230            .count() as u64231    }232}233234/// Root and owner are one contiguous header, shared by each directory entry.235/// Borrowed capabilities pass this header and their Page as two pointers.236#[repr(C)]237struct BlockAuthority {238    root: Root,239    owner: CollectionId,240}241242/// One move-only owned physical block. Only Storage allocation can construct it;243/// Drop returns the whole block to its retained authority. It never writes stable244/// bytes or depends on a thread-local active provider.245pub struct Block {246    authority: BlockAuthority,247    page: Page,248}249impl Block {250    pub const fn offset(&self) -> u64 {251        self.page.physical * BLOCK_BYTES252    }253    pub const fn generation(&self) -> u64 {254        self.page.generation255    }256257    /// Borrow this owning capability for a synchronous provider operation.258    /// The owner cannot be dropped while the borrowed capability is still used.259    ///260    /// ```compile_fail261    /// use cdk_rsx_engine_minima::{Arena, Collection, Storage};262    /// use cdk_rsx_platform::memory::VecMemory;263    /// let mut arena = Arena::format(VecMemory::new()).unwrap();264    /// let collection = Collection::new(&mut arena).unwrap();265    /// let id = collection.identity();266    /// let block = arena.allocate(id).unwrap();267    /// let borrowed = block.borrow();268    /// drop(block);269    /// arena.read(borrowed, 0, &mut [0]).unwrap();270    /// ```271    pub fn borrow(&self) -> BlockRef<'_> {272        BlockRef {273            authority: &self.authority,274            page: &self.page,275        }276    }277278    fn into_page(mut self, root: &Root, owner: CollectionId) -> Result<Page> {279        if !root.same(&self.authority.root) || owner != self.authority.owner {280            return Err(Error::InvalidInput("foreign Minima allocation"));281        }282        // The caller secured directory capacity before acquiring this Block.283        // Move its physical ownership once; ordinary Drop still releases the284        // real Root reference. A consumed, disarmed Block never escapes.285        Ok(core::mem::replace(&mut self.page, Page::EMPTY))286    }287}288impl Drop for Block {289    fn drop(&mut self) {290        if self.page.physical != 0 {291            self.authority.root.release(self.page);292        }293    }294}295296/// A synchronous, nonowning borrow of an actually owned physical block.297/// Private fields prevent construction from offsets or decoded identities.298/// Copying the borrow neither retains nor releases stable storage.299///300/// ```compile_fail301/// use cdk_rsx_engine_minima::BlockRef;302/// let forged = BlockRef { authority: (), page: () };303/// ```304#[derive(Clone, Copy)]305pub struct BlockRef<'a> {306    authority: &'a BlockAuthority,307    page: &'a Page,308}309impl BlockRef<'_> {310    pub const fn offset(self) -> u64 {311        self.page.physical * BLOCK_BYTES312    }313    pub const fn generation(self) -> u64 {314        self.page.generation315    }316}317318/// A synchronous byte capability borrowed from a live Collection.319/// Only Collection's private directory lookup constructs it. Borrowing the320/// whole descriptor excludes retirement, truncation and page reuse; unlike a321/// raw Block borrow, it proves the canonical owner is still live.322///323/// ```compile_fail324/// use cdk_rsx_engine_minima::CollectionBlockRef;325/// let forged = CollectionBlockRef { collection: (), offset: 65_536 };326/// ```327/// A raw block cannot be promoted to this stronger capability:328/// ```compile_fail329/// use cdk_rsx_engine_minima::{Arena, Collection, Storage};330/// use cdk_rsx_platform::memory::VecMemory;331/// let mut arena = Arena::format(VecMemory::new()).unwrap();332/// let collection = Collection::new(&mut arena).unwrap();333/// let block = arena.allocate(collection.identity()).unwrap();334/// arena.read_collection(block.borrow(), 0, &mut [0]).unwrap();335/// ```336#[derive(Clone, Copy)]337pub struct CollectionBlockRef<'a> {338    collection: &'a Collection,339    offset: u64,340}341impl CollectionBlockRef<'_> {342    pub const fn offset(self) -> u64 {343        self.offset344    }345}346347/// One newly acquired whole block, temporarily owned through a live Collection348/// borrow. The collection cannot retire before this ticket is consumed or349/// dropped. Keeping its Root borrowed avoids changing a retained reference count350/// for each page added to the directory.351///352/// The ticket is not persistent data or a byte-access capability. Only the same353/// Collection can consume it into its private directory; dropping it releases354/// the page, including after a wrapper rejects an acquisition.355///356/// ```compile_fail357/// use cdk_rsx_engine_minima::{Arena, Collection, Storage};358/// use cdk_rsx_platform::memory::VecMemory;359/// let mut arena = Arena::format(VecMemory::new()).unwrap();360/// let collection = Collection::new(&mut arena).unwrap();361/// let allocation = arena.allocate_collection(&collection).unwrap();362/// drop(collection);363/// drop(allocation);364/// ```365#[must_use]366pub struct CollectionAllocation<'a> {367    collection: &'a Collection,368    page: Page,369}370impl CollectionAllocation<'_> {371    fn into_page(mut self, collection: &Collection) -> Result<Page> {372        if !core::ptr::eq(self.collection, collection) {373            return Err(Error::InvalidInput("foreign Minima allocation"));374        }375        Ok(core::mem::replace(&mut self.page, Page::EMPTY))376    }377}378impl Drop for CollectionAllocation<'_> {379    fn drop(&mut self) {380        if self.page.physical != 0 {381            self.collection.authority.root.release(self.page);382        }383    }384}385386/// Instrumentable collection byte provider. Custom wrappers forward these387/// methods; no instrumentation or automatic cache is in the default hot path.388pub trait Storage {389    fn root(&self) -> Root;390    /// Read-only identity check. Wrappers may forward this to avoid cloning a391    /// retained Rc on no-fetch validation paths.392    fn same_root(&self, root: &Root) -> bool {393        self.root().same(root)394    }395    /// Acquire an exclusive, all-byte-zero whole block for this live owner.396    /// Custom wrappers must preserve this initialization and ownership promise.397    /// Arena growth supplies zero bytes; reused physical blocks are cleared398    /// before this owning capability is returned. No other owner may alias it.399    fn allocate(&mut self, owner: CollectionId) -> Result<Block>;400    /// Acquire the same initialized block through a live Collection borrow.401    /// Providers can avoid the raw Block's retained Root and live-owner lookup:402    /// this borrow excludes retirement. Exact provider Root identity still must403    /// be checked. Wrappers should forward this method to preserve that path;404    /// the default retains their raw-allocation instrumentation and semantics.405    fn allocate_collection<'a>(406        &mut self,407        collection: &'a Collection,408    ) -> Result<CollectionAllocation<'a>> {409        let block = self.allocate(collection.authority.owner)?;410        let page = block.into_page(&collection.authority.root, collection.authority.owner)?;411        Ok(CollectionAllocation { collection, page })412    }413    /// Grow a live collection to at least this many total owned blocks.414    /// Providers may acquire the exact fresh physical extent once, preserving415    /// the same initialized bytes and per-page generations. This method never416    /// shrinks a directory. Wrappers forward it to preserve bulk acquisition;417    /// the default keeps their individual allocation/fault hooks in the path.418    fn grow_collection(&mut self, collection: &mut Collection, blocks: usize) -> Result<()> {419        if !self.same_root(&collection.authority.root) {420            return Err(Error::InvalidInput("foreign Minima storage"));421        }422        if blocks <= collection.blocks.len() {423            return Ok(());424        }425        collection.blocks.reserve(blocks);426        while collection.blocks.len() < blocks {427            let allocation = self.allocate_collection(collection)?;428            let page = allocation.into_page(collection)?;429            collection.blocks.push(page);430        }431        Ok(())432    }433    fn validate(&self, owner: CollectionId) -> Result<()>;434    /// Read through the borrowed owning capability's canonical root and owner.435    fn read(&self, block: BlockRef<'_>, at: u64, out: &mut [u8]) -> Result<()>;436    /// Backend mutation failures abort the physical execution rather than return437    /// into a frame that could commit a partially changed collection.438    fn write(&mut self, block: BlockRef<'_>, at: u64, bytes: &[u8]) -> Result<()>;439    /// Read through a genuine live Collection borrow. The capability proves440    /// live ownership; providers still check exact Root identity and bounds.441    /// Wrappers must forward this capability, not reconstruct a raw Block.442    fn read_collection(&self, block: CollectionBlockRef<'_>, at: u64, out: &mut [u8])443    -> Result<()>;444    /// Write under the same live borrow and execution-abort contract as write.445    fn write_collection(446        &mut self,447        block: CollectionBlockRef<'_>,448        at: u64,449        bytes: &[u8],450    ) -> Result<()>;451}452453const INLINE_PAGES: usize = 16;454455/// The first MiB of payload needs no separately allocated directory backing.456/// len is the occupancy authority; unused inline entries are plain zero Pages,457/// and rest owns exactly len.saturating_sub(INLINE_PAGES) initialized entries.458#[repr(C)]459struct PageDirectory {460    inline: [Page; INLINE_PAGES],461    rest: RetainedVec<Page>,462    len: usize,463}464impl PageDirectory {465    fn new() -> Self {466        Self {467            inline: [Page::EMPTY; INLINE_PAGES],468            rest: RetainedVec::new_in(Nyxus),469            len: 0,470        }471    }472    fn len(&self) -> usize {473        self.len474    }475    fn get(&self, index: usize) -> Option<&Page> {476        if index >= self.len {477            None478        } else if index < INLINE_PAGES {479            Some(&self.inline[index])480        } else {481            self.rest.get(index - INLINE_PAGES)482        }483    }484    fn reserve(&mut self, len: usize) {485        self.rest.reserve(486            len.saturating_sub(INLINE_PAGES)487                .saturating_sub(self.rest.len()),488        );489    }490    fn push(&mut self, page: Page) {491        if self.len < INLINE_PAGES {492            self.inline[self.len] = page;493        } else {494            self.rest.push(page);495        }496        self.len += 1;497    }498    fn truncate(&mut self, len: usize) {499        if len < self.len {500            self.inline[len.min(INLINE_PAGES)..self.len.min(INLINE_PAGES)].fill(Page::EMPTY);501            self.rest.truncate(len.saturating_sub(INLINE_PAGES));502            self.len = len;503        }504    }505}506impl core::ops::Index<usize> for PageDirectory {507    type Output = Page;508    fn index(&self, index: usize) -> &Page {509        self.get(index).expect("Minima block directory bounds")510    }511}512513/// The two private destinations that take ownership of bulk-claimed pages.514/// Reserve before physical mutation so publication cannot allocate mid-batch.515trait PageSink {516    fn reserve_pages(&mut self, additional: usize);517    fn push_page(&mut self, page: Page);518}519impl PageSink for PageDirectory {520    fn reserve_pages(&mut self, additional: usize) {521        self.reserve(self.len() + additional);522    }523    fn push_page(&mut self, page: Page) {524        self.push(page);525    }526}527impl PageSink for RetainedVec<Page> {528    fn reserve_pages(&mut self, additional: usize) {529        self.reserve(additional);530    }531    fn push_page(&mut self, page: Page) {532        self.push(page);533    }534}535536/// A collection's private, move-only block directory and owning identity.537/// Empty descriptors claim no stable blocks. Collection Drop retires only its538/// own blocks; unrelated collections and Hylix pages remain untouched.539pub struct Collection {540    authority: BlockAuthority,541    blocks: PageDirectory,542}543// SAFETY: complete reachability is one retained Root and a private PageDirectory.544// Collection uniquely owns each private physical Page until explicit release;545// root/owner identity is shared by this complete directory. No payload T.546unsafe impl NyxusData for Collection {547    const __NYXUS_POLICY: [u8; 32] = crate::MINIMA_POLICY;548}549impl Collection {550    pub fn new(storage: &mut dyn Storage) -> Result<Self> {551        let root = storage.root();552        let id = root.owner()?;553        Ok(Self {554            authority: BlockAuthority { root, owner: id },555            blocks: PageDirectory::new(),556        })557    }558    pub const fn identity(&self) -> CollectionId {559        self.authority.owner560    }561    pub fn block_count(&self) -> usize {562        self.blocks.len()563    }564    pub fn node_capacity(&self) -> u64 {565        self.blocks.len() as u64 * NODES_PER_BLOCK566    }567    pub fn validate(&self, storage: &dyn Storage) -> Result<()> {568        if !storage.same_root(&self.authority.root) {569            return Err(Error::InvalidInput("foreign Minima storage"));570        }571        // Only this move-only Collection can retire its unique owner. A real572        // borrow excludes its Drop, so the owner table cannot add information.573        Ok(())574    }575    pub fn ensure_nodes(&mut self, storage: &mut dyn Storage, nodes: u64) -> Result<()> {576        let blocks = nodes.div_ceil(NODES_PER_BLOCK);577        let blocks = usize::try_from(blocks).map_err(|_| Error::Capacity)?;578        if blocks <= self.blocks.len() {579            return self.validate(storage);580        }581        storage.grow_collection(self, blocks)582    }583    pub fn truncate_nodes(&mut self, storage: &mut dyn Storage, nodes: u64) -> Result<()> {584        self.validate(storage)?;585        let blocks =586            usize::try_from(nodes.div_ceil(NODES_PER_BLOCK)).map_err(|_| Error::Capacity)?;587        if blocks > self.blocks.len() {588            return Err(Error::Bounds);589        }590        for index in blocks..self.blocks.len() {591            self.authority.root.release(self.blocks[index]);592        }593        self.blocks.truncate(blocks);594        Ok(())595    }596    pub fn read_node<'a>(597        &self,598        storage: &dyn Storage,599        node: u64,600        workspace: &'a mut Workspace<'_>,601    ) -> Result<&'a [u8; NODE_BYTES]> {602        let block = self603            .blocks604            .get(usize::try_from(node / NODES_PER_BLOCK).map_err(|_| Error::Bounds)?)605            .ok_or(Error::Bounds)?;606        storage.read_collection(607            CollectionBlockRef {608                collection: self,609                offset: block.physical * BLOCK_BYTES,610            },611            node % NODES_PER_BLOCK * NODE_BYTES as u64,612            workspace.bytes_mut(),613        )?;614        Ok(workspace.bytes())615    }616    pub fn write_node(617        &self,618        storage: &mut dyn Storage,619        node: u64,620        bytes: &[u8; NODE_BYTES],621    ) -> Result<()> {622        let block = self623            .blocks624            .get(usize::try_from(node / NODES_PER_BLOCK).map_err(|_| Error::Bounds)?)625            .ok_or(Error::Bounds)?;626        storage.write_collection(627            CollectionBlockRef {628                collection: self,629                offset: block.physical * BLOCK_BYTES,630            },631            node % NODES_PER_BLOCK * NODE_BYTES as u64,632            bytes,633        )634    }635    fn check_range(&self, at: u64, len: usize) -> Result<()> {636        if at637            .checked_add(len as u64)638            .is_none_or(|end| end > self.blocks.len() as u64 * BLOCK_BYTES)639        {640            Err(Error::Bounds)641        } else {642            Ok(())643        }644    }645    pub fn read_at(&self, storage: &dyn Storage, at: u64, out: &mut [u8]) -> Result<()> {646        if out.is_empty() {647            self.check_range(at, 0)?;648            return self.validate(storage);649        }650        let offset = at % BLOCK_BYTES;651        if out.len() <= (BLOCK_BYTES - offset) as usize {652            let block = self653                .blocks654                .get(usize::try_from(at / BLOCK_BYTES).map_err(|_| Error::Bounds)?)655                .ok_or(Error::Bounds)?;656            // The complete nonempty request fits this admitted logical block.657            // Its directory bound proves the whole range without a second658            // length/checked-end calculation or the cross-block loop's state.659            return storage.read_collection(660                CollectionBlockRef {661                    collection: self,662                    offset: block.physical * BLOCK_BYTES,663                },664                offset,665                out,666            );667        }668        self.read_across_blocks(storage, at, out)669    }670    #[inline(never)]671    fn read_across_blocks(672        &self,673        storage: &dyn Storage,674        mut at: u64,675        mut out: &mut [u8],676    ) -> Result<()> {677        // Reject the entire request before the first partial read.678        self.check_range(at, out.len())?;679        while !out.is_empty() {680            let block = &self.blocks[(at / BLOCK_BYTES) as usize];681            let offset = at % BLOCK_BYTES;682            let len = out.len().min((BLOCK_BYTES - offset) as usize);683            storage.read_collection(684                CollectionBlockRef {685                    collection: self,686                    offset: block.physical * BLOCK_BYTES,687                },688                offset,689                &mut out[..len],690            )?;691            out = &mut out[len..];692            at += len as u64;693        }694        Ok(())695    }696    pub fn write_at(&self, storage: &mut dyn Storage, at: u64, bytes: &[u8]) -> Result<()> {697        if bytes.is_empty() {698            self.check_range(at, 0)?;699            return self.validate(storage);700        }701        let offset = at % BLOCK_BYTES;702        if bytes.len() <= (BLOCK_BYTES - offset) as usize {703            let block = self704                .blocks705                .get(usize::try_from(at / BLOCK_BYTES).map_err(|_| Error::Bounds)?)706                .ok_or(Error::Bounds)?;707            return storage.write_collection(708                CollectionBlockRef {709                    collection: self,710                    offset: block.physical * BLOCK_BYTES,711                },712                offset,713                bytes,714            );715        }716        self.write_across_blocks(storage, at, bytes)717    }718    #[inline(never)]719    fn write_across_blocks(720        &self,721        storage: &mut dyn Storage,722        mut at: u64,723        mut bytes: &[u8],724    ) -> Result<()> {725        // Reject the entire request before the first partial write.726        self.check_range(at, bytes.len())?;727        while !bytes.is_empty() {728            let block = &self.blocks[(at / BLOCK_BYTES) as usize];729            let offset = at % BLOCK_BYTES;730            let len = bytes.len().min((BLOCK_BYTES - offset) as usize);731            storage.write_collection(732                CollectionBlockRef {733                    collection: self,734                    offset: block.physical * BLOCK_BYTES,735                },736                offset,737                &bytes[..len],738            )?;739            bytes = &bytes[len..];740            at += len as u64;741        }742        Ok(())743    }744    pub fn retire(self, storage: &mut dyn Storage) -> Result<()> {745        self.validate(storage)?;746        drop(self);747        Ok(())748    }749}750impl Drop for Collection {751    fn drop(&mut self) {752        for index in 0..self.blocks.len() {753            self.authority.root.release(self.blocks[index]);754        }755        self.blocks.truncate(0);756        self.authority.root.retire_owner(self.authority.owner);757    }758}759760/// Transient shared byte capability. All byte loans are synchronous; the sole761/// backend is released when Arena and its HylixMemory wrappers are dropped.762struct Shared<M: Memory> {763    memory: RefCell<M>,764    root: Root,765    linear_leased: Cell<bool>,766    _lease: ProviderLease,767}768struct ProviderLease(Root);769impl Drop for ProviderLease {770    fn drop(&mut self) {771        self.0.inner.provider_live.set(false);772    }773}774pub struct Arena<M: Memory> {775    shared: Rc<Shared<M>>,776}777impl<M: Memory> Arena<M> {778    /// Format a fresh physical stable domain, reserving block zero for its779    /// isolated authority marker. Never call this on an already owned image.780    pub fn format(mut memory: M) -> Result<Self> {781        if memory.len() != 0 {782            return Err(Error::AlreadyExists);783        }784        let domain = NEXT_DOMAIN785            .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {786                next.checked_add(1)787            })788            .map_err(|_| Error::Overflow)?;789        let root = Root {790            inner: Rc::new_in(791                RootInner {792                    domain,793                    provider_live: Cell::new(true),794                    authority: RefCell::new(Authority {795                        slots: RetainedVec::new_in(Nyxus),796                        free: 0,797                        owners: RetainedVec::new_in(Nyxus),798                        free_owners: 0,799                        linear: RetainedVec::new_in(Nyxus),800                    }),801                },802                Nyxus,803            ),804        };805        memory806            .grow_to(BLOCK_BYTES)807            .unwrap_or_else(|error| memory.abort(error));808        let mut header = [0; HEADER_BYTES];809        header[..8].copy_from_slice(&FORMAT);810        header[8..].copy_from_slice(&domain.to_le_bytes());811        memory812            .write(0, &header)813            .unwrap_or_else(|error| memory.abort(error));814        Ok(Self {815            shared: Rc::new(Shared {816                memory: RefCell::new(memory),817                _lease: ProviderLease(root.clone()),818                root,819                linear_leased: Cell::new(false),820            }),821        })822    }823    /// Restore the exact rooted descriptor with one newly acquired physical824    /// provider. Header checks occur at startup, never before a node fetch.825    pub fn open(memory: M, root: Root) -> Result<Self> {826        if root.inner.provider_live.get() {827            return Err(Error::InvalidInput("Minima provider already live"));828        }829        let expected = (root.inner.authority.borrow().slots.len() as u64 + 1)830            .checked_mul(BLOCK_BYTES)831            .ok_or(Error::Capacity)?;832        if memory.len() != expected {833            return Err(Error::UnsupportedFormat);834        }835        let mut header = [0; HEADER_BYTES];836        memory.read(0, &mut header)?;837        if header[..8] != FORMAT || header[8..] != root.inner.domain.to_le_bytes() {838            return Err(Error::UnsupportedFormat);839        }840        NEXT_DOMAIN.fetch_max(841            root.inner.domain.checked_add(1).ok_or(Error::Overflow)?,842            Ordering::Relaxed,843        );844        root.inner.provider_live.set(true);845        Ok(Self {846            shared: Rc::new(Shared {847                memory: RefCell::new(memory),848                _lease: ProviderLease(root.clone()),849                root,850                linear_leased: Cell::new(false),851            }),852        })853    }854    pub fn root(&self) -> Root {855        self.shared.root.clone()856    }857    /// Supply this virtual contiguous Memory to Hylix instead of independently858    /// acquiring StableMemory. Its mapping lives in the same retained Root.859    pub fn hylix_memory(&self) -> HylixMemory<M> {860        assert!(861            !self.shared.linear_leased.replace(true),862            "Hylix virtual memory already leased"863        );864        HylixMemory {865            shared: self.shared.clone(),866        }867    }868    /// Inspect the sole physical provider synchronously, e.g. native counters.869    pub fn with_memory<T>(&self, visit: impl FnOnce(&M) -> T) -> T {870        visit(&self.shared.memory.borrow())871    }872    pub fn into_memory(self) -> Result<M> {873        let shared = Rc::try_unwrap(self.shared)874            .map_err(|_| Error::InvalidInput("live shared stable provider"))?;875        Ok(shared.memory.into_inner())876    }877}878impl<M: Memory> Shared<M> {879    fn clear(memory: &mut M, physical: u64) {880        // Reuse erases all previous collection bytes before admission, including881        // unused tails. Borrow a static node instead of allocating scratch.882        static ZERO: [u8; NODE_BYTES] = [0; NODE_BYTES];883        for node in 0..NODES_PER_BLOCK {884            memory885                .write(physical * BLOCK_BYTES + node * NODE_BYTES as u64, &ZERO)886                .unwrap_or_else(|error| memory.abort(error));887        }888    }889890    fn claim_into(&self, directory: &mut PageDirectory, blocks: usize) -> Result<()> {891        let count = blocks - directory.len();892        let mut authority = self.root.inner.authority.borrow_mut();893        let mut memory = self.memory.borrow_mut();894        let Authority { slots, free, .. } = &mut *authority;895        Self::claim_pages(slots, free, &mut *memory, directory, count)896    }897898    fn grow_linear(&self, pages: usize) -> Result<()> {899        let mut authority = self.root.inner.authority.borrow_mut();900        let count = pages.saturating_sub(authority.linear.len());901        if count == 0 {902            return Ok(());903        }904        let mut memory = self.memory.borrow_mut();905        let Authority {906            slots,907            free,908            linear,909            ..910        } = &mut *authority;911        Self::claim_pages(slots, free, &mut *memory, linear, count)912    }913914    fn claim_pages(915        slots: &mut RetainedVec<Slot>,916        free_head: &mut u64,917        memory: &mut M,918        destination: &mut impl PageSink,919        count: usize,920    ) -> Result<()> {921        // Examine only the free-list prefix this request will consume. Check922        // every changing generation before any byte or ownership mutation.923        let mut free = *free_head;924        let mut reused = 0;925        while free != 0 && reused < count {926            let slot = slots[(free - 1) as usize];927            slot.generation.checked_add(1).ok_or(Error::Overflow)?;928            free = slot.next_free;929            reused += 1;930        }931        let fresh = count - reused;932        let end = u64::try_from(slots.len())933            .ok()934            .and_then(|len| len.checked_add(fresh as u64))935            .and_then(|len| len.checked_add(1))936            .and_then(|len| len.checked_mul(BLOCK_BYTES))937            .ok_or(Error::Capacity)?;938        // Reserve both retained destinations after arithmetic preflight and939        // before physical mutation. No retained buffer grows in the loop.940        destination.reserve_pages(count);941        slots.reserve(fresh);942        if fresh != 0 {943            memory944                .grow_to(end)945                .unwrap_or_else(|error| memory.abort(error));946        }947        for _ in 0..count {948            let page = if *free_head != 0 {949                let physical = *free_head;950                let slot = &mut slots[(physical - 1) as usize];951                // Preflight checked this exact prefix under the same exclusive952                // authority loan. Nothing can change a later free generation.953                let generation = slot.generation + 1;954                let next_free = slot.next_free;955                *slot = Slot {956                    generation,957                    next_free: LIVE,958                };959                *free_head = next_free;960                Self::clear(memory, physical);961                Page {962                    physical,963                    generation,964                }965            } else {966                let physical = slots.len() as u64 + 1;967                slots.push(Slot {968                    generation: 1,969                    next_free: LIVE,970                });971                Page {972                    physical,973                    generation: 1,974                }975            };976            destination.push_page(page);977        }978        Ok(())979    }980981    fn claim(&self) -> Result<Page> {982        let mut authority = self.root.inner.authority.borrow_mut();983        let reused = authority.free != 0;984        let physical = if reused {985            authority.free986        } else {987            authority.slots.len() as u64 + 1988        };989        let generation = if reused {990            authority.slots[(physical - 1) as usize]991                .generation992                .checked_add(1)993                .ok_or(Error::Overflow)?994        } else {995            1996        };997        let mut memory = self.memory.borrow_mut();998        if !reused {999            let end = physical1000                .checked_add(1)1001                .and_then(|blocks| blocks.checked_mul(BLOCK_BYTES))1002                .ok_or(Error::Capacity)?;1003            memory1004                .grow_to(end)1005                .unwrap_or_else(|error| memory.abort(error));1006            authority.slots.push(Slot {1007                generation,1008                next_free: LIVE,1009            });1010        } else {1011            authority.free = authority.slots[(physical - 1) as usize].next_free;1012            authority.slots[(physical - 1) as usize] = Slot {1013                generation,1014                next_free: LIVE,1015            };1016            Self::clear(&mut *memory, physical);1017        }1018        Ok(Page {1019            physical,1020            generation,1021        })1022    }1023}1024impl<M: Memory> Storage for Arena<M> {1025    fn root(&self) -> Root {1026        self.root()1027    }1028    fn same_root(&self, root: &Root) -> bool {1029        self.shared.root.same(root)1030    }1031    fn allocate(&mut self, owner: CollectionId) -> Result<Block> {1032        self.validate(owner)?;1033        let page = self1034            .shared1035            .claim()1036            .unwrap_or_else(|error| self.shared.memory.borrow().abort(error));1037        Ok(Block {1038            authority: BlockAuthority {1039                root: self.root(),1040                owner,1041            },1042            page,1043        })1044    }1045    fn allocate_collection<'a>(1046        &mut self,1047        collection: &'a Collection,1048    ) -> Result<CollectionAllocation<'a>> {1049        collection.validate(self)?;1050        // A genuine Collection borrow proves that its owner cannot retire.1051        // claim still checks physical reuse generations under the sole Root.1052        let page = self1053            .shared1054            .claim()1055            .unwrap_or_else(|error| self.shared.memory.borrow().abort(error));1056        Ok(CollectionAllocation { collection, page })1057    }1058    fn grow_collection(&mut self, collection: &mut Collection, blocks: usize) -> Result<()> {1059        collection.validate(self)?;1060        if blocks <= collection.blocks.len() {1061            return Ok(());1062        }1063        self.shared1064            .claim_into(&mut collection.blocks, blocks)1065            .unwrap_or_else(|error| self.shared.memory.borrow().abort(error));1066        Ok(())1067    }1068    fn validate(&self, owner: CollectionId) -> Result<()> {1069        self.shared.root.validate(owner)1070    }1071    fn read(&self, block: BlockRef<'_>, at: u64, out: &mut [u8]) -> Result<()> {1072        self.shared.root.validate_block(block)?;1073        block_range(at, out.len())?;1074        self.shared.memory.borrow().read(block.offset() + at, out)1075    }1076    fn write(&mut self, block: BlockRef<'_>, at: u64, bytes: &[u8]) -> Result<()> {1077        self.shared.root.validate_block(block)?;1078        block_range(at, bytes.len())?;1079        let mut memory = self.shared.memory.borrow_mut();1080        memory1081            .write(block.offset() + at, bytes)1082            .unwrap_or_else(|error| memory.abort(error));1083        Ok(())1084    }1085    fn read_collection(1086        &self,1087        block: CollectionBlockRef<'_>,1088        at: u64,1089        out: &mut [u8],1090    ) -> Result<()> {1091        if !self.shared.root.same(&block.collection.authority.root) {1092            return Err(Error::InvalidInput("foreign Minima storage"));1093        }1094        block_range(at, out.len())?;1095        // The block base came from an admitted Page whose complete extent was1096        // checked during claim. The local range check proves this sum fits.1097        self.shared.memory.borrow().read(block.offset() + at, out)1098    }1099    fn write_collection(1100        &mut self,1101        block: CollectionBlockRef<'_>,1102        at: u64,1103        bytes: &[u8],1104    ) -> Result<()> {1105        if !self.shared.root.same(&block.collection.authority.root) {1106            return Err(Error::InvalidInput("foreign Minima storage"));1107        }1108        block_range(at, bytes.len())?;1109        let mut memory = self.shared.memory.borrow_mut();1110        memory1111            .write(block.offset() + at, bytes)1112            .unwrap_or_else(|error| memory.abort(error));1113        Ok(())1114    }1115}1116fn block_range(at: u64, len: usize) -> Result<()> {1117    if at1118        .checked_add(len as u64)1119        .is_none_or(|end| end > BLOCK_BYTES)1120    {1121        Err(Error::Bounds)1122    } else {1123        Ok(())1124    }1125}11261127/// Virtual contiguous byte image for Hylix, backed by disjoint blocks from the1128/// same physical authority. No changes to Hylix's allocator or caches are needed.1129/// Mapping metadata is retained and never shares a collection payload block.1130pub struct HylixMemory<M: Memory> {1131    shared: Rc<Shared<M>>,1132}1133impl<M: Memory> Drop for HylixMemory<M> {1134    fn drop(&mut self) {1135        self.shared.linear_leased.set(false);1136    }1137}1138// SAFETY: the single Shared<M> owns its Memory. The retained linear map assigns1139// whole private physical blocks only to this image; Minima allocation never1140// returns their live slots. RefCell excludes physical growth/write while read.1141unsafe impl<M: Memory> Memory for HylixMemory<M> {1142    fn abort(&self, error: Error) -> ! {1143        self.shared.memory.borrow().abort(error)1144    }1145    fn len(&self) -> u64 {1146        self.shared.root.inner.authority.borrow().linear.len() as u64 * BLOCK_BYTES1147    }1148    fn grow_to(&mut self, bytes: u64) -> Result<()> {1149        let pages = usize::try_from(bytes.div_ceil(BLOCK_BYTES)).map_err(|_| Error::Capacity)?;1150        self.shared1151            .grow_linear(pages)1152            .unwrap_or_else(|error| self.abort(error));1153        Ok(())1154    }1155    fn read(&self, mut at: u64, mut out: &mut [u8]) -> Result<()> {1156        if at1157            .checked_add(out.len() as u64)1158            .is_none_or(|end| end > self.len())1159        {1160            return Err(Error::Bounds);1161        }1162        let authority = self.shared.root.inner.authority.borrow();1163        let memory = self.shared.memory.borrow();1164        while !out.is_empty() {1165            let page = authority.linear[(at / BLOCK_BYTES) as usize];1166            let offset = at % BLOCK_BYTES;1167            let len = out.len().min((BLOCK_BYTES - offset) as usize);1168            memory.read(page.physical * BLOCK_BYTES + offset, &mut out[..len])?;1169            out = &mut out[len..];1170            at += len as u64;1171        }1172        Ok(())1173    }1174    fn write(&mut self, mut at: u64, mut bytes: &[u8]) -> Result<()> {1175        if at1176            .checked_add(bytes.len() as u64)1177            .is_none_or(|end| end > self.len())1178        {1179            return Err(Error::Bounds);1180        }1181        let authority = self.shared.root.inner.authority.borrow();1182        let mut memory = self.shared.memory.borrow_mut();1183        while !bytes.is_empty() {1184            let page = authority.linear[(at / BLOCK_BYTES) as usize];1185            let offset = at % BLOCK_BYTES;1186            let len = bytes.len().min((BLOCK_BYTES - offset) as usize);1187            memory1188                .write(page.physical * BLOCK_BYTES + offset, &bytes[..len])1189                .unwrap_or_else(|error| memory.abort(error));1190            bytes = &bytes[len..];1191            at += len as u64;1192        }1193        Ok(())1194    }1195}11961197#[cfg(test)]1198mod tests {1199    use super::*;1200    use cdk_rsx_platform::memory::VecMemory;12011202    #[test]1203    fn linear_no_growth_never_borrows_the_physical_provider() {1204        let arena = Arena::format(VecMemory::new()).unwrap();1205        let mut linear = arena.hylix_memory();1206        linear.grow_to(2 * BLOCK_BYTES).unwrap();1207        let _provider = arena.shared.memory.borrow_mut();1208        for bytes in [0, 1, BLOCK_BYTES, 2 * BLOCK_BYTES] {1209            linear.grow_to(bytes).unwrap();1210        }1211        assert_eq!(linear.len(), 2 * BLOCK_BYTES);1212    }12131214    #[test]1215    fn no_growth_validates_root_without_dispatching_provider_growth() {1216        struct Observed<'a> {1217            arena: &'a mut Arena<VecMemory>,1218            growths: usize,1219        }1220        impl Storage for Observed<'_> {1221            fn root(&self) -> Root {1222                self.arena.root()1223            }1224            fn same_root(&self, root: &Root) -> bool {1225                self.arena.same_root(root)1226            }1227            fn allocate(&mut self, owner: CollectionId) -> Result<Block> {1228                self.arena.allocate(owner)1229            }1230            fn grow_collection(1231                &mut self,1232                collection: &mut Collection,1233                blocks: usize,1234            ) -> Result<()> {1235                self.growths += 1;1236                self.arena.grow_collection(collection, blocks)1237            }1238            fn validate(&self, owner: CollectionId) -> Result<()> {1239                self.arena.validate(owner)1240            }1241            fn read(&self, block: BlockRef<'_>, at: u64, out: &mut [u8]) -> Result<()> {1242                self.arena.read(block, at, out)1243            }1244            fn write(&mut self, block: BlockRef<'_>, at: u64, bytes: &[u8]) -> Result<()> {1245                self.arena.write(block, at, bytes)1246            }1247            fn read_collection(1248                &self,1249                block: CollectionBlockRef<'_>,1250                at: u64,1251                out: &mut [u8],1252            ) -> Result<()> {1253                self.arena.read_collection(block, at, out)1254            }1255            fn write_collection(1256                &mut self,1257                block: CollectionBlockRef<'_>,1258                at: u64,1259                bytes: &[u8],1260            ) -> Result<()> {1261                self.arena.write_collection(block, at, bytes)1262            }1263        }1264        let mut arena = Arena::format(VecMemory::new()).unwrap();1265        let mut collection = Collection::new(&mut arena).unwrap();1266        let mut observed = Observed {1267            arena: &mut arena,1268            growths: 0,1269        };1270        collection.ensure_nodes(&mut observed, 0).unwrap();1271        assert_eq!(observed.growths, 0);1272        collection.ensure_nodes(&mut observed, 1).unwrap();1273        assert_eq!(observed.growths, 1);1274        for nodes in [0, 1, NODES_PER_BLOCK] {1275            collection.ensure_nodes(&mut observed, nodes).unwrap();1276        }1277        assert_eq!(observed.growths, 1);1278        collection1279            .ensure_nodes(&mut observed, NODES_PER_BLOCK + 1)1280            .unwrap();1281        assert_eq!(observed.growths, 2);1282        assert_eq!(collection.block_count(), 2);1283        let mut foreign = Arena::format(VecMemory::new()).unwrap();1284        let mut observed = Observed {1285            arena: &mut foreign,1286            growths: 0,1287        };1288        for nodes in [0, 1, 2 * NODES_PER_BLOCK] {1289            assert_eq!(1290                collection.ensure_nodes(&mut observed, nodes),1291                Err(Error::InvalidInput("foreign Minima storage"))1292            );1293        }1294        assert_eq!(observed.growths, 0);1295        let mut empty = Collection::new(&mut arena).unwrap();1296        assert_eq!(1297            empty.ensure_nodes(&mut observed, 0),1298            Err(Error::InvalidInput("foreign Minima storage"))1299        );1300        assert_eq!(observed.growths, 0);1301    }13021303    #[test]1304    fn borrowed_allocation_preserves_root_counts_and_returns_abandoned_pages() {1305        let mut arena = Arena::format(VecMemory::new()).unwrap();1306        let root = arena.root();1307        let mut collection = Collection::new(&mut arena).unwrap();1308        let other = Collection::new(&mut arena).unwrap();1309        let references = Rc::strong_count(&root.inner);1310        let allocation = arena.allocate_collection(&collection).unwrap();1311        assert_eq!(Rc::strong_count(&root.inner), references);1312        assert_eq!(root.allocated_blocks(), 1);1313        drop(allocation);1314        assert_eq!(root.allocated_blocks(), 0);1315        let allocation = arena.allocate_collection(&collection).unwrap();1316        assert!(matches!(1317            allocation.into_page(&other),1318            Err(Error::InvalidInput("foreign Minima allocation"))1319        ));1320        assert_eq!(root.allocated_blocks(), 0);1321        collection1322            .ensure_nodes(&mut arena, 37 * NODES_PER_BLOCK)1323            .unwrap();1324        assert_eq!(Rc::strong_count(&root.inner), references);1325        assert_eq!(root.allocated_blocks(), 37);1326        drop(collection);1327        assert_eq!(root.allocated_blocks(), 0);1328        assert_eq!(Rc::strong_count(&root.inner), references - 1);1329    }13301331    #[test]1332    fn dense_directory_keeps_one_root_reference_and_releases_every_owned_page() {1333        assert_eq!(core::mem::size_of::<Page>(), 16);1334        assert_eq!(core::mem::size_of::<BlockAuthority>(), 32);1335        assert_eq!(core::mem::size_of::<BlockRef<'_>>(), 16);1336        assert_eq!(core::mem::size_of::<CollectionBlockRef<'_>>(), 16);1337        assert_eq!(core::mem::size_of::<Block>(), 48);1338        assert_eq!(core::mem::size_of::<Collection>(), 320);1339        let mut arena = Arena::format(VecMemory::new()).unwrap();1340        let root = arena.root();1341        let mut collection = Collection::new(&mut arena).unwrap();1342        let references = Rc::strong_count(&root.inner);1343        collection1344            .ensure_nodes(&mut arena, 37 * NODES_PER_BLOCK)1345            .unwrap();1346        assert_eq!(root.allocated_blocks(), 37);1347        assert_eq!(collection.blocks.rest.len(), 21);1348        assert_eq!(collection.blocks.rest.capacity(), 21);1349        assert_eq!(Rc::strong_count(&root.inner), references);1350        let raw = arena.allocate(collection.identity()).unwrap();1351        assert_eq!(Rc::strong_count(&root.inner), references + 1);1352        let borrowed = raw.borrow();1353        assert_eq!(borrowed.offset(), raw.offset());1354        assert_eq!(borrowed.generation(), raw.generation());1355        assert_eq!(Rc::strong_count(&root.inner), references + 1);1356        drop(raw);1357        collection1358            .truncate_nodes(&mut arena, 13 * NODES_PER_BLOCK)1359            .unwrap();1360        assert_eq!(root.allocated_blocks(), 13);1361        drop(collection);1362        assert_eq!(root.allocated_blocks(), 0);1363        assert_eq!(Rc::strong_count(&root.inner), references - 1);1364    }13651366    #[test]1367    fn collection_borrow_needs_no_authority_lookup_but_raw_block_still_does() {1368        let mut arena = Arena::format(VecMemory::new()).unwrap();1369        let root = arena.root();1370        let mut collection = Collection::new(&mut arena).unwrap();1371        collection.ensure_nodes(&mut arena, 17).unwrap();1372        let raw = arena.allocate(collection.identity()).unwrap();1373        let references = Rc::strong_count(&root.inner);13741375        // A held private metadata borrow detects even an attempted owner-table1376        // lookup. Public code cannot take this guard or retire the Collection1377        // behind its live borrow. Byte writes do not revoke page ownership.1378        let metadata = root.inner.authority.borrow_mut();1379        collection.validate(&arena).unwrap();1380        collection1381            .write_at(&mut arena, BLOCK_BYTES - 2, &[1, 2, 3, 4])1382            .unwrap();1383        let mut bytes = [0; 4];1384        collection1385            .read_at(&arena, BLOCK_BYTES - 2, &mut bytes)1386            .unwrap();1387        assert_eq!(bytes, [1, 2, 3, 4]);1388        collection.read_at(&arena, 0, &mut []).unwrap();1389        collection.write_at(&mut arena, 0, &[]).unwrap();1390        assert_eq!(Rc::strong_count(&root.inner), references);13911392        let raw_lookup = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {1393            arena.read(raw.borrow(), 0, &mut [0])1394        }));1395        assert!(raw_lookup.is_err());1396        let external_id_lookup = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {1397            arena.validate(collection.identity())1398        }));1399        assert!(external_id_lookup.is_err());1400        drop(metadata);1401        arena.read(raw.borrow(), 0, &mut [0]).unwrap();1402        drop(raw);1403        drop(collection);1404        assert_eq!(root.allocated_blocks(), 0);1405    }14061407    #[test]1408    fn collection_capability_provider_rechecks_root_and_local_block_bounds() {1409        let mut arena = Arena::format(VecMemory::new()).unwrap();1410        let mut collection = Collection::new(&mut arena).unwrap();1411        collection.ensure_nodes(&mut arena, 1).unwrap();1412        // Test-only access to private fields exercises a genuine capability at1413        // the provider boundary, including wrappers that supply a bad local at.1414        let block = CollectionBlockRef {1415            collection: &collection,1416            offset: collection.blocks[0].physical * BLOCK_BYTES,1417        };1418        for at in [BLOCK_BYTES, u64::MAX] {1419            assert_eq!(1420                arena.read_collection(block, at, &mut [0]),1421                Err(Error::Bounds)1422            );1423            assert_eq!(arena.write_collection(block, at, &[0]), Err(Error::Bounds));1424        }1425        arena.read_collection(block, BLOCK_BYTES, &mut []).unwrap();1426        arena.write_collection(block, BLOCK_BYTES, &[]).unwrap();1427        let mut foreign = Arena::format(VecMemory::new()).unwrap();1428        assert_eq!(1429            foreign.read_collection(block, 0, &mut [0]),1430            Err(Error::InvalidInput("foreign Minima storage"))1431        );1432        assert_eq!(1433            foreign.write_collection(block, 0, &[0]),1434            Err(Error::InvalidInput("foreign Minima storage"))1435        );1436    }14371438    #[test]1439    fn inline_directory_crosses_capacities_moves_and_reuses_only_released_pages() {1440        let mut arena = Arena::format(VecMemory::new()).unwrap();1441        let root = arena.root();1442        let mut collection = Collection::new(&mut arena).unwrap();1443        for blocks in [0, 1, 13, 16, 17, 20, 21, 32, 33, 37] {1444            collection1445                .ensure_nodes(&mut arena, blocks * NODES_PER_BLOCK)1446                .unwrap();1447            assert_eq!(collection.block_count(), blocks as usize);1448            assert_eq!(1449                collection.blocks.rest.len(),1450                (blocks as usize).saturating_sub(INLINE_PAGES)1451            );1452            assert!(collection.blocks.get(blocks as usize).is_none());1453        }1454        let old: std::collections::BTreeMap<_, _> = (0..37)1455            .map(|i| {1456                let page = collection.blocks[i];1457                (page.physical, page.generation)1458            })1459            .collect();1460        for index in 0..37u64 {1461            collection1462                .write_at(&mut arena, index * BLOCK_BYTES + 19, &[index as u8 + 1])1463                .unwrap();1464        }1465        let mut collection = std::boxed::Box::new(collection);1466        let start = &*collection as *const Collection as usize;1467        let end = start + core::mem::size_of::<Collection>();1468        for index in 0..37 {1469            let at = collection.blocks.get(index).unwrap() as *const Page as usize;1470            assert_eq!((start..end).contains(&at), index < INLINE_PAGES);1471        }1472        for remaining in [33usize, 20, 17, 16, 13, 1, 0] {1473            collection1474                .truncate_nodes(&mut arena, remaining as u64 * NODES_PER_BLOCK)1475                .unwrap();1476            assert_eq!(root.allocated_blocks(), remaining as u64);1477            assert_eq!(1478                collection.blocks.rest.len(),1479                remaining.saturating_sub(INLINE_PAGES)1480            );1481            assert!(1482                collection.blocks.inline[remaining.min(INLINE_PAGES)..]1483                    .iter()1484                    .all(|p| p.physical == 0 && p.generation == 0)1485            );1486        }1487        collection1488            .ensure_nodes(&mut arena, 37 * NODES_PER_BLOCK)1489            .unwrap();1490        for index in 0..37 {1491            let page = collection.blocks[index];1492            assert_eq!(page.generation, old[&page.physical] + 1);1493            let mut byte = [255];1494            collection1495                .read_at(&arena, index as u64 * BLOCK_BYTES + 19, &mut byte)1496                .unwrap();1497            assert_eq!(byte, [0]);1498        }1499        drop(collection);1500        assert_eq!(root.allocated_blocks(), 0);1501    }15021503    #[test]1504    fn allocation_from_another_owner_is_released_without_directory_admission() {1505        struct Misdirected<'a> {1506            arena: &'a mut Arena<VecMemory>,1507            other: CollectionId,1508        }1509        impl Storage for Misdirected<'_> {1510            fn root(&self) -> Root {1511                self.arena.root()1512            }1513            fn same_root(&self, root: &Root) -> bool {1514                self.arena.same_root(root)1515            }1516            fn validate(&self, owner: CollectionId) -> Result<()> {1517                self.arena.validate(owner)1518            }1519            fn allocate(&mut self, _: CollectionId) -> Result<Block> {1520                self.arena.allocate(self.other)1521            }1522            fn read(&self, _: BlockRef<'_>, _: u64, _: &mut [u8]) -> Result<()> {1523                panic!("no payload access")1524            }1525            fn write(&mut self, _: BlockRef<'_>, _: u64, _: &[u8]) -> Result<()> {1526                panic!("no payload access")1527            }1528            fn read_collection(1529                &self,1530                _: CollectionBlockRef<'_>,1531                _: u64,1532                _: &mut [u8],1533            ) -> Result<()> {1534                panic!("no payload access")1535            }1536            fn write_collection(1537                &mut self,1538                _: CollectionBlockRef<'_>,1539                _: u64,1540                _: &[u8],1541            ) -> Result<()> {1542                panic!("no payload access")1543            }1544        }1545        let mut arena = Arena::format(VecMemory::new()).unwrap();1546        let root = arena.root();1547        let mut collection = Collection::new(&mut arena).unwrap();1548        let other = Collection::new(&mut arena).unwrap();1549        assert_eq!(1550            collection.ensure_nodes(1551                &mut Misdirected {1552                    arena: &mut arena,1553                    other: other.identity()1554                },1555                11556            ),1557            Err(Error::InvalidInput("foreign Minima allocation"))1558        );1559        assert_eq!(collection.block_count(), 0);1560        assert_eq!(root.allocated_blocks(), 0);1561        collection.ensure_nodes(&mut arena, 1).unwrap();1562        assert_eq!(root.allocated_blocks(), 1);1563        drop(collection);1564        assert_eq!(root.allocated_blocks(), 0);1565    }15661567    #[test]1568    fn owner_validation_checks_the_complete_identity() {1569        let arena = Arena::format(VecMemory::new()).unwrap();1570        let root = arena.root();1571        let id = root.owner().unwrap();1572        assert_eq!(root.validate(id), Ok(()));1573        for owner in [id.owner + (1u64 << 32), u64::MAX] {1574            assert_eq!(1575                root.validate(CollectionId { owner, ..id }),1576                Err(Error::InvalidInput("retired Minima owner"))1577            );1578            assert_eq!(1579                root.validate(CollectionId {1580                    domain: id.domain + 1,1581                    owner,1582                    ..id1583                }),1584                Err(Error::InvalidInput("foreign Minima owner"))1585            );1586        }1587        root.retire_owner(id);1588        assert_eq!(1589            root.validate(id),1590            Err(Error::InvalidInput("retired Minima owner"))1591        );1592    }15931594    #[test]1595    fn exhausted_owner_generation_is_never_reused() {1596        let arena = Arena::format(VecMemory::new()).unwrap();1597        let root = arena.root();1598        let mut id = root.owner().unwrap();1599        // Model the last two incarnations without iterating u64::MAX times.1600        id.generation = u64::MAX - 1;1601        root.inner.authority.borrow_mut().owners[id.owner as usize].generation = id.generation;1602        root.retire_owner(id);1603        let last = root.owner().unwrap();1604        assert_eq!(last.owner, id.owner);1605        assert_eq!(last.generation, u64::MAX);1606        assert!(root.validate(id).is_err());1607        root.retire_owner(last);1608        let next = root.owner().unwrap();1609        assert_ne!(next.owner, last.owner);1610        assert!(root.validate(last).is_err());1611        root.retire_owner(next);1612    }16131614    #[test]1615    fn exhausted_physical_generation_is_never_reused() {1616        let mut arena = Arena::format(VecMemory::new()).unwrap();1617        let root = arena.root();1618        let owner = root.owner().unwrap();1619        let mut block = arena.allocate(owner).unwrap();1620        let physical = block.page.physical;1621        block.page.generation = u64::MAX - 1;1622        root.inner.authority.borrow_mut().slots[physical as usize - 1].generation =1623            block.page.generation;1624        drop(block);1625        let last = arena.allocate(owner).unwrap();1626        assert_eq!(last.page.physical, physical);1627        assert_eq!(last.generation(), u64::MAX);1628        drop(last);1629        let next = arena.allocate(owner).unwrap();1630        assert_ne!(next.page.physical, physical);1631        drop(next);1632        assert_eq!(root.allocated_blocks(), 0);1633        root.retire_owner(owner);1634    }16351636    #[test]1637    fn bulk_acquisition_never_wraps_an_exhausted_physical_generation() {1638        let mut arena = Arena::format(VecMemory::new()).unwrap();1639        let root = arena.root();1640        let mut collection = Collection::new(&mut arena).unwrap();1641        collection.ensure_nodes(&mut arena, 1).unwrap();1642        let physical = collection.blocks[0].physical;1643        collection.blocks.inline[0].generation = u64::MAX - 1;1644        root.inner.authority.borrow_mut().slots[physical as usize - 1].generation = u64::MAX - 1;1645        collection.truncate_nodes(&mut arena, 0).unwrap();1646        collection.ensure_nodes(&mut arena, 1).unwrap();1647        assert_eq!(collection.blocks[0].physical, physical);1648        assert_eq!(collection.blocks[0].generation, u64::MAX);1649        collection.truncate_nodes(&mut arena, 0).unwrap();1650        collection.ensure_nodes(&mut arena, 1).unwrap();1651        assert_ne!(collection.blocks[0].physical, physical);1652        assert_eq!(collection.blocks[0].generation, 1);1653        drop(collection);1654        assert_eq!(root.allocated_blocks(), 0);1655    }16561657    #[test]1658    fn linear_bulk_growth_preserves_reuse_generations_and_excludes_exhausted_slots() {1659        let mut arena = Arena::format(VecMemory::new()).unwrap();1660        let root = arena.root();1661        let owner = root.owner().unwrap();1662        let mut exhausted = arena.allocate(owner).unwrap();1663        exhausted.page.generation = u64::MAX;1664        root.inner.authority.borrow_mut().slots[0].generation = u64::MAX;1665        drop(exhausted); // physical 1 cannot enter the free list1666        let mut last_reuse = arena.allocate(owner).unwrap();1667        last_reuse.page.generation = u64::MAX - 1;1668        root.inner.authority.borrow_mut().slots[1].generation = u64::MAX - 1;1669        drop(last_reuse); // physical 2 has one valid reuse left1670        let mut linear = arena.hylix_memory();1671        linear.grow_to(2 * BLOCK_BYTES).unwrap();1672        {1673            let authority = root.inner.authority.borrow();1674            assert_eq!(authority.linear[0].physical, 2);1675            assert_eq!(authority.linear[0].generation, u64::MAX);1676            assert_eq!(authority.linear[1].physical, 3);1677            assert_eq!(authority.linear[1].generation, 1);1678            assert_eq!(authority.slots[0].generation, u64::MAX);1679            assert_ne!(authority.slots[0].next_free, LIVE);1680        }1681        let unrelated = arena.allocate(owner).unwrap();1682        assert_eq!(unrelated.page.physical, 4);1683        assert_eq!(root.allocated_blocks(), 3);1684        drop(unrelated);1685        root.retire_owner(owner);1686    }1687}