feat(host): expose memcard controls and qualify process persistence
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good

This commit is contained in:
2026-10-30 10:10:07 +00:00
parent dcf6561ea7
commit a4bec5bc45
42 changed files with 4778 additions and 100 deletions
@@ -64,6 +64,14 @@ impl SystemOS {
pub fn memcard(&mut self) -> &mut MemcardService {
&mut self.memcard
}
/// A successful return confirms the shared worker has stopped and joined.
pub fn stop_background_io(&mut self) -> Result<(), crate::AsyncWorkLaneError> {
if let Some(controller) = &mut self.io_controller {
controller.stop()?;
}
self.io_controller = None;
Ok(())
}
/// Host/player operations are admitted only while gameplay is suspended.
pub fn replace_memcard(
@@ -2,6 +2,7 @@
//! shared IO worker owns storage during a publication. Legacy per-slot files are
//! intentionally neither read nor migrated by this service.
pub mod admission;
pub mod diagnostics;
pub mod guest;
pub mod image;
pub mod session;
@@ -37,6 +37,7 @@ pub struct Admission {
pub state: PreparationState,
pub snapshot_budget: usize,
faulted: bool,
replacement_observation: Option<super::diagnostics::SessionDiagnostics>,
}
impl Default for Admission {
fn default() -> Self {
@@ -48,10 +49,26 @@ impl Default for Admission {
state: PreparationState::Idle,
snapshot_budget: DEFAULT_SNAPSHOT_BUDGET,
faulted: false,
replacement_observation: None,
}
}
}
impl MemcardService {
pub fn session_diagnostics(&self) -> super::diagnostics::SessionDiagnostics {
self.admission.replacement_observation.clone().unwrap_or_else(|| self.session.diagnostics())
}
pub fn preparation_active(&self) -> bool {
self.admission.receiver.is_some()
}
pub fn installed_card_id(&self) -> Option<[u8; 16]> {
self.admission.installed.as_ref().map(|c| c.current().card_id)
}
pub fn cancel_pending(&mut self) {
self.session.cancel_pending();
if let Some(control) = &self.admission.control {
control.cancel();
}
}
pub fn host_faulted(&self) -> bool {
self.admission.faulted || self.session.host_faulted()
}
@@ -60,7 +77,11 @@ impl MemcardService {
}
pub fn installed_health(&self) -> Option<(bool, bool, bool)> {
self.admission.installed.as_ref().map(|card| {
(card.recovered, card.degraded, card.write_blocked || card.storage_read_only())
(
card.recovered,
card.degraded,
card.write_blocked || card.storage_read_only() || card.uncertain,
)
})
}
pub fn card_has_game(&self, app_id: u32) -> bool {
@@ -135,6 +156,9 @@ impl MemcardService {
let owned =
card.catalog.games.iter().find(|g| g.app_id == app_id).map_or(0, |g| g.slots.len());
if choice == Choice::Persistent {
if card.uncertain {
return Err(Error::Indeterminate);
}
if card.storage_read_only() || card.write_blocked {
return Err(Error::ReadOnly);
}
@@ -171,6 +195,10 @@ impl MemcardService {
}
Choice::Persistent => {
let mut card = card.take().unwrap();
if card.uncertain {
session.retain_idle_card(card);
return Err(Error::Indeterminate);
}
if card.storage_read_only() || card.write_blocked {
session.retain_idle_card(card);
return Err(Error::ReadOnly);
@@ -256,9 +284,24 @@ impl MemcardService {
&mut self,
storage: Box<dyn MemcardStorage>,
load_existing: bool,
) -> Result<()> {
self.replace_card_job(move |session, control| {
session.replace_storage(storage, load_existing, control)
})
}
pub fn reconcile_card_with(
&mut self,
open: impl FnOnce() -> Result<Box<dyn MemcardStorage>> + Send + 'static,
) -> Result<()> {
self.replace_card_job(move |session, control| session.reconcile_storage_with(open, control))
}
fn replace_card_job(
&mut self,
operation: impl FnOnce(&mut Session, &PublicationControl) -> Result<()> + Send + 'static,
) -> Result<()> {
if self.admission.receiver.is_some()
|| self.session.has_in_flight()
|| self.session.io_active()
|| self.session.has_deferred_write()
|| self.session.is_boot_active()
{
return Err(Error::Busy);
@@ -266,6 +309,7 @@ impl MemcardService {
if self.admission.faulted {
return Err(Error::ReadOnly);
}
self.admission.replacement_observation = Some(self.session.diagnostics());
let handoff = Arc::new(Mutex::new(Some(std::mem::take(&mut self.session))));
let worker = handoff.clone();
let control = Arc::new(PublicationControl::default());
@@ -275,13 +319,14 @@ impl MemcardService {
.lane
.submit_memcard_commit_write(move |_| {
let mut session = worker.lock().unwrap().take().unwrap();
let result = session.replace_storage(storage, load_existing, &worker_control);
let result = operation(&mut session, &worker_control);
let _ = tx.send(Prepared::Replacement(session, result));
crate::AsyncWorkJobOutcome::Completed
})
.is_err()
{
self.session = handoff.lock().unwrap().take().unwrap();
self.admission.replacement_observation = None;
return Err(Error::InvalidState);
}
self.admission.control = Some(control);
@@ -331,6 +376,7 @@ impl MemcardService {
}
self.admission.receiver = None;
self.admission.control = None;
self.admission.replacement_observation = None;
}
Err(mpsc::TryRecvError::Disconnected) => {
self.admission.state = PreparationState::Failed(Error::InvalidState);
@@ -361,3 +407,37 @@ impl MemcardService {
}
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use prometeu_drivers::memcard::FileMemcard;
use prometeu_hal::memcard::MemcardIoError;
#[test]
fn idle_uncertain_media_remains_blocked_before_another_persistent_admission() {
let path = std::env::temp_dir().join(format!(
"memcard-uncertain-idle-{}-{}",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
));
let io = FileMemcard::create(&path, IMAGE_BYTES, |io, id| {
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
})
.unwrap();
let mut card = Card::mount(Box::new(io)).unwrap();
card.uncertain = true;
let mut service = MemcardService::new();
// An ended session returns its backend to the same installed-card state.
service.admission.installed = Some(card);
assert_eq!(service.installed_health(), Some((false, false, true)));
assert_eq!(
service.choose_for_game(42, 1, Choice::Persistent, 0),
Err(Error::Indeterminate)
);
assert!(service.card_installed());
assert_eq!(service.lane.pending_depth(), 0);
service.uninstall_card().unwrap();
std::fs::remove_file(path).unwrap();
}
}
@@ -0,0 +1,31 @@
//! Read-only native observations. These do not consume the guest request entry.
use super::{
image::Error,
session::{Mode, RequestResult},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestDiagnostics {
pub result: RequestResult,
pub storage_error: Option<Error>,
pub slot: Option<usize>,
pub operation: &'static str,
pub retained: bool,
pub io_active: bool,
pub deferred: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionDiagnostics {
pub app_id: Option<u32>,
pub card_id: Option<[u8; 16]>,
pub epoch: u64,
pub mode: Option<Mode>,
pub health: (bool, bool, bool),
pub dirty_slots: Vec<usize>,
pub request: Option<RequestDiagnostics>,
pub io_active: bool,
pub removal_pending: bool,
pub reconciliation_required: bool,
pub restart_required: bool,
}
@@ -31,12 +31,14 @@ pub fn status(e: Error) -> i64 {
use prometeu_hal::memcard::MemcardIoError as I;
match e {
Error::NoSpace | Error::Io(I::NoSpace) => 3,
Error::AccessDenied => 4,
Error::AccessDenied
| Error::IdentityMismatch
| Error::Io(I::AccessDenied | I::AlreadyExists) => 4,
Error::Corrupt => 5,
Error::Indeterminate => 6,
Error::Indeterminate | Error::Io(I::Indeterminate) => 6,
Error::Io(I::Unavailable) => 7,
Error::InvalidState | Error::Canceled => 8,
Error::Busy => 9,
Error::Busy | Error::Io(I::Busy) => 9,
Error::ReadOnly | Error::CounterExhausted | Error::Io(I::ReadOnly) => 10,
Error::InvalidRange | Error::Io(I::InvalidRange) => 11,
Error::Unsupported | Error::Io(I::Unsupported) => 12,
@@ -29,6 +29,7 @@ pub enum Error {
OutOfMemory,
AccessDenied,
InvalidState,
IdentityMismatch,
}
impl From<MemcardIoError> for Error {
fn from(e: MemcardIoError) -> Self {
@@ -71,12 +71,14 @@ struct Request {
job: AsyncWorkJobId,
released: bool,
saves_payload: bool,
worker_returned: bool,
}
/// Main-lane control; the Card moves into the single worker while its source is protected.
#[derive(Default)]
pub struct Session {
card_id: Option<[u8; 16]>,
uncertain_target: Option<Map>,
known_card_exclusions: Option<([u8; 16], [bool; BLOCK_COUNT])>,
health: (bool, bool, bool),
context: u64,
epoch: u64,
@@ -100,6 +102,82 @@ pub struct Session {
deferred: Option<(u64, usize, u64, Instant)>,
}
impl Session {
/// IO ownership, independent of a completed result retained for guest release.
pub fn io_active(&self) -> bool {
self.request.as_ref().is_some_and(|r| !r.worker_returned)
}
pub fn has_deferred_write(&self) -> bool {
self.deferred.is_some()
}
pub fn cancel_pending(&mut self) {
if let Some(r) = &self.request {
r.control.cancel();
}
if let Some((id, local, ..)) = self.deferred.take() {
self.slots[local].protected = false;
self.memory_result = Some(RequestResult {
id,
state: RequestState::Failure,
reason: RequestReason::Storage(Error::Canceled),
});
}
}
pub fn diagnostics(&self) -> super::diagnostics::SessionDiagnostics {
use super::diagnostics::{RequestDiagnostics, SessionDiagnostics};
let request = if let Some((id, local, ..)) = self.deferred {
Some(RequestDiagnostics {
result: RequestResult {
id,
state: RequestState::Pending,
reason: RequestReason::None,
},
storage_error: None,
slot: Some(local),
operation: "commit",
retained: true,
io_active: false,
deferred: true,
})
} else if let Some(r) = &self.request {
Some(RequestDiagnostics {
result: r.result,
storage_error: r.worker_error,
slot: r.saves_payload.then_some(r.local),
operation: if r.saves_payload { "commit" } else { "presentation" },
retained: !r.released,
io_active: self.io_active(),
deferred: false,
})
} else {
self.memory_result.map(|result| RequestDiagnostics {
result,
storage_error: None,
slot: None,
operation: "commit",
retained: true,
io_active: false,
deferred: false,
})
};
SessionDiagnostics {
app_id: self.mode.map(|_| self.app_id),
card_id: self.card_id,
epoch: self.epoch,
mode: self.mode,
health: self.health(),
dirty_slots: self
.slots
.iter()
.enumerate()
.filter_map(|(i, s)| s.data.read().ok().filter(|s| s.dirty).map(|_| i))
.collect(),
request,
io_active: self.io_active(),
removal_pending: self.removal_pending,
reconciliation_required: self.reconcile_blocked,
restart_required: self.faulted,
}
}
pub fn context(&self) -> u64 {
self.context
}
@@ -531,6 +609,7 @@ impl Session {
job,
released: !saves_payload,
saves_payload,
worker_returned: false,
});
Ok(())
}
@@ -674,6 +753,7 @@ impl Session {
job,
released: false,
saves_payload: true,
worker_returned: false,
});
Ok(id)
}
@@ -692,6 +772,7 @@ impl Session {
let Some(r) = &mut self.request else { return };
match r.receiver.try_recv() {
Ok(completion) => {
r.worker_returned = true;
r.worker_error = completion.result.error;
let current =
self.mode.is_some() && r.session == self.context && r.epoch == self.epoch;
@@ -819,7 +900,7 @@ impl Session {
return Err(Error::Busy);
}
r.released = true;
if self.card.is_some() {
if r.worker_returned {
self.request = None;
}
Ok(())
@@ -833,7 +914,7 @@ impl Session {
r.control.cancel();
r.released = true;
}
if self.card.is_some() {
if !self.io_active() {
self.request = None;
}
self.removal_pending = false;
@@ -869,7 +950,23 @@ impl Session {
load_existing: bool,
control: &PublicationControl,
) -> Result<()> {
if self.has_in_flight() || self.boot_active || self.mode.is_none() {
self.replace_storage_with(move || Ok(storage), load_existing, false, control)
}
pub(super) fn reconcile_storage_with(
&mut self,
open: impl FnOnce() -> Result<Box<dyn prometeu_hal::memcard::MemcardStorage>>,
control: &PublicationControl,
) -> Result<()> {
self.replace_storage_with(open, false, true, control)
}
fn replace_storage_with(
&mut self,
open: impl FnOnce() -> Result<Box<dyn prometeu_hal::memcard::MemcardStorage>>,
load_existing: bool,
same_only: bool,
control: &PublicationControl,
) -> Result<()> {
if self.io_active() || self.deferred.is_some() || self.boot_active || self.mode.is_none() {
return Err(Error::Busy);
}
if self.icon.is_empty()
@@ -882,11 +979,18 @@ impl Session {
{
self.uncertain_target = card.attempted_publication.clone();
}
let known = self.card.as_ref().map(|c| (c.current().card_id, c.known_exclusions()));
if let Some(card) = &self.card {
self.known_card_exclusions = Some((card.current().card_id, card.known_exclusions()));
}
let known = self.known_card_exclusions;
self.card.take(); // Release the old scratch before mounting another image.
self.scratch = None;
self.reconcile_blocked = true;
self.card = Some(Card::mount(storage)?);
let candidate = Card::mount(open()?)?;
if same_only && self.card_id != Some(candidate.current().card_id) {
return Err(Error::IdentityMismatch);
}
self.card = Some(candidate);
let card = self.card.as_mut().unwrap();
let same = self.card_id == Some(card.current().card_id);
if let Some((id, known)) = known
@@ -973,14 +1077,15 @@ impl Session {
Ok(())
}
pub fn detach(&mut self) -> Result<()> {
if self.deferred.is_some()
|| self
.request
.as_ref()
.is_some_and(|r| r.result.state == RequestState::Pending || self.card.is_none())
{
if self.deferred.is_some() || self.io_active() {
return Err(Error::Busy);
}
if self.card.is_none() && self.scratch.is_none() {
let mut scratch = Vec::new();
scratch.try_reserve_exact(SLOT_BYTES).map_err(|_| Error::OutOfMemory)?;
scratch.resize(SLOT_BYTES, 0);
self.scratch = Some(scratch);
}
self.mode = Some(Mode::MemoryOnly);
self.removal_pending = false;
self.reconcile_blocked = false;