publication.rs

verification/proofs/hylix/native/publication.rs

publication.rs213 lines← SDK documentation
1use super::*;2use crate::{Block, Storage, context};3use std::panic::{AssertUnwindSafe, catch_unwind};45#[derive(Clone, Debug, PartialEq, Eq)]6enum Event { Begin, Closure, Write(u64), Retire, Records, Finish, Finished, Discard, Return }7struct Image {8    bytes: [u8; 1536], reads: Cell<usize>, writes: usize,9    events: Rc<RefCell<Vec<Event>>>, fail: bool,10}11// One owned initialized byte image. The event observer owns no physical bytes.12// The failure scenario deliberately injects a partial provider error and relies13// on the actual caller's abort path; caught native panic is never a commit.14unsafe impl Memory for Image {15    fn len(&self) -> u64 { 1536 }16    fn grow_to(&mut self, n: u64) -> Result<()> { if n <= 1536 { Ok(()) } else { Err(Error::Bounds) } }17    fn read(&self, at: u64, out: &mut [u8]) -> Result<()> {18        let start = usize::try_from(at).map_err(|_| Error::Bounds)?;19        let end = start.checked_add(out.len()).ok_or(Error::Bounds)?;20        out.copy_from_slice(self.bytes.get(start..end).ok_or(Error::Bounds)?);21        self.reads.set(self.reads.get()+1); Ok(())22    }23    fn write(&mut self, at: u64, input: &[u8]) -> Result<()> {24        let start = usize::try_from(at).map_err(|_| Error::Bounds)?;25        let end = start.checked_add(input.len()).ok_or(Error::Bounds)?;26        let output = self.bytes.get_mut(start..end).ok_or(Error::Bounds)?;27        self.writes += 1; self.events.borrow_mut().push(Event::Write(at));28        if self.fail && !input.is_empty() { output[0]=input[0]; return Err(Error::Bounds); }29        output.copy_from_slice(input); Ok(())30    }31}32fn working_config(retain_clean: bool, max_segments: usize) -> WorkingSet<Image> {33    WorkingSet::new(Image { bytes:[0;1536], reads:Cell::new(0), writes:0,34        events:Rc::new(RefCell::new(Vec::new())), fail:false },35        WorkingSetConfig { segment_bytes:512, max_segments, retain_clean }).unwrap()36}37fn working(retain_clean: bool) -> WorkingSet<Image> { working_config(retain_clean, 1) }38struct Frame { working: WorkingSet<Image>, reject_finish: bool }39impl Frame {40    fn fresh() -> Self { Self { working:working(true), reject_finish:false } }41    fn event(&self, e: Event) { self.working.memory.borrow().events.borrow_mut().push(e); }42}43// A transparent no-allocation Storage adapter over the REAL WorkingSet. It has44// one pre-admitted fixed block, exact bounds and no decoded allocator metadata.45// It does not stand in for Arena's slab/allocator publication algorithm.46impl Storage for Frame {47    fn frame_begin(&self,writable:bool)->Result<()> { self.event(Event::Begin); self.working.begin(writable) }48    fn frame_finish(&mut self)->Result<()> {49        self.event(Event::Finish);50        if self.reject_finish { return Err(Error::Bounds); }51        self.working.finish()?; self.event(Event::Finished); Ok(())52    }53    fn frame_discard(&self) { self.event(Event::Discard); self.working.discard(); }54    fn allocate(&mut self,_:u64)->Result<Block>{Err(Error::Bounds)}55    fn deallocate(&mut self,_:Block)->Result<()>{Err(Error::Bounds)}56    fn resize(&mut self,_:Block,_:u64)->Result<Block>{Err(Error::Bounds)}57    fn len(&self,b:Block)->Result<u64>{if b==crate::storage::fixture_block(){Ok(1536)}else{Err(Error::Bounds)}}58    fn read(&self,b:Block,at:u64,out:&mut[u8])->Result<()>{self.len(b)?;self.working.read(at,out)}59    fn write(&mut self,b:Block,at:u64,input:&[u8])->Result<()>{self.len(b)?;self.working.write(at,input)}60}6162fn eviction_discard_query_and_clean_cache() {63    let mut ws=working(true);64    ws.begin(true).unwrap(); ws.write(8,&[0x31]).unwrap();65    let mut got=[0]; ws.read(8,&mut got).unwrap();66    assert_eq!(got,[0x31]); assert_eq!(ws.memory.borrow().writes,0);67    ws.write(520,&[0x47]).unwrap();68    assert_eq!(ws.memory.borrow().bytes[8],0x31);69    assert_eq!(ws.memory.borrow().bytes[520],0);70    assert_eq!(ws.memory.borrow().writes,1); // dirty eviction precedes finish71    ws.discard();72    assert_eq!(ws.memory.borrow().bytes[8],0x31); // discard did not undo it73    assert_eq!(ws.memory.borrow().bytes[520],0); // pending dirty cache was dropped74    ws.begin(false).unwrap();75    ws.read(8,&mut got).unwrap(); assert_eq!(got,[0x31]);76    ws.read(520,&mut got).unwrap(); assert_eq!(got,[0]);77    assert!(ws.write(8,&[3]).is_err());78    ws.discard(); assert_eq!(ws.memory.borrow().writes,1);7980    ws.begin(true).unwrap(); ws.write(8,&[0x59]).unwrap(); ws.finish().unwrap();81    let reads=ws.memory.borrow().reads.get(); let writes=ws.memory.borrow().writes;82    assert!(!ws.active() && !ws.writable());83    assert!(ws.state.borrow().dirty.is_empty());84    ws.begin(false).unwrap(); ws.read(8,&mut got).unwrap(); assert_eq!(got,[0x59]);85    assert_eq!(ws.memory.borrow().reads.get(),reads); // retained clean hit86    ws.discard(); assert_eq!(ws.memory.borrow().writes,writes);87}88fn crossing_and_pinned_reads() {89    let mut ws=working(false);90    ws.begin(true).unwrap();91    ws.edit(511,2,|out|{out.copy_from_slice(&[0x61,0x73]);Err::<(),_>(Error::Bounds)}).unwrap_err();92    assert_eq!(ws.memory.borrow().bytes[511],0x61); // first segment already evicted93    assert_eq!(ws.memory.borrow().bytes[512],0);94    ws.finish().unwrap();95    let image=ws.into_memory();96    for n in 0..1536 { assert_eq!(image.bytes[n],if n==511{0x61}else if n==512{0x73}else{0}); }97    assert_eq!(image.writes,2);9899    let ws=working(true); ws.begin(false).unwrap();100    ws.visit(0,8,|outer|{101        let saved=outer.as_ptr();102        ws.visit(512,8,|inner|{assert_eq!(inner,&[0;8]);Ok(())})?;103        assert_eq!(outer.as_ptr(),saved); assert_eq!(outer,&[0;8]); Ok(())104    }).unwrap();105    assert_eq!(ws.views.get(),0); assert_eq!(ws.memory.borrow().writes,0);106    ws.discard();107    let mut empty=working(false);empty.begin(true).unwrap();108    let mut called=false;109    empty.edit(1536,0,|bytes|{called=true;assert!(bytes.is_empty());Ok(())}).unwrap();110    empty.finish().unwrap(); assert!(called); assert_eq!(empty.memory.borrow().writes,0);111}112fn pinned_dirty_identity_moves_without_invalidating_its_view() {113    let mut ws=working_config(true,2);114    ws.begin(true).unwrap();ws.write(8,&[0x31]).unwrap();ws.write(520,&[0x47]).unwrap();115    ws.visit(512,16,|pinned|{116        assert_eq!(pinned[8],0x47);117        let mut third=[0];ws.read(1024,&mut third)?;118        assert_eq!(pinned[8],0x47); // dirty-position Cell moved; byte loan stayed pinned119        Ok(())120    }).unwrap();121    assert_eq!(ws.memory.borrow().writes,1);122    assert_eq!(ws.state.borrow().dirty.as_slice(),&[512]);123    assert_eq!(ws.state.borrow().segments.get(&512).unwrap().dirty_position.get(),0);124    ws.finish().unwrap();125    assert_eq!(ws.memory.borrow().writes,2);126    assert_eq!(ws.memory.borrow().bytes[8],0x31);assert_eq!(ws.memory.borrow().bytes[520],0x47);127}128fn returned_errors_and_early_write_trace() {129    for fail in [false,true] {130        let mut frame=Frame::fresh();131        let events=Rc::clone(&frame.working.memory.borrow().events);132        let returned=context::using(&mut frame,||{133            events.borrow_mut().push(Event::Closure);134            context::with_storage(|s|s.write(crate::storage::fixture_block(),8,&[0x31]))?;135            context::with_storage(|s|s.write(crate::storage::fixture_block(),520,&[0x47]))?;136            // Caller-supplied retirement/record-publication contract points.137            // This does not prove actual Store or Arena metadata publication.138            events.borrow_mut().push(Event::Retire);139            events.borrow_mut().push(Event::Records);140            if fail{Err(Error::Bounds)}else{Ok(17usize)}141        });142        events.borrow_mut().push(Event::Return);143        assert!(match returned{Ok(n)=>!fail&&n==17,Err(Error::Bounds)=>fail,Err(_)=>false});144        assert_eq!(*events.borrow(),vec![Event::Begin,Event::Closure,Event::Write(8),Event::Retire,145            Event::Records,Event::Finish,Event::Write(520),Event::Finished,Event::Return]);146        assert_eq!(frame.working.memory.borrow().bytes[8],0x31);147        assert_eq!(frame.working.memory.borrow().bytes[520],0x47);148        let writes=frame.working.memory.borrow().writes;149        context::using_read(&frame,||{150            let mut got=[0];151            context::with_storage_read(|s|s.read(crate::storage::fixture_block(),8,&mut got))?;152            assert_eq!(got,[0x31]);153            assert!(context::with_storage(|_|Ok(())).is_err());154            Ok(())155        }).unwrap();156        assert_eq!(frame.working.memory.borrow().writes,writes);157        assert_eq!(events.borrow().last(),Some(&Event::Discard));158    }159}160fn native_failure_is_not_rollback_and_guard_quarantine() {161    let mut frame=Frame::fresh(); frame.working.memory.borrow_mut().fail=true;162    let failed=catch_unwind(AssertUnwindSafe(||context::using(&mut frame,||{163        context::with_storage(|s|s.write(crate::storage::fixture_block(),8,&[0x31,0x47]))164    })));165    let payload=failed.expect_err("partial provider failure must abort");166    assert!(matches!(payload.downcast_ref::<Error>(),Some(Error::Bounds)));167    assert_eq!(frame.working.memory.borrow().bytes[8],0x31);168    assert_eq!(frame.working.memory.borrow().bytes[9],0);169    // Whole failed image is abandoned; no continuation from caught partial state.170    drop(frame);171172    let mut frame=Frame::fresh(); frame.reject_finish=true;173    let failed=catch_unwind(AssertUnwindSafe(||context::using(&mut frame,||{174        context::with_storage(|s|s.write(crate::storage::fixture_block(),8,&[0x31]))?;175        context::with_storage(|s|s.write(crate::storage::fixture_block(),520,&[0x47]))176    })));177    let payload=failed.expect_err("returned finalization failure must abort before returning R");178    let message=payload.downcast_ref::<String>().map(String::as_str)179        .or_else(||payload.downcast_ref::<&'static str>().copied());180    assert_eq!(message,Some("Hylix frame finalization: Bounds"));181    assert_eq!(frame.working.memory.borrow().bytes[8],0x31); // earlier eviction remains182    assert_eq!(frame.working.memory.borrow().bytes[520],0); // pending buffer discarded183    assert!(!frame.working.active());184    drop(frame); // abandon this entire failed image too185186    let mut frame=Frame::fresh(); let mut old=None;187    let failed=catch_unwind(AssertUnwindSafe(||context::using(&mut frame,||{188        old=Some(context::ContextLoan::new()?);Ok(())189    })));190    let payload=failed.expect_err("outstanding guard must abort before returning R");191    assert!(matches!(payload.downcast_ref::<Error>(),Some(Error::InvalidInput("Hylix context has live collection guards"))));192    assert!(old.as_ref().unwrap().check().is_err());193    let mut called=false;194    assert!(context::using(&mut frame,||{called=true;Ok(())}).is_err()); assert!(!called);195    // Restore the entire fixture image/cache before the native-only host hook.196    frame=Frame::fresh();unsafe{context::reset_context_after_rollback().unwrap();}197    context::using(&mut frame,||{198        let current=context::ContextLoan::new()?;199        assert!(old.as_ref().unwrap().check().is_err());200        drop(old.take());201        assert!(context::check_no_loans().is_err());202        drop(current);assert!(context::check_no_loans().is_ok());Ok(())203    }).unwrap();204}205206pub fn run() {207    eviction_discard_query_and_clean_cache();208    crossing_and_pinned_reads();209    pinned_dirty_identity_moves_without_invalidating_its_view();210    returned_errors_and_early_write_trace();211    native_failure_is_not_rollback_and_guard_quarantine();212    println!("hylix_actual_publication_context_ok");213}