shared.rs
cdk-rsx/crates/cdk-rsx-collections/src/hylix/shared.rs
1use super::{Edit, Read, must, read_value};2use cdk_rsx_engine_hylix::{3 Block, Codec, ContextLoan, Error, HylixValue, Result, Storage, with_storage, with_storage_read,4};5use core::marker::PhantomData;6use std::cell::RefCell;78#[derive(Clone, Copy)]9struct LoanEntry {10 block: Block,11 readers: usize,12 writer: bool,13}14impl LoanEntry {15 const EMPTY: Self = Self {16 block: Block::NULL,17 readers: 0,18 writer: false,19 };20 fn acquire(&mut self, write: bool) -> Result<()> {21 if self.writer || (write && self.readers != 0) {22 return Err(Error::InvalidInput("stable cell already borrowed"));23 }24 if write {25 self.writer = true;26 } else {27 self.readers = self.readers.checked_add(1).ok_or(Error::Overflow)?;28 }29 Ok(())30 }31 fn release(&mut self, write: bool) -> bool {32 if write {33 self.writer = false;34 } else {35 self.readers -= 1;36 }37 self.readers == 0 && !self.writer38 }39}40const INLINE_LOANS: usize = 4;41struct Loans {42 context: u64,43 // Only this prefix represents live distinct Cells. Unused slots carry no44 // authority, require no allocation and are overwritten before reuse.45 inline: [LoanEntry; INLINE_LOANS],46 len: usize,47 overflow: std::vec::Vec<LoanEntry>,48}49impl Loans {50 const fn new() -> Self {51 Self {52 context: 0,53 inline: [LoanEntry::EMPTY; INLINE_LOANS],54 len: 0,55 overflow: std::vec::Vec::new(),56 }57 }58 fn reset(&mut self, context: u64) {59 self.len = 0;60 self.overflow = std::vec::Vec::new();61 self.context = context;62 }63 fn acquire(&mut self, block: Block, write: bool) -> Result<()> {64 let entry = if let Some(index) = self.inline[..self.len]65 .iter()66 .position(|entry| entry.block == block)67 {68 &mut self.inline[index]69 } else if let Some(index) = self.overflow.iter().position(|entry| entry.block == block) {70 &mut self.overflow[index]71 } else if self.len < INLINE_LOANS {72 let index = self.len;73 self.len += 1;74 self.inline[index] = LoanEntry {75 block,76 ..LoanEntry::EMPTY77 };78 &mut self.inline[index]79 } else {80 self.overflow.push(LoanEntry {81 block,82 ..LoanEntry::EMPTY83 });84 self.overflow.last_mut().expect("new overflow loan")85 };86 entry.acquire(write)87 }88 fn release(&mut self, block: Block, write: bool) {89 if let Some(index) = self.inline[..self.len]90 .iter()91 .position(|entry| entry.block == block)92 {93 if self.inline[index].release(write) {94 self.len -= 1;95 self.inline[index] = self.inline[self.len];96 }97 } else {98 let index = self99 .overflow100 .iter()101 .position(|entry| entry.block == block)102 .expect("live stable cell loan");103 if self.overflow[index].release(write) {104 self.overflow.swap_remove(index);105 if self.overflow.is_empty() {106 // KEEP requires every Global allocation drained, even if107 // an inline guard remains live. Empty overflow owns none.108 self.overflow = std::vec::Vec::new();109 }110 }111 }112 }113}114115thread_local! {116 // Only live Cell guards are represented. No durable entry index/cache is117 // retained, and the last loan immediately removes its temporary record.118 static CELL_LOANS: RefCell<Loans> = const { RefCell::new(Loans::new()) };119}120pub(super) struct CellLoan {121 block: Block,122 write: bool,123 scope: ContextLoan,124}125impl CellLoan {126 pub(super) fn acquire(block: Block, write: bool) -> Result<Self> {127 let scope = ContextLoan::new()?;128 let context = scope.context_id();129 CELL_LOANS.with(|loans| {130 let mut loans = loans.borrow_mut();131 if loans.context != context {132 // A context with a live guard traps and is invalidated by the133 // foundation before another epoch can start. This drops only134 // quarantined bookkeeping, never a live valid borrow.135 loans.reset(context);136 }137 loans.acquire(block, write)138 })?;139 Ok(Self {140 block,141 write,142 scope,143 })144 }145 pub(super) fn check(&self) -> Result<()> {146 self.scope.check()147 }148}149impl Drop for CellLoan {150 fn drop(&mut self) {151 CELL_LOANS.with(|loans| {152 let mut loans = loans.borrow_mut();153 if loans.context != self.scope.context_id() {154 return;155 }156 loans.release(self.block, self.write);157 });158 }159}160161/// A unique stable record. Unlike a Rust RefCell its payload is decoded on each162/// borrow; its guards contain ordinary transient values and never raw pointers.163pub struct Cell<T: HylixValue> {164 block: Block,165 marker: PhantomData<fn() -> T>,166}167impl<T: HylixValue> Cell<T> {168 pub fn new(value: T) -> Self {169 let block = must(with_storage(|storage| {170 let block = storage.allocate(T::SIZE.max(1) as u64)?;171 let mut bytes = std::vec![0; T::SIZE.max(1)];172 value.encode(&mut bytes[..T::SIZE]);173 storage.write(block, 0, &bytes)?;174 Ok(block)175 }));176 Self {177 block,178 marker: PhantomData,179 }180 }181 pub fn read(&self) -> Read<'_, T> {182 must(self.try_read())183 }184 pub fn try_read(&self) -> Result<Read<'_, T>> {185 let loan = CellLoan::acquire(self.block, false)?;186 let value =187 with_storage_read(|storage| cdk_rsx_engine_hylix::read_value(storage, self.block, 0))?;188 Ok(Read::with_loan(value, loan))189 }190 pub fn edit(&self) -> Edit<'_, T> {191 must(self.try_edit())192 }193 pub fn try_edit(&self) -> Result<Edit<'_, T>> {194 with_storage(|_| Ok(()))?;195 let loan = CellLoan::acquire(self.block, true)?;196 let value =197 with_storage_read(|storage| cdk_rsx_engine_hylix::read_value(storage, self.block, 0))?;198 Ok(Edit::with_loan(value, self.block, 0, loan))199 }200 pub fn into_inner(self) -> T {201 let _loan = must(CellLoan::acquire(self.block, true));202 let value = read_value(self.block, 0);203 must(with_storage(|storage| storage.deallocate(self.block)));204 value205 }206}207impl<T: HylixValue> Codec for Cell<T> {208 const __CODEC_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("mod.rs", "shared.rs");209 const SIZE: usize = Block::SIZE;210 fn encode(&self, out: &mut [u8]) {211 self.block.encode(out);212 }213 fn decode(bytes: &[u8]) -> Result<Self> {214 let block = Block::decode(bytes)?;215 if block.is_null() {216 return Err(Error::Corrupt("stable cell"));217 }218 Ok(Self {219 block,220 marker: PhantomData,221 })222 }223}224// SAFETY: the unique cell has one fixed initialized payload and one allocation.225unsafe impl<T: HylixValue> HylixValue for Cell<T> {226 fn retire(self, storage: &mut dyn Storage) -> Result<()> {227 let _loan = CellLoan::acquire(self.block, true)?;228 cdk_rsx_engine_hylix::read_value::<T>(storage, self.block, 0)?.retire(storage)?;229 storage.deallocate(self.block)230 }231}232233#[cfg(test)]234mod shared_cell_loan_tests {235 use super::*;236 use crate::hylix::SharedCell;237 use cdk_rsx_engine_hylix::{Arena, using};238 use cdk_rsx_platform::memory::VecMemory;239240 #[test]241 fn mixed_cell_guards_release_global_loan_backing_before_idle() {242 let mut arena = Arena::format(VecMemory::new(), [0x6c; 32]).unwrap();243 using(&mut arena, || {244 let unique = Cell::new(1u64);245 let shared = SharedCell::new(2u64);246 let unique_read = unique.read();247 let shared_read = shared.read();248 CELL_LOANS.with(|loans| {249 let loans = loans.borrow();250 assert_eq!(loans.len + loans.overflow.len(), 2);251 assert_eq!(loans.overflow.capacity(), 0);252 });253 drop(unique_read);254 drop(shared_read);255 cdk_rsx_engine_hylix::check_no_loans()?;256 CELL_LOANS.with(|loans| {257 let loans = loans.borrow();258 assert_eq!(loans.len, 0);259 assert!(loans.overflow.is_empty());260 assert_eq!(261 loans.overflow.capacity(),262 0,263 "KEEP must not retain Global loan backing"264 );265 });266 crate::hylix::retire(unique);267 crate::hylix::retire(shared);268 Ok(())269 })270 .unwrap();271 }272}273274/// An immutable shared stable value. Only `share` creates another persistable275/// owner; a clonable `snapshot` cannot be inserted into a stable collection.276/// ```compile_fail277/// use cdk_rsx_collections::hylix::{Map, Shared};278/// let owner = Shared::new(1u64);279/// let mut map = Map::<u64, Shared<u64>>::new();280/// map.insert(0, owner.snapshot().clone());281/// ```282pub struct Shared<T: HylixValue> {283 block: Block,284 marker: PhantomData<fn() -> T>,285}286/// A borrowed inert shared view. It deliberately implements neither Codec nor287/// HylixValue and cannot masquerade as a second persistent owning edge.288pub struct SharedSnapshot<'a, T: HylixValue> {289 owner: &'a Shared<T>,290}291impl<T: HylixValue> Clone for SharedSnapshot<'_, T> {292 fn clone(&self) -> Self {293 Self { owner: self.owner }294 }295}296impl<T: HylixValue> SharedSnapshot<'_, T> {297 pub fn read(&self) -> Read<'_, T> {298 self.owner.read()299 }300 pub fn share(&self) -> Shared<T> {301 self.owner.share()302 }303 pub fn strong_count(&self) -> u64 {304 self.owner.strong_count()305 }306}307impl<T: HylixValue> Shared<T> {308 pub fn new(value: T) -> Self {309 let block = must(with_storage(|storage| {310 let block = storage.allocate((8 + T::SIZE) as u64)?;311 let mut bytes = std::vec![0; 8 + T::SIZE];312 1u64.encode(&mut bytes[..8]);313 value.encode(&mut bytes[8..]);314 storage.write(block, 0, &bytes)?;315 Ok(block)316 }));317 Self {318 block,319 marker: PhantomData,320 }321 }322 pub fn read(&self) -> Read<'_, T> {323 Read::new(read_value(self.block, 8))324 }325 pub fn snapshot(&self) -> SharedSnapshot<'_, T> {326 SharedSnapshot { owner: self }327 }328 pub fn share(&self) -> Self {329 must(with_storage(|storage| self.retain(storage)));330 Self {331 block: self.block,332 marker: PhantomData,333 }334 }335 pub fn ptr_eq(left: &Self, right: &Self) -> bool {336 left.block == right.block337 }338 pub fn strong_count(&self) -> u64 {339 read_value(self.block, 0)340 }341 fn change_count(&self, storage: &mut dyn Storage, increment: bool) -> Result<u64> {342 let count: u64 = cdk_rsx_engine_hylix::read_value(storage, self.block, 0)?;343 let updated = if increment {344 count.checked_add(1).ok_or(Error::Overflow)?345 } else {346 count347 .checked_sub(1)348 .ok_or(Error::Corrupt("stable shared count"))?349 };350 cdk_rsx_engine_hylix::write_value(storage, self.block, 0, &updated)?;351 Ok(updated)352 }353}354impl<T: HylixValue> Codec for Shared<T> {355 const __CODEC_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("mod.rs", "shared.rs");356 const SIZE: usize = Block::SIZE;357 fn encode(&self, out: &mut [u8]) {358 self.block.encode(out);359 }360 fn decode(bytes: &[u8]) -> Result<Self> {361 let block = Block::decode(bytes)?;362 if block.is_null() {363 return Err(Error::Corrupt("stable shared"));364 }365 Ok(Self {366 block,367 marker: PhantomData,368 })369 }370}371// SAFETY: explicit share adds a durable reference, and exactly the final retire372// reclaims the initialized payload. Snapshots never call either hook implicitly.373unsafe impl<T: HylixValue> HylixValue for Shared<T> {374 fn retain(&self, storage: &mut dyn Storage) -> Result<()> {375 self.change_count(storage, true).map(|_| ())376 }377 fn retire(self, storage: &mut dyn Storage) -> Result<()> {378 if self.change_count(storage, false)? == 0 {379 cdk_rsx_engine_hylix::read_value::<T>(storage, self.block, 8)?.retire(storage)?;380 storage.deallocate(self.block)?;381 }382 Ok(())383 }384}385386/// An immutable stable byte allocation. The length is carried with its offset,387/// so loading bytes makes one initialized read with no header/payload reread.388pub struct Blob {389 block: Block,390 len: u64,391}392impl Blob {393 pub const fn new() -> Self {394 Self {395 block: Block::NULL,396 len: 0,397 }398 }399 pub fn from_slice(bytes: &[u8]) -> Self {400 if bytes.is_empty() {401 return Self::new();402 }403 let block = must(with_storage(|storage| {404 let block = storage.allocate(bytes.len() as u64)?;405 storage.write(block, 0, bytes)?;406 Ok(block)407 }));408 Self {409 block,410 len: bytes.len() as u64,411 }412 }413 /// Construct a complete immutable blob using reusable bounded scratch.414 ///415 /// `fill` initializes the requested chunk at its blob-relative byte offset.416 /// It runs without an active provider borrow; each subsequent write takes417 /// its own short borrow. No complete transient payload is assembled here.418 /// The blob is published only after every byte has been written. Its stable419 /// carrier and stored bytes match [`Self::from_slice`].420 ///421 /// Validate normal business rejection before calling this constructor.422 ///423 /// # Panics424 /// Panics if nonempty input has empty scratch, the write frame is unavailable,425 /// allocation/write fails, or `fill` returns an error. Failure after allocation426 /// aborts the execution; native hosts must restore their complete snapshot427 /// before reuse. Returned errors are not a local rollback mechanism.428 pub fn from_reader(429 len: usize,430 scratch: &mut [u8],431 mut fill: impl FnMut(usize, &mut [u8]) -> Result<()>,432 ) -> Self {433 if len == 0 {434 return Self::new();435 }436 assert!(!scratch.is_empty(), "nonempty stable blob requires scratch");437 let block = must(with_storage(|storage| storage.allocate(len as u64)));438 let mut at = 0;439 while at < len {440 let count = (len - at).min(scratch.len());441 must(fill(at, &mut scratch[..count]));442 must(with_storage(|storage| {443 storage.write(block, at as u64, &scratch[..count])444 }));445 at += count;446 }447 Self {448 block,449 len: len as u64,450 }451 }452 pub fn len(&self) -> usize {453 usize::try_from(self.len).expect("stable blob length exceeds usize")454 }455 pub fn is_empty(&self) -> bool {456 self.len == 0457 }458 pub fn to_transient(&self) -> std::vec::Vec<u8> {459 must(with_storage_read(|storage| self.read_in(storage)))460 }461 pub(super) fn read_in(&self, storage: &dyn Storage) -> Result<std::vec::Vec<u8>> {462 let mut bytes = std::vec![0; self.len()];463 if !bytes.is_empty() {464 storage.read(self.block, 0, &mut bytes)?;465 }466 Ok(bytes)467 }468 pub fn copy(&self) -> Self {469 Self::from_slice(&self.to_transient())470 }471 pub fn read_range(&self, start: usize, out: &mut [u8]) {472 assert!(473 start474 .checked_add(out.len())475 .is_some_and(|end| end <= self.len())476 );477 if !out.is_empty() {478 must(with_storage_read(|storage| {479 storage.read(self.block, start as u64, out)480 }));481 }482 }483}484impl Default for Blob {485 fn default() -> Self {486 Self::new()487 }488}489impl Codec for Blob {490 const __CODEC_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("mod.rs", "shared.rs");491 const SIZE: usize = Block::SIZE + u64::SIZE;492 fn encode(&self, out: &mut [u8]) {493 self.block.encode(&mut out[..16]);494 self.len.encode(&mut out[16..]);495 }496 fn decode(bytes: &[u8]) -> Result<Self> {497 if bytes.len() != Self::SIZE {498 return Err(Error::Bounds);499 }500 let block = Block::decode(&bytes[..16])?;501 let len = u64::decode(&bytes[16..])?;502 if block.is_null() != (len == 0) {503 return Err(Error::Corrupt("stable blob"));504 }505 Ok(Self { block, len })506 }507}508// SAFETY: nonempty Blob owns precisely its single allocation and no children.509unsafe impl HylixValue for Blob {510 fn retire(self, storage: &mut dyn Storage) -> Result<()> {511 if !self.block.is_null() {512 storage.deallocate(self.block)?;513 }514 Ok(())515 }516}517518#[cfg(test)]519mod tests {520 use super::*;521 use cdk_rsx_engine_hylix::{Arena, reset_context_after_rollback, using, using_read};522 use cdk_rsx_platform::memory::VecMemory;523524 const CONTRACT: [u8; 32] = [0xc7; 32];525 fn fresh() -> Arena<VecMemory> {526 Arena::format(VecMemory::new(), CONTRACT).unwrap()527 }528529 #[test]530 fn inline_cell_loans_use_no_global_capacity_and_keep_reader_writer_exclusion() {531 let mut arena = fresh();532 let cell = using(&mut arena, || Ok(Cell::new(12u64))).unwrap();533 for _ in 0..8 {534 using_read(&arena, || {535 let read = cell.try_read()?;536 let other = cell.try_read()?;537 assert_eq!(*other, 12);538 drop(read);539 CELL_LOANS.with(|loans| {540 let loans = loans.borrow();541 assert_eq!(loans.len, 1);542 assert_eq!(loans.overflow.capacity(), 0);543 });544 drop(other);545 CELL_LOANS.with(|loans| {546 let loans = loans.borrow();547 assert_eq!((loans.len, loans.overflow.capacity()), (0, 0));548 });549 assert!(550 cell.try_edit().is_err(),551 "read-only context cannot grant a writer"552 );553 Ok(())554 })555 .unwrap();556 }557 using(&mut arena, || {558 let read = cell.try_read()?;559 assert!(cell.try_edit().is_err());560 drop(read);561 let mut write = cell.try_edit()?;562 *write += 1;563 assert!(cell.try_read().is_err());564 assert!(cell.try_edit().is_err());565 drop(write);566 CELL_LOANS.with(|loans| assert_eq!(loans.borrow().overflow.capacity(), 0));567 with_storage(|storage| cell.retire(storage))?;568 Ok(())569 })570 .unwrap();571 }572573 #[test]574 fn expired_cell_edits_cannot_publish_after_a_restored_native_image() {575 let mut arena = fresh();576 let cell = using(&mut arena, || Ok(Cell::new(12u64))).unwrap();577 let image = arena.into_memory();578 let mut arena = Arena::open(image.clone(), CONTRACT).unwrap();579 let mut escaped = None;580 let failure = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {581 using(&mut arena, || {582 let mut edit = cell.edit();583 *edit = 999;584 escaped = Some(edit);585 Ok(())586 })587 }));588 assert!(589 failure.is_err(),590 "a live guard must fail frame finalization"591 );592 assert!(593 using(&mut arena, || Ok(())).is_err(),594 "failed native context is quarantined"595 );596 // SAFETY: this restores the complete provider snapshot before granting597 // another native context. No Wasm caller has this test-host API.598 arena = Arena::open(image.clone(), CONTRACT).unwrap();599 unsafe {600 reset_context_after_rollback().unwrap();601 }602 using(&mut arena, || {603 assert!(604 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(escaped.take())))605 .is_err()606 );607 assert_eq!(*cell.read(), 12, "expired edit must not publish 999");608 *cell.edit() = 13;609 assert_eq!(*cell.read(), 13);610 Ok(())611 })612 .unwrap();613 drop(escaped);614 let failure = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {615 using(&mut arena, || {616 std::mem::forget(cell.edit());617 Ok(())618 })619 }));620 assert!(failure.is_err());621 arena = Arena::open(image, CONTRACT).unwrap();622 // SAFETY: the provider has just been restored to the complete image.623 unsafe {624 reset_context_after_rollback().unwrap();625 }626 using(&mut arena, || {627 assert_eq!(*cell.read(), 12);628 assert_eq!(629 CELL_LOANS.with(|loans| loans.borrow().overflow.capacity()),630 0631 );632 with_storage(|storage| cell.retire(storage))?;633 Ok(())634 })635 .unwrap();636 }637638 #[test]639 fn overflow_preserves_owner_exclusion_and_releases_before_inline_guards() {640 let mut arena = fresh();641 let cells = using(&mut arena, || {642 Ok((0u64..12).map(Cell::new).collect::<std::vec::Vec<_>>())643 })644 .unwrap();645 using(&mut arena, || {646 let mut reads = cells647 .iter()648 .map(Cell::try_read)649 .collect::<Result<std::vec::Vec<_>>>()?;650 CELL_LOANS.with(|loans| {651 let loans = loans.borrow();652 assert_eq!(loans.len, INLINE_LOANS);653 assert_eq!(loans.overflow.len(), 12 - INLINE_LOANS);654 });655 for cell in &cells {656 assert!(cell.try_edit().is_err());657 }658 for index in [0, 7] {659 let mut bytes = [0; Cell::<u64>::SIZE];660 cells[index].encode(&mut bytes);661 let alias = Cell::<u64>::decode(&bytes)?;662 assert!(663 with_storage(|storage| alias.retire(storage)).is_err(),664 "a context loan alone cannot pin this allocation"665 );666 }667 drop(reads.remove(0));668 *cells[0].try_edit()? = 100;669 assert_eq!(670 *cells[0].try_read()?,671 100,672 "reuse a free inline slot while overflow loans remain"673 );674 for cell in &cells[1..] {675 assert!(cell.try_edit().is_err());676 }677 drop(reads.split_off(INLINE_LOANS - 1));678 CELL_LOANS.with(|loans| {679 let loans = loans.borrow();680 assert_eq!(loans.len, INLINE_LOANS - 1);681 assert_eq!(682 loans.overflow.capacity(),683 0,684 "empty overflow releases its Global allocation immediately"685 );686 });687 drop(reads);688 cdk_rsx_engine_hylix::check_no_loans()?;689 Ok(())690 })691 .unwrap();692 using(&mut arena, || {693 for cell in cells {694 with_storage(|storage| cell.retire(storage))?;695 }696 Ok(())697 })698 .unwrap();699 }700701 #[test]702 fn deeply_nested_readers_can_overflow_and_unwind_without_a_guard_limit() {703 fn nested(cells: &[Cell<u64>], index: usize) -> Result<()> {704 let read = cells[index].try_read()?;705 let second = cells[index].try_read()?;706 assert_eq!(*read, index as u64);707 assert!(cells[index].try_edit().is_err());708 if index + 1 < cells.len() {709 nested(cells, index + 1)?;710 }711 if index + 1 == INLINE_LOANS {712 CELL_LOANS.with(|loans| assert_eq!(loans.borrow().overflow.capacity(), 0));713 }714 drop(second);715 assert!(716 cells[index].try_edit().is_err(),717 "one remaining reader still excludes a writer"718 );719 drop(read);720 drop(cells[index].try_edit()?);721 Ok(())722 }723 let mut arena = fresh();724 let cells = using(&mut arena, || {725 Ok((0u64..24).map(Cell::new).collect::<std::vec::Vec<_>>())726 })727 .unwrap();728 using(&mut arena, || nested(&cells, 0)).unwrap();729 using(&mut arena, || {730 for cell in cells {731 with_storage(|storage| cell.retire(storage))?;732 }733 Ok(())734 })735 .unwrap();736 }737738 #[test]739 fn rollback_resets_overflow_and_stale_read_drops_cannot_release_new_loans() {740 let mut arena = fresh();741 let cells = using(&mut arena, || {742 Ok((0u64..12).map(Cell::new).collect::<std::vec::Vec<_>>())743 })744 .unwrap();745 let image = arena.into_memory();746 let mut arena = Arena::open(image.clone(), CONTRACT).unwrap();747 let mut escaped = std::vec::Vec::new();748 let failure = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {749 using(&mut arena, || {750 for cell in &cells {751 escaped.push(cell.try_read()?);752 }753 core::mem::forget(cells.last().unwrap().try_read()?);754 Ok(())755 })756 }));757 assert!(failure.is_err());758 assert!(759 using(&mut arena, || Ok(())).is_err(),760 "forgotten and escaped loans quarantine the provider"761 );762 arena = Arena::open(image, CONTRACT).unwrap();763 // SAFETY: restore the complete provider image before clearing native764 // quarantine. Old guards keep their invalidated original epochs.765 unsafe {766 reset_context_after_rollback().unwrap();767 }768 using(&mut arena, || {769 let current = cells[0].try_read()?;770 CELL_LOANS.with(|loans| {771 let loans = loans.borrow();772 assert_eq!((loans.len, loans.overflow.capacity()), (1, 0));773 });774 drop(core::mem::take(&mut escaped));775 assert!(776 cells[0].try_edit().is_err(),777 "stale drops cannot end the new epoch's matching-block loan"778 );779 assert_eq!(*current, 0);780 drop(current);781 *cells[0].try_edit()? = 91;782 Ok(())783 })784 .unwrap();785 drop(escaped);786 using(&mut arena, || {787 assert_eq!(*cells[0].try_read()?, 91);788 for cell in cells {789 with_storage(|storage| cell.retire(storage))?;790 }791 Ok(())792 })793 .unwrap();794 }795}