use super::*; use crate::{AdvanceFrameOutcome, HostExecutionStatus}; use prometeu_test_support::memcard_fixture::{MemcardFixture, memcard_program}; use std::{fs, sync::mpsc}; /// Holds the first native write after admission; the controller decides its outcome. struct BootstrapStore { file: FileMemcard, entered: mpsc::Sender<()>, continue_io: mpsc::Receiver>, held: bool, } impl MemcardStorage for BootstrapStore { fn len(&self) -> Result { self.file.len() } fn read_only(&self) -> bool { false } fn read_at(&mut self, offset: u64, bytes: &mut [u8]) -> Result<(), MemcardIoError> { self.file.read_at(offset, bytes) } fn write_at(&mut self, offset: u64, bytes: &[u8]) -> Result<(), MemcardIoError> { if !self.held { self.held = true; let _ = self.entered.send(()); self.continue_io .recv_timeout(Duration::from_secs(5)) .unwrap_or(Err(MemcardIoError::IoError))?; } self.file.write_at(offset, bytes) } fn sync(&mut self) -> Result<(), MemcardIoError> { self.file.sync() } } fn reopen_with_controlled_io( kind: MemcardFixture, ) -> (Fixture, HeadlessHost, mpsc::Receiver<()>, mpsc::Sender>) { use prometeu_system::memcard::{ image::{Game, Icon, crc32c}, transaction::{DurableResult, PublicationControl}, }; let f = Fixture::new(kind); let file = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| { Card::format(io, id).map_err(|_| MemcardIoError::IoError) }) .unwrap(); let mut card = Card::mount(Box::new(file)).unwrap(); let icon = [0; 560]; card.register( Game { app_id: 42, title: "Existing record".into(), data_format_version: 1, created_at: 0, slots: vec![0], icon: Icon { offset: 0, frames: 1, duration: 1, crc32c: crc32c(&icon) }, }, &icon, &PublicationControl::default(), ) .unwrap(); assert_eq!( card.commit(0, &[0, 127, 128, 255], 0, &PublicationControl::default()).durable, DurableResult::Success ); drop(card); let (entered_tx, entered) = mpsc::channel(); let (continue_io, release_rx) = mpsc::channel(); let mut host = HeadlessHost::new(); host.media.path = Some(f.image.clone()); host.media.access = Some(MediaAccess::ReadWrite); host.install_memcard(Box::new(BootstrapStore { file: FileMemcard::open(&f.image, false).unwrap(), entered: entered_tx, continue_io: release_rx, held: false, })) .unwrap(); host.boot_with_memcard_choice(f.cart.to_string_lossy(), Choice::Persistent).unwrap(); assert_eq!(host.get_state().tick_index, 0); (f, host, entered, continue_io) } #[test] fn first_reopen_frame_waits_for_controlled_presentation_without_replaying() { let (_f, mut host, entered, continue_io) = reopen_with_controlled_io(MemcardFixture::ReadWithPresentation); let (finished_tx, finished) = mpsc::channel(); let controller = std::thread::spawn(move || { entered.recv_timeout(Duration::from_secs(3)).unwrap(); // Observe the owner while publication is provably held. This is a // channel deadline, not a sleep used to infer that IO has started. let premature = finished.recv_timeout(Duration::from_millis(300)).is_ok(); let _ = continue_io.send(Ok(())); premature }); let result = host.advance_frame(); let _ = finished_tx.send(()); let premature = controller.join().unwrap(); assert!(!premature, "advance returned while native publication was held: {result:?}"); assert!(matches!( result, Ok(AdvanceFrameOutcome::FrameCompleted { logical_frame_index: 1, .. }) )); let state = host.get_state(); assert_eq!(state.frame_index, 1); assert_eq!(state.tick_index, 2); assert_eq!(state.status, HostExecutionStatus::Paused); assert_eq!(state.stack_top.last(), Some(&prometeu_bytecode::Value::Int64(201))); assert!(!host.firmware.os.vm().debug_step_requested()); assert!(host.get_fault().is_none()); assert!(!host.get_memcard_state().io.active); assert_eq!(host.capture_frame().unwrap().logical_frame_index, 1); host.shutdown(TeardownPolicy::default()).unwrap(); } #[test] fn blocked_bootstrap_reaches_native_deadline_and_keeps_worker_lock() { let (f, mut host, entered, continue_io) = reopen_with_controlled_io(MemcardFixture::ReadWithPresentation); let started = Instant::now(); let result = host.advance_frame(); entered.recv_timeout(Duration::from_secs(1)).unwrap(); let state = host.get_memcard_state(); let busy = matches!(FileMemcard::open(&f.image, false), Err(MemcardIoError::Busy)); // Always let the worker return before asserting, including on the old host. continue_io.send(Ok(())).unwrap(); settle(&mut host); assert_eq!(result.unwrap(), AdvanceFrameOutcome::ActionRequired); assert!(started.elapsed() < Duration::from_secs(3)); assert!(state.recovery.restart_required); assert!(state.io.active && busy); assert_eq!(host.get_state().frame_index, 0); assert_eq!(host.get_state().tick_index, 1); assert_eq!(host.get_state().status, HostExecutionStatus::Paused); assert!(!host.firmware.os.vm().debug_step_requested()); assert!(host.get_fault().is_none()); } #[test] fn ordinary_gameplay_commit_does_not_wait_for_native_io() { let (_f, mut host, entered, continue_io) = reopen_with_controlled_io(MemcardFixture::Read); host.advance_frame().unwrap(); let service = host.firmware.os.memcard(); let context = service.session.context(); service.session.write(context, 0, 0, &[0, 127, 128, 255]).unwrap(); service.session.commit(context, 0, 0, Instant::now(), &service.lane).unwrap(); entered.recv_timeout(Duration::from_secs(2)).unwrap(); let result = host.advance_frame(); let pending = host.get_memcard_state(); continue_io.send(Ok(())).unwrap(); settle(&mut host); assert!(matches!( result, Ok(AdvanceFrameOutcome::FrameCompleted { logical_frame_index: 2, .. }) )); assert!(pending.io.active); assert_eq!(pending.request.unwrap().operation, "commit"); assert!(!host.firmware.os.vm().debug_step_requested()); assert!(host.get_fault().is_none()); host.shutdown(TeardownPolicy::default()).unwrap(); } #[test] fn bootstrap_wait_deadline_is_shared_across_wakes_and_reentry() { use super::super::{BOOTSTRAP_IO_WAIT_QUANTUM, BootstrapIoWait}; let start = Instant::now(); let mut wait = BootstrapIoWait::default(); assert_eq!(wait.next_wait(start), Some(BOOTSTRAP_IO_WAIT_QUANTUM)); assert_eq!( wait.next_wait(start + Duration::from_millis(1000)), Some(BOOTSTRAP_IO_WAIT_QUANTUM) ); assert_eq!(wait.next_wait(start + Duration::from_millis(1999)), Some(Duration::from_millis(1))); assert_eq!(wait.next_wait(start + Duration::from_secs(2)), None); assert_eq!(wait.next_wait(start + Duration::from_secs(3)), None); } #[test] fn bootstrap_outer_timeout_preserves_native_snapshot_and_machine_state() { use super::super::BootstrapIoWait; let (_f, mut host, _entered, _release) = reopen_with_controlled_io(MemcardFixture::Read); let before = host.get_state(); host.firmware.os.vm().set_paused(false); host.firmware.os.vm().request_debug_step(); let mut wait = BootstrapIoWait { deadline: Some(Instant::now()) }; let error = host.wait_for_bootstrap_io(&mut wait, 0).unwrap_err(); let snapshot = host.get_memcard_state(); let HostError::Memcard(error) = error else { panic!("expected a native memcard error") }; assert_eq!(error.operation, "advance"); assert_eq!(error.reason, "restart_required"); assert_eq!(error.state, snapshot); let after = host.get_state(); assert_eq!((after.pc, after.frame_index, after.tick_index), (before.pc, 0, 0)); assert_eq!(after.stack_top.to_vec(), before.stack_top.to_vec()); assert_eq!(after.status, HostExecutionStatus::Paused); assert!(!host.firmware.os.vm().debug_step_requested()); assert!(host.get_fault().is_none()); host.shutdown(TeardownPolicy::default()).unwrap(); } #[test] fn failed_bootstrap_io_returns_native_media_action_without_guest_fault() { let (_f, mut host, entered, continue_io) = reopen_with_controlled_io(MemcardFixture::ReadWithPresentation); let controller = std::thread::spawn(move || { entered.recv_timeout(Duration::from_secs(2)).unwrap(); continue_io.send(Err(MemcardIoError::Unavailable)).unwrap(); }); let result = host.advance_frame(); controller.join().unwrap(); assert_eq!(result.unwrap(), AdvanceFrameOutcome::ActionRequired); let state = host.get_memcard_state(); assert!(state.recovery.removal_pending); assert!(!state.io.active); assert_eq!(host.get_state().frame_index, 0); assert_eq!(host.get_state().status, HostExecutionStatus::Paused); assert!(!host.firmware.os.vm().debug_step_requested()); assert!(host.get_fault().is_none()); } #[test] fn queued_bootstrap_publication_can_progress_without_moving_guest_during_poll() { use prometeu_system::AsyncWorkJobOutcome; let (_f, mut host, entered, continue_io) = reopen_with_controlled_io(MemcardFixture::ReadWithPresentation); let (busy_tx, busy) = mpsc::channel(); let (unblock, unblock_rx) = mpsc::channel(); host.firmware .os .memcard() .lane .submit_memcard_commit_write(move |_| { busy_tx.send(()).unwrap(); let _ = unblock_rx.recv_timeout(Duration::from_secs(3)); AsyncWorkJobOutcome::Completed }) .unwrap(); busy.recv_timeout(Duration::from_secs(2)).unwrap(); for _ in 0..10 { host.firmware.os.vm().set_paused(false); host.firmware.os.vm().request_debug_step(); host.tick_once(); if host.bootstrap_io_pending() { break; } } let pending = host.bootstrap_io_pending(); let queued = host.get_memcard_state(); let before = host.get_state(); host.poll_memcard(); let after = host.get_state(); let (finished_tx, finished) = mpsc::channel(); let controller = std::thread::spawn(move || { let premature = finished.recv_timeout(Duration::from_millis(300)).is_ok(); let _ = unblock.send(()); entered.recv_timeout(Duration::from_secs(2)).unwrap(); let _ = continue_io.send(Ok(())); premature }); let result = host.advance_frame(); let _ = finished_tx.send(()); let premature = controller.join().unwrap(); assert!(pending); assert!(!premature, "advance returned while its publication was queued: {result:?}"); assert_eq!(queued.io.phase, "queued"); assert_eq!( (before.pc, before.frame_index, before.tick_index), (after.pc, after.frame_index, after.tick_index) ); assert_eq!(before.stack_top.to_vec(), after.stack_top.to_vec()); assert!(matches!( result, Ok(AdvanceFrameOutcome::FrameCompleted { logical_frame_index: 1, .. }) )); host.shutdown(TeardownPolicy::default()).unwrap(); } struct Fixture { root: PathBuf, image: PathBuf, cart: PathBuf, } impl Fixture { fn new(kind: MemcardFixture) -> Self { static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let root = std::env::temp_dir().join(format!( "native-memcard-{}-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(), COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed) )); let cart = root.join("cart"); fs::create_dir_all(&cart).unwrap(); fs::write(cart.join("program.pbx"), memcard_program(kind)).unwrap(); fs::write(cart.join("manifest.json"),r#"{"magic":"PMTU","cartridge_version":1,"app_id":42,"title":"Native memcard","app_version":"1","app_mode":"Game","capabilities":["memcard"],"memcard_slots":1}"#).unwrap(); let image = root.join("save.pmc"); Self { root, image, cart } } fn mount(&self, host: &mut HeadlessHost) { host.mount_memcard(MemcardMount { path: self.image.to_string_lossy().into_owned(), action: MediaAction::Create, access: MediaAccess::ReadWrite, }) .unwrap(); host.boot_with_memcard_choice(self.cart.to_string_lossy(), Choice::Persistent).unwrap(); } } impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.root); } } fn settle(host: &mut HeadlessHost) { let deadline = Instant::now() + Duration::from_secs(3); loop { host.poll_memcard(); if !host.get_memcard_state().io.active { break; } assert!(Instant::now() < deadline, "IO did not cease"); let lane = host.firmware.os.memcard().lane.clone(); lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5)); } } fn pause_for_media(host: &mut HeadlessHost) { let task = host.firmware.os.lifecycle().resident_game_task().unwrap(); host.firmware.os.lifecycle().suspend_task(task).unwrap(); assert_eq!( host.firmware.os.lifecycle().task_state(task), Some(prometeu_system::task::TaskState::Suspended) ); } #[test] fn same_media_recovery_rejects_replacement_and_preserves_ram_continuation() { let f = Fixture::new(MemcardFixture::Dirty); let mut host = HeadlessHost::new(); f.mount(&mut host); assert!(matches!(host.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. })); settle(&mut host); let context = host.firmware.os.memcard().session.context(); host.firmware.os.memcard().session.notify_removal(); pause_for_media(&mut host); assert_eq!(host.get_state().status, HostExecutionStatus::Paused); assert_eq!(host.advance_frame().unwrap(), AdvanceFrameOutcome::ActionRequired); let old = f.root.join("old.pmc"); fs::rename(&f.image, &old).unwrap(); let replacement = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| { Card::format(io, id).map_err(|_| MemcardIoError::IoError) }) .unwrap(); drop(replacement); let error = host.reconcile_memcard().unwrap_err(); assert!(matches!(error,HostError::Memcard(e) if e.reason=="identity_mismatch")); let mut bytes = [0; 4]; host.firmware.os.memcard().session.read(context, 0, 0, &mut bytes).unwrap(); assert_eq!(bytes, [0, 127, 128, 255]); fs::rename(&f.image, f.root.join("other.pmc")).unwrap(); fs::rename(&old, &f.image).unwrap(); let restored = host.reconcile_memcard().unwrap(); assert!(restored.dirty); assert!(!restored.recovery.reconciliation_required); assert_eq!(host.firmware.os.memcard().session.context(), context); assert!(matches!(host.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. })); assert_eq!(host.get_state().stack_top.last(), Some(&prometeu_bytecode::Value::Int64(301))); host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap(); } #[test] fn explicit_continue_in_ram_preserves_dirty_snapshot_and_uses_no_new_boot() { let f = Fixture::new(MemcardFixture::Dirty); let mut host = HeadlessHost::new(); f.mount(&mut host); host.advance_frame().unwrap(); settle(&mut host); let context = host.firmware.os.memcard().session.context(); host.firmware.os.memcard().session.notify_removal(); pause_for_media(&mut host); let ram = host.continue_memcard_in_memory().unwrap(); assert_eq!(ram.session.mode, Some("memory_only")); assert!(ram.dirty); assert_eq!(host.firmware.os.memcard().session.context(), context); host.advance_frame().unwrap(); host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap(); } struct GateStore { file: FileMemcard, inside_publication: bool, payload_seen: bool, fired: bool, entered: mpsc::Sender<()>, continue_io: mpsc::Receiver<()>, } impl MemcardStorage for GateStore { fn len(&self) -> Result { self.file.len() } fn read_only(&self) -> bool { false } fn read_at(&mut self, o: u64, b: &mut [u8]) -> Result<(), MemcardIoError> { self.file.read_at(o, b) } fn sync(&mut self) -> Result<(), MemcardIoError> { self.file.sync() } fn write_at(&mut self, o: u64, b: &[u8]) -> Result<(), MemcardIoError> { let payload = o >= prometeu_system::memcard::image::DATA_OFFSET; self.payload_seen |= payload; let publication = self.payload_seen && (o == 8192 || o == 12288); if !self.fired && if self.inside_publication { publication } else { payload } { self.fired = true; if self.inside_publication { self.file.write_at(o, b)?; } self.entered.send(()).unwrap(); self.continue_io.recv_timeout(Duration::from_secs(10)).unwrap(); return Err(MemcardIoError::IoError); } self.file.write_at(o, b) } } #[test] fn unceased_io_retains_lock_and_terminal_result_survives_late_return_and_reconcile() { for inside_publication in [false, true] { let f = Fixture::new(MemcardFixture::Write); let file = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| { Card::format(io, id).map_err(|_| MemcardIoError::IoError) }) .unwrap(); let (entered_tx, entered) = mpsc::channel(); let (continue_io, release_rx) = mpsc::channel(); let mut host = HeadlessHost::new(); host.media.path = Some(f.image.clone()); host.media.access = Some(MediaAccess::ReadWrite); host.install_memcard(Box::new(GateStore { file, inside_publication, payload_seen: false, fired: false, entered: entered_tx, continue_io: release_rx, })) .unwrap(); host.boot_with_memcard_choice(f.cart.to_string_lossy(), Choice::Persistent).unwrap(); host.advance_frame().unwrap(); entered.recv_timeout(Duration::from_secs(3)).unwrap(); host.firmware.os.memcard().poll(Instant::now() + Duration::from_secs(2)); let before = host.get_memcard_state(); assert!(before.io.active); assert!(before.recovery.restart_required); assert_eq!( before.request.as_ref().unwrap().state, if inside_publication { "indeterminate" } else { "failure" } ); assert!( matches!(host.shutdown(TeardownPolicy{discard_unsaved:true,..Default::default()}),Err(HostError::Memcard(e)) if e.reason=="restart_required") ); assert!(matches!(FileMemcard::open(&f.image, false), Err(MemcardIoError::Busy))); continue_io.send(()).unwrap(); settle(&mut host); let returned = host.get_memcard_state().request; let original = before.request.as_ref().unwrap(); let late = returned.as_ref().unwrap(); assert_eq!( (&late.id, late.state, late.reason), (&original.id, original.state, original.reason), "late completion cannot rewrite the original result" ); assert_eq!(late.storage_error, Some("io_error")); pause_for_media(&mut host); let restored = host.reconcile_memcard().unwrap(); assert_eq!( restored.request, returned, "recovery must not consume or rewrite the guest result" ); assert!(!restored.recovery.restart_required); host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap(); } }