Compare commits
10
Commits
dcf6561ea7
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a32f834b2b
|
||
|
|
f1adf86dd5
|
||
|
|
2d5735cb13
|
||
|
|
dccf4d0775
|
||
|
|
c3589be1ad
|
||
|
|
49d7fca0b7
|
||
|
|
c649e02816
|
||
|
|
09d8778f04
|
||
|
|
1aa939eca8 | ||
|
|
a4bec5bc45
|
@@ -13,9 +13,10 @@ jobs:
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy, llvm-tools-preview
|
||||
- name: Install repository Rust toolchain
|
||||
run: |
|
||||
toolchain=$(python3 -c 'import tomllib; print(tomllib.load(open("rust-toolchain.toml", "rb"))["toolchain"]["channel"])')
|
||||
rustup toolchain install "$toolchain" --profile minimal
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
|
||||
@@ -66,7 +66,3 @@ AGENTS.md
|
||||
|
||||
.python-version
|
||||
.venv
|
||||
|
||||
discussion/*
|
||||
!discussion/lessons/
|
||||
!discussion/lessons/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.PHONY: fmt fmt-check clippy test-local test-debugger-socket clean coverage coverage-xml coverage-json coverage-report-json coverage-domain-list coverage-domain-evidence coverage-domain-audit coverage-domain-gate test ci ci-domains cobertura
|
||||
.PHONY: fmt fmt-check clippy test-unit test-local test-integration test-debugger-socket clean coverage coverage-xml coverage-json coverage-report-json coverage-domain-list coverage-domain-evidence coverage-domain-audit coverage-domain-gate test ci ci-domains cobertura
|
||||
|
||||
fmt:
|
||||
cargo fmt --all
|
||||
@@ -9,8 +9,15 @@ fmt-check:
|
||||
clippy:
|
||||
cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
|
||||
test-local:
|
||||
cargo test --workspace --all-targets --all-features --no-fail-fast
|
||||
test-unit:
|
||||
cargo test --workspace --lib --bins --all-features --no-fail-fast
|
||||
|
||||
# Compatibility entry point: repository-local verification is unit-only.
|
||||
test-local: test-unit
|
||||
|
||||
# Explicit opt-in, orchestrated by ../tooling; test sources stay in this repository.
|
||||
test-integration:
|
||||
cargo test --workspace --tests --all-features --no-fail-fast
|
||||
|
||||
test-debugger-socket:
|
||||
cargo test -p prometeu-host-desktop-winit --lib runner::tests -- --ignored
|
||||
@@ -19,7 +26,7 @@ clean:
|
||||
cargo llvm-cov clean --workspace
|
||||
|
||||
coverage:
|
||||
cargo llvm-cov --workspace --all-features --html --output-dir target/llvm-cov
|
||||
cargo llvm-cov --workspace --lib --bins --all-features --html --output-dir target/llvm-cov
|
||||
|
||||
coverage-report-json:
|
||||
cargo llvm-cov report --json --output-path target/llvm-cov/report.json
|
||||
@@ -46,9 +53,9 @@ coverage-domain-evidence:
|
||||
coverage-domain-gate:
|
||||
./scripts/coverage-domain-evidence.sh --check-all
|
||||
|
||||
test: fmt-check clippy test-local test-debugger-socket
|
||||
test: fmt-check clippy test-unit
|
||||
# Local and GitHub entry point; Jenkins exposes the same targets as stages.
|
||||
CI_DOMAIN_STEPS = clean fmt-check clippy test-local test-debugger-socket coverage coverage-report-json coverage-xml coverage-json coverage-domain-audit coverage-domain-gate
|
||||
CI_DOMAIN_STEPS = clean fmt-check clippy test-unit coverage coverage-report-json coverage-xml coverage-json coverage-domain-audit coverage-domain-gate
|
||||
|
||||
ci: ci-domains
|
||||
ci-domains:
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# PROMETEU Runtime
|
||||
|
||||
PROMETEU is an educational and experimental fantasy handheld / fantasy console.
|
||||
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, firmware/system services, host integration, CLI entrypoints, development utilities, specs, and discussion artifacts.
|
||||
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, firmware/system services, host integration, CLI entrypoints, development utilities, specs, and engineering lessons.
|
||||
|
||||
The VM is only one subsystem of the machine. The canonical docs in this repository intentionally distinguish:
|
||||
|
||||
- machine-level specs;
|
||||
- VM/runtime internal architecture;
|
||||
- implementation crates;
|
||||
- discussion workflow and lessons learned.
|
||||
- engineering lessons learned.
|
||||
|
||||
## What This Repository Contains
|
||||
|
||||
@@ -19,7 +19,7 @@ The VM is only one subsystem of the machine. The canonical docs in this reposito
|
||||
- `docs/specs/runtime/`: canonical PROMETEU machine specs
|
||||
- `docs/vm-arch/`: canonical VM/runtime architecture and ISA references
|
||||
- `devtools/`: debugger protocol material
|
||||
- `discussion/`: agendas, decisions, plans, and lessons for architectural work
|
||||
- `discussion/lessons/`: published engineering lessons and supporting assets
|
||||
- `test-cartridges/`: cartridge fixtures used for validation and manual runs
|
||||
|
||||
## Canonical Documentation
|
||||
@@ -29,7 +29,11 @@ Use these entrypoints instead of inferring the model from isolated source files:
|
||||
- [Machine specs](docs/specs/runtime/README.md): authoritative contract for the PROMETEU machine, peripherals, firmware, cartridge format, timing, and host ABI
|
||||
- [VM architecture](docs/vm-arch/ARCHITECTURE.md): authoritative internal architecture for VM/runtime invariants
|
||||
- [ISA reference](docs/vm-arch/ISA_CORE.md): bytecode-level instruction set authority
|
||||
- [Discussion workflow](discussion/index.ndjson): architectural agenda, decision, and execution traceability
|
||||
- [Engineering lessons](discussion/lessons/): published results and rationale
|
||||
|
||||
Engineering discussions, decisions, plans and execution evidence are maintained in
|
||||
the enclosing [Prometeu Engineering workspace](../README.md) using
|
||||
[AI Engineering](../.ai-engineering/README.md).
|
||||
|
||||
## Workspace Layout
|
||||
|
||||
@@ -60,11 +64,21 @@ Other ecosystem commands, such as build, pack, and verification tooling, are not
|
||||
|
||||
## Requirements
|
||||
|
||||
- Rust toolchain from [rust-toolchain.toml](rust-toolchain.toml)
|
||||
- Rust **1.98.1**, pinned in [rust-toolchain.toml](rust-toolchain.toml)
|
||||
- `rustup` for toolchain installation and management
|
||||
- `cargo-llvm-cov` for coverage targets such as `make coverage` and `make ci-domains`
|
||||
- a local graphical environment for desktop runtime commands
|
||||
|
||||
From the repository root, install and verify the pinned toolchain:
|
||||
|
||||
```bash
|
||||
rustup toolchain install 1.98.1 --profile minimal --component rustfmt,clippy
|
||||
rustc --version
|
||||
```
|
||||
|
||||
Rustup selects the pinned version automatically for commands run in this repository.
|
||||
CI installs the toolchain from the same file.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Build the workspace:
|
||||
@@ -119,7 +133,14 @@ The authoritative target used by both GitHub and Jenkins is:
|
||||
make ci-domains
|
||||
```
|
||||
|
||||
The five debugger socket tests bind localhost sockets and are marked ignored in Rust test metadata; both `make test` and `make ci-domains` select only `runner::tests` through `test-debugger-socket`. Physical audio and other manual probes remain opt-in. See [quality-gate prerequisites and commands](docs/vm-arch/COVERAGE_DOMAINS.md#commands-and-ci).
|
||||
`make test-unit` selects library and binary unit-test harnesses with
|
||||
`--lib --bins --all-features`; `test-local` remains an alias. Both `make test`
|
||||
and `make ci-domains` run only this suite. Integration targets under `tests/`,
|
||||
installed-process qualification and the five ignored debugger socket tests are
|
||||
excluded from the pipeline. They remain available explicitly through
|
||||
`make test-integration` and `make test-debugger-socket`, orchestrated by
|
||||
`../tooling`. Tests and fixtures stay in this repository. Physical audio and manual probes remain opt-in. See
|
||||
[quality-gate prerequisites and commands](docs/vm-arch/COVERAGE_DOMAINS.md#commands-and-ci).
|
||||
|
||||
## Coverage Governance
|
||||
|
||||
@@ -156,7 +177,7 @@ make coverage-domain-evidence DOMAIN=host/headless
|
||||
```
|
||||
|
||||
`make ci-domains` runs formatting, strict workspace/all-target/all-feature Clippy,
|
||||
all-target tests, the five debugger socket tests, fresh coverage and every domain
|
||||
library/binary unit tests, fresh unit-only coverage and every domain
|
||||
ownership/evidence gate. Both CI providers archive available evidence on failure.
|
||||
A failing run never lowers a configured floor; local and CI checks use the same
|
||||
repository-owned commands. Reports identify their revision, source/configuration
|
||||
@@ -173,7 +194,7 @@ Improving the global percentage alone is not sufficient review evidence when the
|
||||
|
||||
The project is still in active architectural and implementation convergence.
|
||||
|
||||
- the machine contract is being clarified through the specs and discussion workflow;
|
||||
- the machine contract is being clarified through the specs and AI Engineering;
|
||||
- the workspace already contains concrete runtime and host code;
|
||||
- the CLI dispatcher currently exposes the runtime paths that are backed by binaries in this workspace.
|
||||
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
//! Controlled graphics measurement. This is not a cartridge stress-suite replacement.
|
||||
use prometeu_drivers::{Gfx, GlyphBankPoolInstaller, MemoryBanks, hardware::Hardware};
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::glyph::Glyph;
|
||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
||||
use prometeu_hal::scene_bank::SceneBank;
|
||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
||||
use prometeu_hal::scene_viewport_resolver::SceneViewportResolver;
|
||||
use prometeu_hal::sprite::Sprite;
|
||||
use prometeu_hal::tile::Tile;
|
||||
use prometeu_hal::tilemap::TileMap;
|
||||
use prometeu_hal::{FrameId, OwnedRgba8888Frame, RenderOwnership, app_mode::AppMode};
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use std::time::Instant;
|
||||
|
||||
struct CountingAllocator;
|
||||
static LIVE: AtomicUsize = AtomicUsize::new(0);
|
||||
static PEAK: AtomicUsize = AtomicUsize::new(0);
|
||||
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
// Only the measurement executable pays the atomic allocation instrumentation cost.
|
||||
unsafe impl GlobalAlloc for CountingAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
let ptr = unsafe { System.alloc(layout) };
|
||||
if !ptr.is_null() {
|
||||
let live = LIVE.fetch_add(layout.size(), Ordering::Relaxed) + layout.size();
|
||||
PEAK.fetch_max(live, Ordering::Relaxed);
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
ptr
|
||||
}
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
LIVE.fetch_sub(layout.size(), Ordering::Relaxed);
|
||||
unsafe { System.dealloc(ptr, layout) };
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CountingAllocator = CountingAllocator;
|
||||
|
||||
fn summary(samples: &mut [u64]) -> serde_json::Value {
|
||||
samples.sort_unstable();
|
||||
let n = samples.len();
|
||||
serde_json::json!({"mean_us": samples.iter().sum::<u64>() as f64 / n as f64 / 1000.0,
|
||||
"p95_us": samples[(n * 95).div_ceil(100) - 1] as f64 / 1000.0,
|
||||
"p99_us": samples[(n * 99).div_ceil(100) - 1] as f64 / 1000.0,
|
||||
"max_us": samples[n-1] as f64 / 1000.0,
|
||||
"over_60hz_budget": samples.iter().filter(|&&v| v > 1_000_000_000 / 60).count()})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let count: usize =
|
||||
std::env::args().nth(1).map(|v| v.parse().expect("frame count")).unwrap_or(600);
|
||||
assert!(count > 0);
|
||||
let (w, h) = (Hardware::W, Hardware::H);
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
let mixed = std::env::args().nth(2).as_deref() == Some("mixed");
|
||||
let sizes = if mixed {
|
||||
[TileSize::Size8, TileSize::Size16, TileSize::Size32, TileSize::Size8]
|
||||
} else {
|
||||
[TileSize::Size16; 4]
|
||||
};
|
||||
for (i, size) in sizes.iter().enumerate() {
|
||||
let edge = *size as usize;
|
||||
let mut bank = GlyphBank::new(*size, edge, edge);
|
||||
bank.palettes[0][1] = Color::rgba((i * 47 + 30) as u8, 120, 210, 255);
|
||||
// Transparent holes make all four layers participate in the visible output.
|
||||
for (p, pixel) in bank.pixel_indices.iter_mut().enumerate() {
|
||||
*pixel = u8::from(i == 0 || (p + i) % 3 != 0);
|
||||
}
|
||||
banks.install_glyph_bank(i, Arc::new(bank));
|
||||
}
|
||||
let scene = SceneBank {
|
||||
layers: std::array::from_fn(|i| SceneLayer {
|
||||
active: true,
|
||||
glyph_asset_id: i as i32,
|
||||
tile_size: sizes[i],
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap {
|
||||
width: 160,
|
||||
height: 100,
|
||||
tiles: vec![
|
||||
Tile {
|
||||
active: true,
|
||||
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
};
|
||||
160 * 100
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
let min_tile = if mixed { 8 } else { 16 };
|
||||
let (cw, ch) = (w.div_ceil(min_tile) + 5, h.div_ceil(min_tile) + 4);
|
||||
let mut cache = SceneViewportCache::new(&scene, cw, ch);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
w as i32,
|
||||
h as i32,
|
||||
cw,
|
||||
ch,
|
||||
min_tile as i32 - 4,
|
||||
min_tile as i32 + 4,
|
||||
);
|
||||
let mut gfx = Gfx::new(w, h, banks);
|
||||
let sprites: Vec<_> = (0..512)
|
||||
.map(|i| Sprite {
|
||||
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||
x: ((i * 37) % w) as i32,
|
||||
y: ((i * 53) % h) as i32,
|
||||
layer: (i % 4) as u8,
|
||||
bank_id: (i % 4) as u8,
|
||||
active: true,
|
||||
flip_x: i % 2 == 0,
|
||||
flip_y: i % 3 == 0,
|
||||
priority: (i % 4) as u8,
|
||||
})
|
||||
.collect();
|
||||
gfx.load_frame_sprites(&sprites);
|
||||
let mut compose = Vec::with_capacity(count);
|
||||
let mut publish = Vec::with_capacity(count);
|
||||
let mut upload = Vec::with_capacity(count);
|
||||
let mut total = Vec::with_capacity(count);
|
||||
let mut rgba = vec![0u8; w * h * 4];
|
||||
let ownership = RenderOwnership::new(1, AppMode::Game, 1);
|
||||
let mut checksum = 0u32;
|
||||
for frame_id in 0..(count + 120) {
|
||||
// Resolve/materialize cache outside the raster timing; total includes it.
|
||||
let start = Instant::now();
|
||||
let update = resolver.update(&scene, (frame_id % 71) as i32, (frame_id % 43) as i32);
|
||||
for request in &update.copy_requests {
|
||||
cache.move_layer_window_to(
|
||||
request.layer_index,
|
||||
request.cache_origin_tile_x,
|
||||
request.cache_origin_tile_y,
|
||||
);
|
||||
}
|
||||
cache.materialize_all_layers(&scene);
|
||||
let t = Instant::now();
|
||||
gfx.render_scene_from_cache(&cache, &update, &[0, 1, 2, 3]);
|
||||
gfx.fill_rect(0, h as i32 - 8, w as i32, 8, Color::WHITE);
|
||||
let raster = t.elapsed().as_nanos() as u64;
|
||||
let t = Instant::now();
|
||||
gfx.present();
|
||||
let frame = OwnedRgba8888Frame::packed(
|
||||
FrameId::new(frame_id as u64),
|
||||
ownership,
|
||||
w,
|
||||
h,
|
||||
gfx.front_buffer().to_vec(),
|
||||
)
|
||||
.unwrap();
|
||||
let publication = t.elapsed().as_nanos() as u64;
|
||||
let t = Instant::now();
|
||||
for (pixel, bytes) in frame.pixels.iter().zip(rgba.as_chunks_mut::<4>().0.iter_mut()) {
|
||||
bytes.copy_from_slice(&pixel.to_be_bytes());
|
||||
}
|
||||
std::hint::black_box(&rgba);
|
||||
let staging = t.elapsed().as_nanos() as u64;
|
||||
checksum ^= frame.pixels[(frame_id * 173) % (w * h)];
|
||||
if frame_id >= 120 {
|
||||
compose.push(raster);
|
||||
publish.push(publication);
|
||||
upload.push(staging);
|
||||
total.push(start.elapsed().as_nanos() as u64);
|
||||
}
|
||||
}
|
||||
let live = LIVE.load(Ordering::Relaxed);
|
||||
let peak = PEAK.load(Ordering::Relaxed);
|
||||
let allocations = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"schema":1,"width":w,"height":h,"frames":count,
|
||||
"warmup_frames":120,"tiles":sizes.map(|s|s as u32),"sprites_accepted":512,"layers":4,
|
||||
"framebuffer_bytes":w*h*4,"front_back_bytes":w*h*8,"host_staging_bytes":rgba.len(),
|
||||
"compose":summary(&mut compose),"publish_owned":summary(&mut publish),
|
||||
"rgba_staging":summary(&mut upload),"total":summary(&mut total),
|
||||
"allocated_live_bytes":live,"allocated_peak_bytes":peak,"allocation_count":allocations,
|
||||
"checksum":checksum,"vm_hz":null,"physical_display_hz":null,
|
||||
"limitations":"unpaced controlled raster/cache/owned publication/staging; no VM, IPC or GPU present; allocator instrumented; RSS is measured by the process wrapper"})
|
||||
);
|
||||
}
|
||||
@@ -664,7 +664,7 @@ mod tests {
|
||||
assert!(frame_composer.bind_scene(0));
|
||||
|
||||
let cache = frame_composer.cache().expect("cache should exist for bound scene");
|
||||
assert_eq!((cache.width(), cache.height()), (65, 38));
|
||||
assert_eq!((cache.width(), cache.height()), (85, 49));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -43,6 +43,8 @@ pub struct Gfx {
|
||||
front: Vec<u32>,
|
||||
/// Back buffer: the working buffer where canonical game frames are composed
|
||||
back: Vec<u32>,
|
||||
/// Complete local framebuffer publications, including native Hub/Shell output.
|
||||
publication_count: u64,
|
||||
|
||||
/// Shared access to graphical memory banks (tiles and palettes).
|
||||
pub glyph_banks: Arc<dyn GlyphBankPoolAccess>,
|
||||
@@ -321,6 +323,7 @@ impl Gfx {
|
||||
h,
|
||||
front: vec![0; len],
|
||||
back: vec![0; len],
|
||||
publication_count: 0,
|
||||
glyph_banks,
|
||||
sprites: [EMPTY_SPRITE; 512],
|
||||
sprite_count: 0,
|
||||
@@ -570,6 +573,11 @@ impl Gfx {
|
||||
/// Typically called by the Host when it's time to display the finished frame.
|
||||
pub fn present(&mut self) {
|
||||
std::mem::swap(&mut self.front, &mut self.back);
|
||||
self.publication_count = self.publication_count.wrapping_add(1);
|
||||
}
|
||||
|
||||
pub fn publication_count(&self) -> u64 {
|
||||
self.publication_count
|
||||
}
|
||||
|
||||
pub fn load_frame_sprites(&mut self, sprites: &[Sprite]) {
|
||||
|
||||
@@ -28,7 +28,7 @@ use std::sync::Arc;
|
||||
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
||||
///
|
||||
/// ### Console Specifications:
|
||||
/// - **Resolution**: 480x270 (16:9 Aspect Ratio).
|
||||
/// - **Resolution**: 640x360 (16:9 Aspect Ratio).
|
||||
/// - **Color Format**: RGBA8888.
|
||||
/// - **Audio**: Stereo, Command-based mixing.
|
||||
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
|
||||
@@ -201,9 +201,9 @@ impl RuntimePlatform for Hardware {
|
||||
|
||||
impl Hardware {
|
||||
/// Internal hardware width in pixels.
|
||||
pub const W: usize = 480;
|
||||
pub const W: usize = prometeu_hal::graphics_contract::WIDTH;
|
||||
/// Internal hardware height in pixels.
|
||||
pub const H: usize = 270;
|
||||
pub const H: usize = prometeu_hal::graphics_contract::HEIGHT;
|
||||
|
||||
/// Creates a fresh hardware instance with default settings.
|
||||
pub fn new(wall_clock: Arc<dyn WallClock>) -> Self {
|
||||
|
||||
@@ -5,6 +5,8 @@ mod gfx;
|
||||
pub mod hardware;
|
||||
mod local_render_backend;
|
||||
mod memory_banks;
|
||||
#[cfg(test)]
|
||||
mod native_graphics_tests;
|
||||
mod pad;
|
||||
mod test_platform;
|
||||
mod touch;
|
||||
|
||||
@@ -13,7 +13,8 @@ fn io_error(e: std::io::Error) -> Error {
|
||||
use std::io::ErrorKind as K;
|
||||
match e.kind() {
|
||||
K::NotFound => Error::Unavailable,
|
||||
K::PermissionDenied => Error::ReadOnly,
|
||||
K::PermissionDenied => Error::AccessDenied,
|
||||
K::AlreadyExists => Error::AlreadyExists,
|
||||
K::StorageFull => Error::NoSpace,
|
||||
K::InvalidInput | K::UnexpectedEof => Error::InvalidRange,
|
||||
K::Unsupported => Error::Unsupported,
|
||||
@@ -21,8 +22,15 @@ fn io_error(e: std::io::Error) -> Error {
|
||||
}
|
||||
}
|
||||
impl FileMemcard {
|
||||
fn lock(file: &File) -> Result<(), Error> {
|
||||
file.try_lock().map_err(|error| match error {
|
||||
std::fs::TryLockError::WouldBlock => Error::Busy,
|
||||
std::fs::TryLockError::Error(error) => io_error(error),
|
||||
})
|
||||
}
|
||||
pub fn open(path: &Path, read_only: bool) -> Result<Self, Error> {
|
||||
let file = OpenOptions::new().read(true).write(!read_only).open(path).map_err(io_error)?;
|
||||
Self::lock(&file)?;
|
||||
let length = file.metadata().map_err(io_error)?.len();
|
||||
Ok(Self { file, length, read_only })
|
||||
}
|
||||
@@ -47,7 +55,9 @@ impl FileMemcard {
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.map_err(io_error)?;
|
||||
let mut published = false;
|
||||
let result = (|| {
|
||||
Self::lock(&file)?;
|
||||
let mut card = Self { file, length, read_only: false };
|
||||
let zeros = [0u8; 65_536];
|
||||
let mut offset = 0;
|
||||
@@ -64,6 +74,7 @@ impl FileMemcard {
|
||||
card.sync()?;
|
||||
// hard_link publishes without replacing a user file; parent sync makes the name durable.
|
||||
std::fs::hard_link(&temporary, path).map_err(io_error)?;
|
||||
published = true;
|
||||
File::open(parent).and_then(|f| f.sync_all()).map_err(io_error)?;
|
||||
Ok(card)
|
||||
})();
|
||||
@@ -71,10 +82,10 @@ impl FileMemcard {
|
||||
std::fs::remove_file(&temporary).and_then(|()| File::open(parent)?.sync_all());
|
||||
match result {
|
||||
Ok(card) => {
|
||||
cleanup.map_err(io_error)?;
|
||||
cleanup.map_err(|_| Error::Indeterminate)?;
|
||||
Ok(card)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(e) => Err(if published { Error::Indeterminate } else { e }),
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
use crate::{Gfx, GlyphBankPoolInstaller, MemoryBanks};
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_hal::glyph::Glyph;
|
||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
||||
use prometeu_hal::graphics_contract::{FRAME_BYTES, HEIGHT, PIXELS, WIDTH};
|
||||
use prometeu_hal::scene_bank::SceneBank;
|
||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
||||
use prometeu_hal::scene_viewport_resolver::SceneViewportResolver;
|
||||
use prometeu_hal::tile::Tile;
|
||||
use prometeu_hal::tilemap::TileMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn native_allocation_stride_corners_and_external_coordinates() {
|
||||
let mut gfx = Gfx::new(WIDTH, HEIGHT, Arc::new(MemoryBanks::new()));
|
||||
assert_eq!(gfx.publication_count(), 0);
|
||||
gfx.clear(Color::BLACK);
|
||||
for (x, y) in [(0, 0), (639, 0), (0, 359), (639, 359)] {
|
||||
gfx.draw_pixel(x, y, Color::RED);
|
||||
}
|
||||
for (x, y) in [(-1, 0), (640, 359), (639, 360), (0, -1)] {
|
||||
gfx.draw_pixel(x, y, Color::GREEN);
|
||||
}
|
||||
assert_eq!(gfx.publication_count(), 0, "drawing is not a complete publication");
|
||||
gfx.present();
|
||||
assert_eq!(gfx.publication_count(), 1);
|
||||
let front = gfx.front_buffer();
|
||||
assert_eq!(gfx.size(), (640, 360));
|
||||
assert_eq!(front.len(), PIXELS);
|
||||
assert_eq!(std::mem::size_of_val(front), FRAME_BYTES);
|
||||
for index in [0, 639, 359 * WIDTH, PIXELS - 1] {
|
||||
assert_eq!(front[index], Color::RED.raw());
|
||||
}
|
||||
assert_eq!(front.iter().filter(|&&p| p == Color::RED.raw()).count(), 4);
|
||||
gfx.present();
|
||||
assert_eq!(gfx.publication_count(), 2, "each complete swap is a publication");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_tile_edges_and_mixed_camera_layers_cover_every_corner() {
|
||||
for sizes in [
|
||||
[TileSize::Size8; 4],
|
||||
[TileSize::Size16; 4],
|
||||
[TileSize::Size32; 4],
|
||||
[TileSize::Size8, TileSize::Size16, TileSize::Size32, TileSize::Size8],
|
||||
] {
|
||||
let banks = Arc::new(MemoryBanks::new());
|
||||
let colors = [Color::RED, Color::GREEN, Color::BLUE, Color::WHITE];
|
||||
for i in 0..4 {
|
||||
let n = sizes[i] as usize;
|
||||
let mut bank = GlyphBank::new(sizes[i], n, n);
|
||||
bank.palettes[0][1] = colors[i];
|
||||
bank.pixel_indices.fill(1);
|
||||
banks.install_glyph_bank(i, Arc::new(bank));
|
||||
}
|
||||
let scene = SceneBank {
|
||||
layers: std::array::from_fn(|i| SceneLayer {
|
||||
active: true,
|
||||
glyph_asset_id: i as i32,
|
||||
tile_size: sizes[i],
|
||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||
tilemap: TileMap {
|
||||
width: 160,
|
||||
height: 120,
|
||||
tiles: vec![
|
||||
Tile {
|
||||
active: true,
|
||||
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||
flip_x: true,
|
||||
flip_y: true,
|
||||
};
|
||||
160 * 120
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
let min = sizes.iter().map(|s| *s as usize).min().unwrap();
|
||||
let (cw, ch) = (WIDTH.div_ceil(min) + 5, HEIGHT.div_ceil(min) + 4);
|
||||
let mut cache = SceneViewportCache::new(&scene, cw, ch);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
WIDTH as i32,
|
||||
HEIGHT as i32,
|
||||
cw,
|
||||
ch,
|
||||
min as i32 - 4,
|
||||
min as i32 + 4,
|
||||
);
|
||||
let mut gfx = Gfx::new(WIDTH, HEIGHT, banks);
|
||||
for (x, y) in [(0, 0), (1, 1), (7, 7), (15, 15), (31, 31), (400, 300), (2, 3)] {
|
||||
let update = resolver.update(&scene, x, y);
|
||||
for request in &update.copy_requests {
|
||||
cache.move_layer_window_to(
|
||||
request.layer_index,
|
||||
request.cache_origin_tile_x,
|
||||
request.cache_origin_tile_y,
|
||||
);
|
||||
}
|
||||
cache.materialize_all_layers(&scene);
|
||||
gfx.render_scene_from_cache(&cache, &update, &[0, 1, 2, 3]);
|
||||
gfx.present();
|
||||
// Every pixel, including rows 352..359, must be supplied by the last layer.
|
||||
assert!(
|
||||
gfx.front_buffer().iter().all(|&p| p == Color::WHITE.raw()),
|
||||
"sizes={sizes:?}, camera=({x},{y})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,8 @@ impl ControlledWallClock {
|
||||
}
|
||||
|
||||
/// Advance civil time explicitly, saturating at the largest timestamp.
|
||||
// `try_update` requires Rust 1.95; keep older stable CI toolchains compatible.
|
||||
#[allow(deprecated)]
|
||||
pub fn advance(&self, seconds: u64) {
|
||||
// Harness control may retry on a concurrent update; reads remain a single load.
|
||||
let _ = self.seconds.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
|
||||
|
||||
@@ -609,7 +609,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn front_buffer_pixel(platform: &TestPlatform, x: i32, y: i32) -> u32 {
|
||||
const FRAMEBUFFER_WIDTH: usize = 480;
|
||||
const FRAMEBUFFER_WIDTH: usize = prometeu_hal::graphics_contract::WIDTH;
|
||||
let index = x as usize + y as usize * FRAMEBUFFER_WIDTH;
|
||||
platform.local_hardware().gfx.front_buffer()[index]
|
||||
}
|
||||
@@ -1094,7 +1094,9 @@ mod tests {
|
||||
assert_eq!(dummy_ownership.app_id, 2);
|
||||
|
||||
let front = platform.local_hardware().gfx.front_buffer();
|
||||
let center = 240 + 135 * 480;
|
||||
let center = prometeu_hal::graphics_contract::WIDTH / 2
|
||||
+ (prometeu_hal::graphics_contract::HEIGHT / 2)
|
||||
* prometeu_hal::graphics_contract::WIDTH;
|
||||
assert_eq!(front[center], Color::GREEN.raw());
|
||||
|
||||
firmware.request_home_from_host();
|
||||
@@ -1512,8 +1514,12 @@ mod tests {
|
||||
#[test]
|
||||
fn shell_running_close_click_uses_lifecycle_and_returns_hub_home() {
|
||||
let (mut firmware, mut platform, _signals, task_id) = load_shell_running_firmware();
|
||||
let close_signals =
|
||||
InputSignals { f_signal: true, x_pos: 420, y_pos: 24, ..Default::default() };
|
||||
let close_signals = InputSignals {
|
||||
f_signal: true,
|
||||
x_pos: prometeu_hal::graphics_contract::WIDTH as i32 - 60,
|
||||
y_pos: 24,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
firmware.tick(&close_signals, &mut platform);
|
||||
|
||||
|
||||
@@ -47,7 +47,12 @@ impl HubHomeStep {
|
||||
let id = ctx.os.windows().add_window(
|
||||
app.title().to_string(),
|
||||
WindowOwner::Task(task_id),
|
||||
Rect { x: 40, y: 20, w: 400, h: 220 },
|
||||
Rect {
|
||||
x: 40,
|
||||
y: 20,
|
||||
w: prometeu_hal::graphics_contract::WIDTH as i32 - 80,
|
||||
h: prometeu_hal::graphics_contract::HEIGHT as i32 - 50,
|
||||
},
|
||||
app.color(),
|
||||
);
|
||||
ctx.os.windows().set_focus(id);
|
||||
|
||||
@@ -48,6 +48,25 @@ impl LoadCartridgeStep {
|
||||
pub fn needs_memcard_choice(&self) -> bool {
|
||||
self.awaiting_memcard && !self.preparing_memcard
|
||||
}
|
||||
/// Typed host and UI admission share this single policy boundary.
|
||||
pub fn choose_memcard(
|
||||
&mut self,
|
||||
os: &mut prometeu_system::SystemOS,
|
||||
choice: prometeu_system::memcard::admission::Choice,
|
||||
created_at: u64,
|
||||
) -> prometeu_system::memcard::image::Result<()> {
|
||||
if !self.needs_memcard_choice() {
|
||||
return Err(prometeu_system::memcard::image::Error::InvalidState);
|
||||
}
|
||||
os.memcard().choose_for_game(
|
||||
self.cartridge.app_id,
|
||||
self.cartridge.memcard_slots.unwrap() as usize,
|
||||
choice,
|
||||
created_at,
|
||||
)?;
|
||||
self.preparing_memcard = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn new_game_switch(cartridge: Cartridge) -> Self {
|
||||
Self { failure_recovery: LoadCartridgeFailureRecovery::ReturnToHub, ..Self::new(cartridge) }
|
||||
@@ -128,13 +147,8 @@ impl LoadCartridgeStep {
|
||||
Choice::MemoryExisting
|
||||
};
|
||||
let created_at = ctx.platform.wall_clock().utc_unix_seconds();
|
||||
match ctx.os.memcard().choose_for_game(
|
||||
self.cartridge.app_id,
|
||||
self.cartridge.memcard_slots.unwrap() as usize,
|
||||
choice,
|
||||
created_at,
|
||||
) {
|
||||
Ok(()) => self.preparing_memcard = true,
|
||||
match self.choose_memcard(ctx.os, choice, created_at) {
|
||||
Ok(()) => {}
|
||||
Err(error) => self.memcard_message = Self::preparation_message(error),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Fixed machine graphics contract. Host surfaces never change these dimensions.
|
||||
pub const WIDTH: usize = 640;
|
||||
pub const HEIGHT: usize = 360;
|
||||
pub const REFRESH_HZ: u32 = 60;
|
||||
/// Canonical RGBA8888, with tightly packed native rows.
|
||||
pub const BYTES_PER_PIXEL: usize = 4;
|
||||
pub const PIXELS: usize = WIDTH * HEIGHT;
|
||||
pub const STRIDE_PIXELS: usize = WIDTH;
|
||||
pub const STRIDE_BYTES: usize = STRIDE_PIXELS * BYTES_PER_PIXEL;
|
||||
pub const FRAME_BYTES: usize = STRIDE_BYTES * HEIGHT;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn native_graphics_contract_is_fixed() {
|
||||
assert_eq!((WIDTH, HEIGHT, REFRESH_HZ), (640, 360, 60));
|
||||
assert_eq!((PIXELS, STRIDE_BYTES, FRAME_BYTES), (230_400, 2_560, 921_600));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod debugger_protocol;
|
||||
pub mod gfx_bridge;
|
||||
pub mod glyph;
|
||||
pub mod glyph_bank;
|
||||
pub mod graphics_contract;
|
||||
pub mod host_context;
|
||||
pub mod host_return;
|
||||
pub mod input_signals;
|
||||
|
||||
@@ -57,6 +57,21 @@ impl LogService {
|
||||
self.events.iter().filter(|e| e.seq > seq).cloned().collect()
|
||||
}
|
||||
|
||||
/// Non-destructive page in native sequence order. A null cursor includes zero.
|
||||
pub fn get_page(&self, after: Option<u64>, limit: usize) -> Vec<LogEvent> {
|
||||
self.events
|
||||
.iter()
|
||||
.filter(|event| after.is_none_or(|seq| event.seq > seq))
|
||||
.take(limit)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Retained bounds, independent of any reader's progress.
|
||||
pub fn sequence_bounds(&self) -> (Option<u64>, Option<u64>) {
|
||||
(self.events.front().map(|event| event.seq), self.last_seq())
|
||||
}
|
||||
|
||||
pub fn last_seq(&self) -> Option<u64> {
|
||||
self.events.back().map(|e| e.seq)
|
||||
}
|
||||
@@ -107,4 +122,35 @@ mod tests {
|
||||
assert_eq!(after[0].msg, "Log 3");
|
||||
assert_eq!(after[1].msg, "Log 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_preserve_zero_requery_and_retained_bounds() {
|
||||
let mut service = LogService::new(3);
|
||||
assert_eq!(service.sequence_bounds(), (None, None));
|
||||
assert!(service.get_page(None, 2).is_empty());
|
||||
for i in 0..3 {
|
||||
service.log(i, i, LogLevel::Info, LogSource::Pos, 7, format!("{i}"));
|
||||
}
|
||||
assert_eq!(service.sequence_bounds(), (Some(0), Some(2)));
|
||||
for _ in 0..2 {
|
||||
let page = service.get_page(None, 2);
|
||||
assert_eq!(page.iter().map(|event| event.seq).collect::<Vec<_>>(), vec![0, 1]);
|
||||
}
|
||||
assert_eq!(service.get_page(Some(1), 2)[0].seq, 2);
|
||||
assert!(service.get_page(Some(2), 2).is_empty());
|
||||
service.log(3, 3, LogLevel::Info, LogSource::Pos, 7, "next".into());
|
||||
assert_eq!(service.sequence_bounds(), (Some(1), Some(3)));
|
||||
assert_eq!(service.get_page(Some(2), 2)[0].seq, 3);
|
||||
assert_eq!(service.get_page(None, 10).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_cursors_preserve_large_unsigned_sequences() {
|
||||
let mut service = LogService::new(3);
|
||||
service.next_seq = u64::MAX - 2;
|
||||
service.log(0, 0, LogLevel::Info, LogSource::Pos, 0, "first".into());
|
||||
service.log(0, 0, LogLevel::Info, LogSource::Pos, 0, "second".into());
|
||||
assert_eq!(service.get_page(Some(u64::MAX - 2), 1)[0].seq, u64::MAX - 1);
|
||||
assert!(service.get_page(Some(u64::MAX), 1).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ pub enum MemcardIoError {
|
||||
InvalidRange,
|
||||
NoSpace,
|
||||
Unsupported,
|
||||
Busy,
|
||||
AccessDenied,
|
||||
AlreadyExists,
|
||||
Indeterminate,
|
||||
IoError,
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ pub trait RuntimePlatform {
|
||||
fn wall_clock(&self) -> &dyn WallClock;
|
||||
|
||||
fn display_size(&self) -> (usize, usize) {
|
||||
(480, 270)
|
||||
(crate::graphics_contract::WIDTH, crate::graphics_contract::HEIGHT)
|
||||
}
|
||||
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink;
|
||||
|
||||
@@ -224,6 +224,8 @@ impl SceneViewportResolver {
|
||||
scene_height_tiles: usize,
|
||||
) -> TileAnchor {
|
||||
let mut next = current;
|
||||
// Mixed layers must not step past the center and immediately step back.
|
||||
let trigger = self.hysteresis_trigger_px.max(tile_size_px / 2);
|
||||
|
||||
loop {
|
||||
let center_x_px = next.x * tile_size_px + tile_size_px / 2;
|
||||
@@ -231,11 +233,11 @@ impl SceneViewportResolver {
|
||||
if drift_x.abs() <= self.hysteresis_safe_px {
|
||||
break;
|
||||
}
|
||||
if drift_x > self.hysteresis_trigger_px {
|
||||
if drift_x > trigger {
|
||||
next.x += 1;
|
||||
continue;
|
||||
}
|
||||
if drift_x < -self.hysteresis_trigger_px {
|
||||
if drift_x < -trigger {
|
||||
next.x -= 1;
|
||||
continue;
|
||||
}
|
||||
@@ -248,11 +250,11 @@ impl SceneViewportResolver {
|
||||
if drift_y.abs() <= self.hysteresis_safe_px {
|
||||
break;
|
||||
}
|
||||
if drift_y > self.hysteresis_trigger_px {
|
||||
if drift_y > trigger {
|
||||
next.y += 1;
|
||||
continue;
|
||||
}
|
||||
if drift_y < -self.hysteresis_trigger_px {
|
||||
if drift_y < -trigger {
|
||||
next.y -= 1;
|
||||
continue;
|
||||
}
|
||||
@@ -433,20 +435,34 @@ mod tests {
|
||||
#[test]
|
||||
fn first_update_initializes_master_and_layer_anchors() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let update = resolver.update(&scene, 0, 0);
|
||||
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.layer_anchors[1], TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 22, y: 13 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 22, y: 13 });
|
||||
assert_eq!(update.layer_anchors[1], TileAnchor { x: 22, y: 13 });
|
||||
assert_eq!(update.refresh_requests.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_layer_copy_requests_follow_parallax_factor() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let update = resolver.update(&scene, 32, 48);
|
||||
|
||||
@@ -461,24 +477,38 @@ mod tests {
|
||||
#[test]
|
||||
fn hysteresis_prevents_small_back_and_forth_refresh_churn() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let _ = resolver.update(&scene, 0, 0);
|
||||
let update = resolver.update(&scene, 8, 0);
|
||||
|
||||
assert!(update.refresh_requests.is_empty());
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 22, y: 13 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_high_speed_movement_advances_in_tile_steps() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let _ = resolver.update(&scene, 0, 0);
|
||||
let update = resolver.update(&scene, 64, 0);
|
||||
|
||||
assert!(update.master_anchor.x > 17);
|
||||
assert!(update.master_anchor.x > 22);
|
||||
assert!(update.refresh_requests.iter().any(|request| matches!(
|
||||
request,
|
||||
CacheRefreshRequest::RefreshColumn { layer_index: 0, .. }
|
||||
@@ -489,18 +519,32 @@ mod tests {
|
||||
#[test]
|
||||
fn anchors_clamp_near_scene_edges() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let update = resolver.update(&scene, 10_000, 10_000);
|
||||
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 46, y: 53 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 46, y: 53 });
|
||||
assert_eq!(update.master_anchor, TileAnchor { x: 41, y: 50 });
|
||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 41, y: 50 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_trigger_converts_to_non_overlapping_region_requests() {
|
||||
let scene = make_scene();
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let _ = resolver.update(&scene, 0, 0);
|
||||
let update = resolver.update(&scene, 64, 80);
|
||||
@@ -515,15 +559,22 @@ mod tests {
|
||||
.collect();
|
||||
|
||||
assert_eq!(regions.len(), 2);
|
||||
assert_eq!(regions[0].x + regions[0].width, 35);
|
||||
assert_eq!(regions[0].height, 21);
|
||||
assert_eq!(regions[1].width, 34);
|
||||
assert_eq!(regions[0].x + regions[0].width, 45);
|
||||
assert_eq!(regions[0].height, 27);
|
||||
assert_eq!(regions[1].width, 44);
|
||||
assert_eq!(regions[1].height, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_scene_requests_full_invalidation_for_all_layers() {
|
||||
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||
let mut resolver = SceneViewportResolver::new(
|
||||
crate::graphics_contract::WIDTH as i32,
|
||||
crate::graphics_contract::HEIGHT as i32,
|
||||
45,
|
||||
27,
|
||||
12,
|
||||
20,
|
||||
);
|
||||
|
||||
let requests = resolver.reset_scene();
|
||||
|
||||
|
||||
@@ -385,6 +385,14 @@ impl<'a> VmFacade<'a> {
|
||||
self.os.vm_runtime.record_repeated_render_worker_frame(frame_id);
|
||||
}
|
||||
|
||||
pub fn record_presented_render_worker_frame(
|
||||
&self,
|
||||
ownership: RenderOwnership,
|
||||
frame_id: FrameId,
|
||||
) {
|
||||
self.os.vm_runtime.record_presented_render_worker_frame(ownership, frame_id);
|
||||
}
|
||||
|
||||
pub fn active_render_ownership(&self) -> RenderOwnership {
|
||||
if let Some(task_id) = self.foreground_session_task_id()
|
||||
&& let Some(session) = self.os.vm_sessions.for_task(task_id)
|
||||
|
||||
@@ -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(
|
||||
@@ -162,6 +170,16 @@ impl SystemOS {
|
||||
self.log_service.get_after(seq)
|
||||
}
|
||||
|
||||
/// Coherent non-destructive page and retained bounds; does not execute the VM.
|
||||
pub fn log_snapshot(
|
||||
&self,
|
||||
after: Option<u64>,
|
||||
limit: usize,
|
||||
) -> (Vec<LogEvent>, Option<u64>, Option<u64>) {
|
||||
let (oldest, newest) = self.log_service.sequence_bounds();
|
||||
(self.log_service.get_page(after, limit), oldest, newest)
|
||||
}
|
||||
|
||||
pub fn frame_index(&mut self) -> u64 {
|
||||
self.vm().logical_frame_index()
|
||||
}
|
||||
|
||||
@@ -10,19 +10,41 @@ use prometeu_hal::{
|
||||
|
||||
const SHELL_A_BUTTON: Rect = Rect { x: 112, y: 172, w: 112, h: 32 };
|
||||
const SHELL_B_BUTTON: Rect = Rect { x: 256, y: 172, w: 112, h: 32 };
|
||||
const CLOSE_BUTTON: Rect = Rect { x: 420, y: 24, w: 16, h: 16 };
|
||||
const VIEWPORT: Rect = Rect { x: 0, y: 0, w: 480, h: 270 };
|
||||
const HOME_PANEL: Rect = Rect { x: 48, y: 58, w: 384, h: 154 };
|
||||
const TITLE_PANEL: Rect = Rect { x: 72, y: 34, w: 336, h: 28 };
|
||||
const CLOSE_BUTTON: Rect =
|
||||
Rect { x: prometeu_hal::graphics_contract::WIDTH as i32 - 60, y: 24, w: 16, h: 16 };
|
||||
const VIEWPORT: Rect = Rect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
w: prometeu_hal::graphics_contract::WIDTH as i32,
|
||||
h: prometeu_hal::graphics_contract::HEIGHT as i32,
|
||||
};
|
||||
const HOME_PANEL: Rect = Rect {
|
||||
x: 48,
|
||||
y: 58,
|
||||
w: prometeu_hal::graphics_contract::WIDTH as i32 - 96,
|
||||
h: prometeu_hal::graphics_contract::HEIGHT as i32 - 116,
|
||||
};
|
||||
const TITLE_PANEL: Rect =
|
||||
Rect { x: 72, y: 34, w: prometeu_hal::graphics_contract::WIDTH as i32 - 144, h: 28 };
|
||||
const GAME_ROW_X: i32 = 72;
|
||||
const GAME_ROW_Y: i32 = 90;
|
||||
const GAME_ROW_W: i32 = 336;
|
||||
const GAME_ROW_W: i32 = prometeu_hal::graphics_contract::WIDTH as i32 - 144;
|
||||
const GAME_ROW_H: i32 = 22;
|
||||
const GAME_ROW_GAP: i32 = 6;
|
||||
const MAX_HOME_GAME_ROWS: usize = 3;
|
||||
pub const HUB_SUSPENDED_GAME_KILL_CONTROL: Rect = Rect { x: 288, y: 230, w: 168, h: 24 };
|
||||
pub const HUB_SUSPENDED_GAME_KILL_CONTROL: Rect = Rect {
|
||||
x: prometeu_hal::graphics_contract::WIDTH as i32 - 192,
|
||||
y: prometeu_hal::graphics_contract::HEIGHT as i32 - 40,
|
||||
w: 168,
|
||||
h: 24,
|
||||
};
|
||||
#[cfg(test)]
|
||||
const SHELL_FRAME: Rect = Rect { x: 40, y: 20, w: 400, h: 220 };
|
||||
const SHELL_FRAME: Rect = Rect {
|
||||
x: 40,
|
||||
y: 20,
|
||||
w: prometeu_hal::graphics_contract::WIDTH as i32 - 80,
|
||||
h: prometeu_hal::graphics_contract::HEIGHT as i32 - 50,
|
||||
};
|
||||
|
||||
const COLOR_BG: Color = Color::rgb(12, 14, 22);
|
||||
const COLOR_PANEL: Color = Color::rgb(25, 31, 48);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -7,6 +7,8 @@ use std::time::{Duration, Instant};
|
||||
|
||||
pub const GUEST_BYTES: usize = 4096;
|
||||
static NEXT_CONTEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
// `try_update` requires Rust 1.95; keep older stable CI toolchains compatible.
|
||||
#[allow(deprecated)]
|
||||
fn next_context() -> Result<u64> {
|
||||
NEXT_CONTEXT
|
||||
.fetch_update(
|
||||
@@ -71,12 +73,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 +104,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 +611,7 @@ impl Session {
|
||||
job,
|
||||
released: !saves_payload,
|
||||
saves_payload,
|
||||
worker_returned: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -674,6 +755,7 @@ impl Session {
|
||||
job,
|
||||
released: false,
|
||||
saves_payload: true,
|
||||
worker_returned: false,
|
||||
});
|
||||
Ok(id)
|
||||
}
|
||||
@@ -692,6 +774,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 +902,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 +916,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 +952,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 +981,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 +1079,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;
|
||||
|
||||
@@ -16,6 +16,8 @@ impl PublicationControl {
|
||||
pub fn publication_attempted(&self) -> bool {
|
||||
self.0.load(Ordering::SeqCst) & 1 != 0
|
||||
}
|
||||
// `try_update` requires Rust 1.95; keep older stable CI toolchains compatible.
|
||||
#[allow(deprecated)]
|
||||
fn enter(&self) -> Result<()> {
|
||||
self.0
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| {
|
||||
|
||||
@@ -187,6 +187,16 @@ impl VirtualMachineRuntime {
|
||||
self.render_worker_ownership.set(self.render_manager.active_ownership());
|
||||
}
|
||||
|
||||
pub fn record_presented_render_worker_frame(
|
||||
&self,
|
||||
ownership: prometeu_hal::RenderOwnership,
|
||||
frame_id: FrameId,
|
||||
) {
|
||||
if let Some(controller) = self.render_worker_controller.as_ref() {
|
||||
controller.record_presented_frame(ownership, frame_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_repeated_render_worker_frame(&self, frame_id: FrameId) {
|
||||
if let Some(controller) = self.render_worker_controller.as_ref() {
|
||||
controller.record_repeated_frame(frame_id);
|
||||
|
||||
@@ -25,6 +25,7 @@ impl Default for RenderWorkerConfig {
|
||||
struct RenderWorkerState {
|
||||
telemetry: RenderWorkerTelemetry,
|
||||
last_error: Option<RenderWorkerError>,
|
||||
last_presented: Option<(RenderOwnership, FrameId)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -40,6 +41,19 @@ impl LatestRenderFrameStore {
|
||||
pub fn latest_frame(&self) -> Option<OwnedRgba8888Frame> {
|
||||
self.latest.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Copy only a different complete publication; paused observers need not copy pixels.
|
||||
pub fn latest_frame_after(
|
||||
&self,
|
||||
previous: Option<(RenderOwnership, FrameId)>,
|
||||
) -> Option<OwnedRgba8888Frame> {
|
||||
self.latest
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.filter(|frame| previous != Some((frame.ownership, frame.frame_id)))
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderWorkerFrameSink for LatestRenderFrameStore {
|
||||
@@ -144,6 +158,7 @@ impl RenderWorkerController {
|
||||
let mut telemetry = self.handoff.telemetry();
|
||||
let state = self.state.lock().unwrap();
|
||||
telemetry.published_frames = state.telemetry.published_frames;
|
||||
telemetry.presented_frames = state.telemetry.presented_frames;
|
||||
telemetry.render_failures = state.telemetry.render_failures;
|
||||
telemetry.publish_failures = state.telemetry.publish_failures;
|
||||
telemetry.present_failures = state.telemetry.present_failures;
|
||||
@@ -166,6 +181,17 @@ impl RenderWorkerController {
|
||||
self.ownership.snapshot()
|
||||
}
|
||||
|
||||
/// Record only after a successful host presentation, never on publication.
|
||||
pub fn record_presented_frame(&self, ownership: RenderOwnership, frame_id: FrameId) {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.last_presented == Some((ownership, frame_id)) {
|
||||
state.telemetry.record_repeated_frame(frame_id.get());
|
||||
} else {
|
||||
state.telemetry.record_presented(frame_id.get());
|
||||
}
|
||||
state.last_presented = Some((ownership, frame_id));
|
||||
}
|
||||
|
||||
pub fn record_repeated_frame(&self, frame_id: FrameId) {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.telemetry.record_repeated_frame(frame_id.get());
|
||||
@@ -190,13 +216,13 @@ fn run_worker_loop<B, S>(
|
||||
B: RenderWorkerBackend,
|
||||
S: RenderWorkerFrameSink,
|
||||
{
|
||||
loop {
|
||||
let submission = match handoff.wait_take() {
|
||||
RenderWorkerHandoffWait::Submission(submission) => submission,
|
||||
RenderWorkerHandoffWait::Shutdown => return,
|
||||
};
|
||||
let report_path = std::env::var_os("PROMETEU_GRAPHICS_METRICS").map(std::path::PathBuf::from);
|
||||
let mut measurements = Vec::new();
|
||||
let mut measured_frames = 0usize;
|
||||
while let RenderWorkerHandoffWait::Submission(submission) = handoff.wait_take() {
|
||||
let frame_id = submission.frame_id;
|
||||
|
||||
let render_begin = report_path.as_ref().map(|_| std::time::Instant::now());
|
||||
let render_result = catch_unwind(AssertUnwindSafe(|| backend.render(&submission)))
|
||||
.map_err(|_| RenderWorkerError::WorkerPanic);
|
||||
let frame = match render_result {
|
||||
@@ -212,13 +238,45 @@ fn run_worker_loop<B, S>(
|
||||
continue;
|
||||
}
|
||||
|
||||
let render_us = render_begin.map(|start| start.elapsed().as_micros() as u64);
|
||||
let publish_begin = report_path.as_ref().map(|_| std::time::Instant::now());
|
||||
let publish_result = catch_unwind(AssertUnwindSafe(|| sink.publish(frame)))
|
||||
.map_err(|_| RenderWorkerError::WorkerPanic);
|
||||
if let (Some(render_us), Some(begin)) = (render_us, publish_begin) {
|
||||
let sample = (frame_id.get(), render_us, begin.elapsed().as_micros() as u64);
|
||||
if measurements.len() < 16384 {
|
||||
measurements.push(sample);
|
||||
} else {
|
||||
measurements[measured_frames % 16384] = sample;
|
||||
}
|
||||
measured_frames += 1;
|
||||
}
|
||||
match publish_result {
|
||||
Ok(Ok(())) => record_published(&state, frame_id),
|
||||
Ok(Err(error)) | Err(error) => record_error(&state, error, frame_id),
|
||||
}
|
||||
}
|
||||
if let Some(path) = report_path {
|
||||
use std::io::Write;
|
||||
let worker = state.lock().unwrap();
|
||||
let handoff = handoff.telemetry();
|
||||
let report = serde_json::json!({"schema":1,"source":"async_render_worker",
|
||||
"produced_submissions":handoff.produced_submissions,"consumed_submissions":handoff.consumed_submissions,
|
||||
"replaced_before_consume":handoff.replaced_before_consume,
|
||||
"published_frames":worker.telemetry.published_frames,"first_presentations":worker.telemetry.presented_frames,
|
||||
"repeated_presentations":worker.telemetry.repeated_frames,
|
||||
"render_failures":worker.telemetry.render_failures,"publish_failures":worker.telemetry.publish_failures,
|
||||
"measured_frames":measured_frames,"samples_frame_render_publish_us":measurements,
|
||||
"physical_display_hz":null,
|
||||
"limitations":"last 16384 successful-render samples; render includes owned-frame copy; sink publication is not scanout; opt-in clock and storage overhead"});
|
||||
if let Ok(mut file) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path.with_extension("renderer.jsonl"))
|
||||
{
|
||||
let _ = writeln!(file, "{report}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_published(state: &Arc<Mutex<RenderWorkerState>>, frame_id: FrameId) {
|
||||
@@ -333,6 +391,14 @@ mod tests {
|
||||
SharedFakeBackend(backend),
|
||||
);
|
||||
|
||||
let first_session = RenderOwnership::new(1, AppMode::Game, 7);
|
||||
controller.record_presented_frame(first_session, FrameId::ZERO);
|
||||
controller.record_presented_frame(first_session, FrameId::ZERO);
|
||||
// Frame zero in a new epoch is a new image, not a repeat of the old session.
|
||||
controller.record_presented_frame(RenderOwnership::new(2, AppMode::Game, 7), FrameId::ZERO);
|
||||
assert_eq!(controller.telemetry().presented_frames, 2);
|
||||
assert_eq!(controller.telemetry().repeated_frames, 1);
|
||||
|
||||
assert_eq!(controller.stop(), Ok(()));
|
||||
assert_eq!(controller.last_error(), None);
|
||||
}
|
||||
|
||||
@@ -107,4 +107,5 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
pub mod memcard_fixture;
|
||||
pub mod program;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Neutral PBX/ABI fixture. No source-language frontend or compiler is involved.
|
||||
use crate::program::{TestProgram, scalar_catalog};
|
||||
use prometeu_bytecode::{
|
||||
assembler::assemble,
|
||||
model::{ConstantPoolEntry, SyscallDecl},
|
||||
registry::*,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum MemcardFixture {
|
||||
Write,
|
||||
Read,
|
||||
ReadWithPresentation,
|
||||
Dirty,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Code {
|
||||
bytes: Vec<u8>,
|
||||
labels: BTreeMap<&'static str, u32>,
|
||||
fixups: Vec<(usize, &'static str)>,
|
||||
}
|
||||
impl Code {
|
||||
fn emit(&mut self, text: &str) {
|
||||
self.bytes.extend(assemble(text).expect("fixture assembly"));
|
||||
}
|
||||
fn mark(&mut self, name: &'static str) {
|
||||
self.labels.insert(name, self.bytes.len() as u32);
|
||||
}
|
||||
fn jump(&mut self, op: &str, name: &'static str) {
|
||||
self.fixups.push((self.bytes.len() + 2, name));
|
||||
self.emit(&format!("{op} 0"));
|
||||
}
|
||||
fn check(&mut self, value: i64, int32: bool) {
|
||||
self.emit(&format!("PUSH_{} {value}\nEQ", if int32 { "I32" } else { "I64" }));
|
||||
let resume = self.bytes.len() + 8; // conditional jump followed by a terminal trap
|
||||
self.emit(&format!("JMP_IF_TRUE {resume}\nTRAP"));
|
||||
}
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
for (offset, label) in self.fixups {
|
||||
self.bytes[offset..offset + 4].copy_from_slice(&self.labels[label].to_le_bytes());
|
||||
}
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Stack oracle at a completed frame: 100 pending, 101 durable SUCCESS,
|
||||
/// 104 MEMORY_ONLY, 201 exact existing readback, 301 dirty/uncommitted RAM.
|
||||
/// Read never writes or submits a commit; a missing/wrong payload traps.
|
||||
pub fn memcard_program(kind: MemcardFixture) -> Vec<u8> {
|
||||
let reads = matches!(kind, MemcardFixture::Read | MemcardFixture::ReadWithPresentation);
|
||||
let mut main = Code::default();
|
||||
main.emit("HOSTCALL 0");
|
||||
main.check(0, true);
|
||||
main.emit("PUSH_I64 4\nARRAY_NEW 9\nSET_GLOBAL 1");
|
||||
if reads {
|
||||
let read_import = if matches!(kind, MemcardFixture::Read) { 1 } else { 2 };
|
||||
main.emit(&format!("GET_GLOBAL 0\nPUSH_I32 0\nPUSH_I32 0\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 4\nHOSTCALL {read_import}"));
|
||||
main.check(4, false);
|
||||
main.check(0, false);
|
||||
for (i, value) in [0, 127, 128, 255].into_iter().enumerate() {
|
||||
main.emit(&format!("GET_GLOBAL 1\nPUSH_I64 {i}\nARRAY_GET 9"));
|
||||
main.check(value, true);
|
||||
}
|
||||
main.mark("done");
|
||||
main.emit("PUSH_I64 201\nFRAME_SYNC\nPOP_N 1");
|
||||
main.jump("JMP", "done");
|
||||
} else {
|
||||
for (i, value) in [0, 127, 128, 255].into_iter().enumerate() {
|
||||
main.emit(&format!("GET_GLOBAL 1\nPUSH_I64 {i}\nPUSH_I32 {value}\nARRAY_SET 9"));
|
||||
}
|
||||
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nPUSH_I32 0\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 4\nHOSTCALL 2");
|
||||
main.check(4, false);
|
||||
main.check(0, false);
|
||||
if matches!(kind, MemcardFixture::Dirty) {
|
||||
main.mark("done");
|
||||
main.emit("PUSH_I64 301\nFRAME_SYNC\nPOP_N 1");
|
||||
main.jump("JMP", "done");
|
||||
} else {
|
||||
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nHOSTCALL 3\nSET_GLOBAL 2");
|
||||
main.check(0, false);
|
||||
main.mark("query");
|
||||
main.emit("GET_GLOBAL 0\nGET_GLOBAL 2\nHOSTCALL 4\nPOP_N 1\nSET_GLOBAL 3");
|
||||
main.check(0, false);
|
||||
main.emit("GET_GLOBAL 3\nPUSH_I64 100\nADD\nFRAME_SYNC\nPOP_N 1");
|
||||
main.jump("JMP", "query");
|
||||
}
|
||||
}
|
||||
main.mark("error");
|
||||
main.emit("TRAP");
|
||||
let mut code = main.finish();
|
||||
let main_len = code.len() as u32;
|
||||
let hook = if matches!(kind, MemcardFixture::Read) {
|
||||
assemble("GET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I32 0\nRET").unwrap()
|
||||
} else {
|
||||
assemble("GET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I64 560\nARRAY_NEW 9\nSET_GLOBAL 1\nGET_LOCAL 0\nPUSH_CONST 0\nPUSH_I64 1\nPUSH_I32 1\nPUSH_I32 1\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 560\nHOSTCALL 1\nPOP_N 1\nPUSH_I32 0\nRET").unwrap()
|
||||
};
|
||||
let hook_len = hook.len() as u32;
|
||||
code.extend(hook);
|
||||
let mut types = scalar_catalog();
|
||||
types.push(TypeDecl { name: None, kind: TypeKind::Array(TypeId(1)) });
|
||||
let mut imports = vec![("bootstrap", 0, 1)];
|
||||
if !matches!(kind, MemcardFixture::Read) {
|
||||
imports.push(("presentation", 8, 1));
|
||||
}
|
||||
match kind {
|
||||
MemcardFixture::Read | MemcardFixture::ReadWithPresentation => {
|
||||
imports.push(("slot_read", 6, 2));
|
||||
}
|
||||
MemcardFixture::Dirty => imports.push(("slot_write", 6, 2)),
|
||||
MemcardFixture::Write => {
|
||||
imports.extend([("slot_write", 6, 2), ("slot_commit", 2, 2), ("query", 2, 3)])
|
||||
}
|
||||
}
|
||||
let syscalls = imports
|
||||
.into_iter()
|
||||
.map(|(name, arg_slots, ret_slots)| SyscallDecl {
|
||||
module: "mem".into(),
|
||||
name: name.into(),
|
||||
version: 1,
|
||||
arg_slots,
|
||||
ret_slots,
|
||||
})
|
||||
.collect();
|
||||
TestProgram {
|
||||
const_pool: vec![ConstantPoolEntry::String("Neutral persistence fixture".into())],
|
||||
code,
|
||||
functions: vec![
|
||||
FunctionDecl { code_len: main_len, max_stack_slots: 32, ..Default::default() },
|
||||
FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::MemcardBoot,
|
||||
code_offset: main_len,
|
||||
code_len: hook_len,
|
||||
max_stack_slots: 32,
|
||||
signature: Signature {
|
||||
parameters: vec![NamedType { type_id: TypeId(0), name: None }],
|
||||
results: vec![TypeId(1)],
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
syscalls,
|
||||
..Default::default()
|
||||
}
|
||||
.serialize_with_types(types)
|
||||
}
|
||||
@@ -63,10 +63,13 @@ impl TestProgram {
|
||||
}
|
||||
}
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
self.serialize_with_types(scalar_catalog())
|
||||
}
|
||||
pub fn serialize_with_types(&self, types: Vec<TypeDecl>) -> Vec<u8> {
|
||||
let mut budget = LoadBudget::new(Default::default());
|
||||
let registry = Registry::resolve(
|
||||
RegistryDeclarations {
|
||||
types: scalar_catalog(),
|
||||
types,
|
||||
functions: self.functions.clone(),
|
||||
implementations: vec![],
|
||||
},
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Bounded run of the production desktop host, with normal teardown for metrics.
|
||||
//! No machine timing or rendering loop is replaced by this measurement harness.
|
||||
use prometeu_host_desktop_winit::{audio, fs_backend, log_sink, stats, utilities, wall_clock};
|
||||
#[allow(dead_code)]
|
||||
#[path = "../src/debugger.rs"]
|
||||
mod debugger;
|
||||
#[path = "../src/input.rs"]
|
||||
mod input;
|
||||
#[path = "../src/presentation_blit.rs"]
|
||||
mod presentation_blit;
|
||||
#[allow(dead_code)]
|
||||
#[path = "../src/studio/mod.rs"]
|
||||
mod studio;
|
||||
#[path = "../src/viewport.rs"]
|
||||
mod viewport;
|
||||
// Compile the actual host implementation; its non-desktop entry points are unused
|
||||
// by this executable. Keep measurement access out of the product's public API.
|
||||
#[allow(dead_code)]
|
||||
mod runner {
|
||||
include!("../src/runner.rs");
|
||||
impl HostRunner {
|
||||
pub(super) fn measured_state(&mut self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"host_vm_ticks": self.firmware.os.vm().tick_index(),
|
||||
"completed_vm_frames": self.firmware.os.vm().completed_logical_frames(),
|
||||
"logical_frame_index": self.firmware.os.vm().logical_frame_index(),
|
||||
"synchronous_publications": self.firmware.os.vm().telemetry_snapshot().presented_frames,
|
||||
"front_buffer_publications": self.hardware.gfx.publication_count(),
|
||||
"physical_display_hz": null,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::WindowEvent,
|
||||
event_loop::{ActiveEventLoop, EventLoop},
|
||||
window::WindowId,
|
||||
};
|
||||
|
||||
struct Measure {
|
||||
runner: runner::HostRunner,
|
||||
started: Option<Instant>,
|
||||
duration: Duration,
|
||||
}
|
||||
impl ApplicationHandler for Measure {
|
||||
fn resumed(&mut self, events: &ActiveEventLoop) {
|
||||
self.runner.resumed(events);
|
||||
self.started = Some(Instant::now());
|
||||
}
|
||||
fn window_event(&mut self, events: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
self.runner.window_event(events, id, event);
|
||||
}
|
||||
fn about_to_wait(&mut self, events: &ActiveEventLoop) {
|
||||
if self.started.is_some_and(|start| start.elapsed() >= self.duration) {
|
||||
events.exit();
|
||||
} else {
|
||||
self.runner.about_to_wait(events);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let path = std::env::args().nth(1).expect("cartridge directory");
|
||||
let seconds: u64 = std::env::args().nth(2).map(|s| s.parse().expect("seconds")).unwrap_or(10);
|
||||
assert!(seconds > 0);
|
||||
let mut runner = runner::HostRunner::new(None, None);
|
||||
runner.set_boot_target(prometeu_firmware::BootTarget::Cartridge {
|
||||
path,
|
||||
debug: false,
|
||||
debug_port: 0,
|
||||
});
|
||||
let mut app = Measure { runner, started: None, duration: Duration::from_secs(seconds) };
|
||||
let mut events = EventLoop::builder();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||
events.with_activate_ignoring_other_apps(true);
|
||||
}
|
||||
events.build()?.run_app(&mut app)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"schema":1,"source":"production_desktop_host",
|
||||
"elapsed_seconds":app.started.map(|s|s.elapsed().as_secs_f64()),
|
||||
"state":app.runner.measured_state(),
|
||||
"limitation":"includes boot, no discarded warmup; host/API submission is not physical scanout"})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! GPU readback qualification of the actual host blit, not a software geometry mirror.
|
||||
#[path = "../src/presentation_blit.rs"]
|
||||
mod presentation_blit;
|
||||
#[path = "../src/viewport.rs"]
|
||||
mod viewport;
|
||||
use pixels::{PixelsBuilder, SurfaceTexture, wgpu};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event_loop::{ActiveEventLoop, EventLoop},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Probe;
|
||||
impl ApplicationHandler for Probe {
|
||||
fn resumed(&mut self, events: &ActiveEventLoop) {
|
||||
let window = Box::leak(Box::new(
|
||||
events
|
||||
.create_window(
|
||||
Window::default_attributes()
|
||||
.with_title("PROMETEU graphics qualification")
|
||||
.with_inner_size(winit::dpi::PhysicalSize::new(640, 360)),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let size = window.inner_size();
|
||||
let mut pixels =
|
||||
PixelsBuilder::new(640, 360, SurfaceTexture::new(size.width, size.height, &*window))
|
||||
.build()
|
||||
.unwrap();
|
||||
for (i, p) in pixels.frame_mut().as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let (x, y) = (i % 640, i / 640);
|
||||
// Single-pixel checkerboard detects smoothing; all channels equal avoid channel-order ambiguity.
|
||||
let value = if (x + y) % 2 == 0 { 255 } else { 0 };
|
||||
p.copy_from_slice(&[value, value, value, 255]);
|
||||
}
|
||||
// Exercise real surface acquisition/upload/shader validation too.
|
||||
let blit = presentation_blit::PresentationBlit::new(&pixels);
|
||||
pixels
|
||||
.render_with(|e, t, _| {
|
||||
blit.render(
|
||||
e,
|
||||
t,
|
||||
viewport::Viewport::new((size.width, size.height), (640, 360)).unwrap(),
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let ctx = pixels.context();
|
||||
// A newly created macOS surface may be occluded: render_with then returns
|
||||
// without uploading. Offscreen verification must establish its own input.
|
||||
ctx.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &ctx.texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
pixels.frame(),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(640 * 4),
|
||||
rows_per_image: Some(360),
|
||||
},
|
||||
ctx.texture_extent,
|
||||
);
|
||||
for (w, h) in [(1280u32, 720u32), (1000, 700), (320, 240), (641, 361)] {
|
||||
let view = viewport::Viewport::new((w, h), (640, 360)).unwrap();
|
||||
let texture = ctx.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("blit-readback"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: pixels.render_texture_format(),
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let stride = (w * 4).div_ceil(256) * 256;
|
||||
let buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("readback"),
|
||||
size: u64::from(stride) * u64::from(h),
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = ctx.device.create_command_encoder(&Default::default());
|
||||
blit.render(&mut encoder, &texture.create_view(&Default::default()), view);
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(stride),
|
||||
rows_per_image: Some(h),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
ctx.queue.submit([encoder.finish()]);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| tx.send(result).unwrap());
|
||||
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
rx.recv().unwrap().unwrap();
|
||||
let data = buffer.slice(..).get_mapped_range();
|
||||
let mut checked = 0;
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let offset = (y * stride + x * 4) as usize;
|
||||
let rgb = &data[offset..offset + 3];
|
||||
// Every output pixel is black or white: any intermediate value means smoothing.
|
||||
assert!(
|
||||
rgb == [0, 0, 0] || rgb == [255, 255, 255],
|
||||
"filtered pixel at {w}x{h}:({x},{y})={rgb:?}"
|
||||
);
|
||||
if let Some((nx, ny)) = view.inverse(x as f64 + 0.5, y as f64 + 0.5) {
|
||||
let expected = if (nx + ny) % 2 == 0 { 255 } else { 0 };
|
||||
assert_eq!(
|
||||
rgb, [expected; 3],
|
||||
"GPU/input transform mismatch at {w}x{h}:({x},{y})"
|
||||
);
|
||||
checked += 1;
|
||||
} else {
|
||||
assert_eq!(rgb, [0, 0, 0], "bar");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked > 0);
|
||||
println!("GPU_NEAREST_PASS={w}x{h} checked={checked}");
|
||||
}
|
||||
events.exit();
|
||||
}
|
||||
fn window_event(
|
||||
&mut self,
|
||||
_: &ActiveEventLoop,
|
||||
_: winit::window::WindowId,
|
||||
_: winit::event::WindowEvent,
|
||||
) {
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
EventLoop::new().unwrap().run_app(&mut Probe).unwrap();
|
||||
}
|
||||
@@ -3,48 +3,11 @@ use winit::event::{ElementState, MouseButton, WindowEvent};
|
||||
use winit::keyboard::{KeyCode, PhysicalKey};
|
||||
use winit::window::Window;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FbViewport {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
impl FbViewport {
|
||||
fn framebuffer_viewport(window: &Window, display_size: (usize, usize)) -> Option<FbViewport> {
|
||||
let size = window.inner_size();
|
||||
|
||||
let win_w = size.width as f32;
|
||||
let win_h = size.height as f32;
|
||||
|
||||
if win_w <= 0.0 || win_h <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fb_w = display_size.0 as f32;
|
||||
let fb_h = display_size.1 as f32;
|
||||
|
||||
let scale_x = (win_w / fb_w).floor();
|
||||
let scale_y = (win_h / fb_h).floor();
|
||||
|
||||
let scale = scale_x.min(scale_y).max(1.0);
|
||||
|
||||
let viewport_w = fb_w * scale;
|
||||
let viewport_h = fb_h * scale;
|
||||
|
||||
let viewport_x = ((win_w - viewport_w) * 0.5).floor();
|
||||
let viewport_y = ((win_h - viewport_h) * 0.5).floor();
|
||||
|
||||
Some(FbViewport { x: viewport_x, y: viewport_y, w: viewport_w, h: viewport_h, scale })
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HostInputHandler {
|
||||
pub signals: InputSignals,
|
||||
system_controls: HostSystemControls,
|
||||
display_size: (usize, usize),
|
||||
cursor: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -66,7 +29,7 @@ impl HostSystemControls {
|
||||
|
||||
impl Default for HostInputHandler {
|
||||
fn default() -> Self {
|
||||
Self::new((480, 270))
|
||||
Self::new((prometeu_hal::graphics_contract::WIDTH, prometeu_hal::graphics_contract::HEIGHT))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +39,7 @@ impl HostInputHandler {
|
||||
signals: InputSignals::default(),
|
||||
system_controls: HostSystemControls::default(),
|
||||
display_size,
|
||||
cursor: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,50 +85,34 @@ impl HostInputHandler {
|
||||
}
|
||||
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
if let Some((x, y)) =
|
||||
window_to_fb(position.x as f32, position.y as f32, window, self.display_size)
|
||||
{
|
||||
self.signals.x_pos = x;
|
||||
self.signals.y_pos = y;
|
||||
}
|
||||
self.cursor = Some((position.x, position.y));
|
||||
let size = window.inner_size();
|
||||
self.update_pointer((size.width, size.height));
|
||||
}
|
||||
|
||||
WindowEvent::CursorLeft { .. } | WindowEvent::Focused(false) => {
|
||||
self.signals.f_signal = false;
|
||||
self.cursor = None;
|
||||
}
|
||||
WindowEvent::Resized(size) => self.update_pointer((size.width, size.height)),
|
||||
WindowEvent::MouseInput { state, button, .. } if *button == MouseButton::Left => {
|
||||
match state {
|
||||
ElementState::Pressed => {
|
||||
self.signals.f_signal = true;
|
||||
}
|
||||
ElementState::Released => {
|
||||
self.signals.f_signal = false;
|
||||
}
|
||||
}
|
||||
let size = window.inner_size();
|
||||
let inside = self.pointer_position((size.width, size.height)).is_some();
|
||||
self.signals.f_signal = *state == ElementState::Pressed && inside;
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
|
||||
fn window_to_fb(
|
||||
wx: f32,
|
||||
wy: f32,
|
||||
window: &Window,
|
||||
display_size: (usize, usize),
|
||||
) -> Option<(i32, i32)> {
|
||||
let viewport = FbViewport::framebuffer_viewport(window, display_size)?;
|
||||
|
||||
let local_x = wx - viewport.x;
|
||||
let local_y = wy - viewport.y;
|
||||
|
||||
if local_x < 0.0 || local_y < 0.0 || local_x >= viewport.w || local_y >= viewport.h {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fb_x = (local_x / viewport.scale).floor() as i32;
|
||||
let fb_y = (local_y / viewport.scale).floor() as i32;
|
||||
|
||||
Some((
|
||||
fb_x.clamp(0, display_size.0 as i32 - 1),
|
||||
fb_y.clamp(0, display_size.1 as i32 - 1),
|
||||
))
|
||||
}
|
||||
fn pointer_position(&self, surface: (u32, u32)) -> Option<(i32, i32)> {
|
||||
let (x, y) = self.cursor?;
|
||||
crate::viewport::Viewport::new(surface, self.display_size)?.inverse(x, y)
|
||||
}
|
||||
fn update_pointer(&mut self, surface: (u32, u32)) {
|
||||
if let Some((x, y)) = self.pointer_position(surface) {
|
||||
self.signals.x_pos = x;
|
||||
self.signals.y_pos = y;
|
||||
} else {
|
||||
self.signals.f_signal = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,6 +121,23 @@ impl HostInputHandler {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn drag_cancels_outside_and_cannot_recapture_on_reentry() {
|
||||
let mut input = HostInputHandler {
|
||||
cursor: Some((200.0, 200.0)),
|
||||
signals: InputSignals { f_signal: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
input.update_pointer((1000, 700));
|
||||
assert_eq!((input.signals.x_pos, input.signals.y_pos), (20, 30));
|
||||
input.cursor = Some((10.0, 200.0)); // left letterbox
|
||||
input.update_pointer((1000, 700));
|
||||
assert!(!input.signals.f_signal);
|
||||
input.cursor = Some((200.0, 200.0));
|
||||
input.update_pointer((1000, 700));
|
||||
assert!(!input.signals.f_signal);
|
||||
}
|
||||
|
||||
fn assert_no_pad_signal(signals: InputSignals) {
|
||||
assert!(!signals.up_signal);
|
||||
assert!(!signals.down_signal);
|
||||
|
||||
@@ -4,9 +4,12 @@ pub mod debugger;
|
||||
pub mod fs_backend;
|
||||
pub mod input;
|
||||
pub mod log_sink;
|
||||
mod presentation_blit;
|
||||
pub mod runner;
|
||||
pub mod stats;
|
||||
pub mod studio;
|
||||
pub mod utilities;
|
||||
mod viewport;
|
||||
pub mod wall_clock;
|
||||
|
||||
use cap::load_cap_config;
|
||||
@@ -18,6 +21,9 @@ use winit::event_loop::EventLoop;
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
struct Cli {
|
||||
/// Run an interactive Studio session without creating a desktop window.
|
||||
#[arg(long, requires = "run", conflicts_with = "debug")]
|
||||
studio: bool,
|
||||
/// Run a cartridge
|
||||
#[arg(long, value_name = "PATH", conflicts_with = "debug")]
|
||||
run: Option<String>,
|
||||
@@ -54,6 +60,23 @@ struct Cli {
|
||||
pub fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
if cli.studio {
|
||||
let bootstrap = studio::wire::Bootstrap::read(std::io::stdin().lock())?;
|
||||
let mut runner =
|
||||
HostRunner::new(cli.fs_root, cli.cap.as_ref().and_then(|path| load_cap_config(path)));
|
||||
if let Some(path) = cli.memcard {
|
||||
runner
|
||||
.install_memcard(path, cli.create_memcard)
|
||||
.map_err(|e| format!("Cannot install memory card: {e:?}"))?;
|
||||
}
|
||||
runner.set_boot_target(BootTarget::Cartridge {
|
||||
path: cli.run.expect("--studio requires --run"),
|
||||
debug: false,
|
||||
debug_port: 0,
|
||||
});
|
||||
return studio::run(runner, bootstrap).map_err(Into::into);
|
||||
}
|
||||
|
||||
let fs_root = cli.fs_root;
|
||||
let cap_config = cli.cap.as_ref().and_then(|path| load_cap_config(path));
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Host-only blit: pixels' built-in PixelPerfect path crops below 1x and Fill smooths.
|
||||
use crate::viewport::Viewport;
|
||||
use pixels::{Pixels, wgpu};
|
||||
|
||||
pub(crate) struct PresentationBlit {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
texture: wgpu::BindGroup,
|
||||
geometry: wgpu::Buffer,
|
||||
queue: wgpu::Queue,
|
||||
}
|
||||
impl PresentationBlit {
|
||||
pub fn new(pixels: &Pixels<'_>) -> Self {
|
||||
let device = pixels.device();
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("native-nearest-blit"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
r#"
|
||||
struct Vertex { @builtin(position) position: vec4f, @location(0) uv: vec2f }
|
||||
@vertex fn vs(@builtin(vertex_index) i: u32) -> Vertex {
|
||||
let p = array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));
|
||||
var v: Vertex; v.position=vec4f(p[i],0,1); v.uv=vec2f((p[i].x+1)*0.5,(1-p[i].y)*0.5); return v;
|
||||
}
|
||||
@group(0) @binding(0) var image: texture_2d<f32>;
|
||||
@group(0) @binding(1) var<uniform> geometry: vec4f;
|
||||
@fragment fn fs(v: Vertex) -> @location(0) vec4f {
|
||||
let size=vec2i(textureDimensions(image));
|
||||
let pixel=clamp(vec2i(floor((v.position.xy-geometry.xy)/geometry.z)),vec2i(0),size-vec2i(1));
|
||||
return textureLoad(image,pixel,0);
|
||||
}"#
|
||||
.into(),
|
||||
),
|
||||
});
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("native-nearest-blit"),
|
||||
layout: None,
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: pixels.render_texture_format(),
|
||||
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let view = pixels.context().texture.create_view(&Default::default());
|
||||
let geometry = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("native-viewport"),
|
||||
size: 16,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let texture = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("native-nearest-texture"),
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&view),
|
||||
},
|
||||
wgpu::BindGroupEntry { binding: 1, resource: geometry.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
Self { pipeline, texture, geometry, queue: pixels.context().queue.clone() }
|
||||
}
|
||||
pub fn render(
|
||||
&self,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
target: &wgpu::TextureView,
|
||||
viewport: Viewport,
|
||||
) {
|
||||
let geometry = [viewport.x, viewport.y, viewport.scale, 0.0].map(f32::to_ne_bytes);
|
||||
self.queue.write_buffer(&self.geometry, 0, geometry.as_flattened());
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("native-nearest-present"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: target,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, &self.texture, &[]);
|
||||
pass.set_viewport(viewport.x, viewport.y, viewport.width, viewport.height, 0.0, 1.0);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,7 @@ pub struct HostRunner {
|
||||
window: Option<&'static Window>,
|
||||
/// The pixel buffer interface for rendering to the GPU.
|
||||
pixels: Option<Pixels<'static>>,
|
||||
blit: Option<crate::presentation_blit::PresentationBlit>,
|
||||
|
||||
/// The instance of the virtual hardware peripherals.
|
||||
hardware: Hardware,
|
||||
@@ -151,6 +152,7 @@ pub struct HostRunner {
|
||||
render_frame_store: LatestRenderFrameStore,
|
||||
/// Tracks whether a new logical frame or host-only surface invalidation requires presentation.
|
||||
presentation: PresentationState,
|
||||
studio_capture: bool,
|
||||
}
|
||||
|
||||
impl HostRunner {
|
||||
@@ -194,7 +196,7 @@ impl HostRunner {
|
||||
|
||||
/// Creates a new desktop runner instance.
|
||||
pub(crate) fn new(fs_root: Option<String>, cap_config: Option<CertificationConfig>) -> Self {
|
||||
let target_fps = 60;
|
||||
let target_fps = prometeu_hal::graphics_contract::REFRESH_HZ;
|
||||
|
||||
let mut firmware = Firmware::new(cap_config);
|
||||
if let Some(root) = &fs_root {
|
||||
@@ -224,12 +226,13 @@ impl HostRunner {
|
||||
Self {
|
||||
window: None,
|
||||
pixels: None,
|
||||
blit: None,
|
||||
hardware,
|
||||
firmware,
|
||||
input: HostInputHandler::new(display_size),
|
||||
fs_root,
|
||||
log_sink: HostConsoleSink::new(),
|
||||
frame_target_dt: Duration::from_nanos(1_000_000_000 / target_fps),
|
||||
frame_target_dt: Duration::from_nanos(1_000_000_000 / u64::from(target_fps)),
|
||||
last_frame_time: Instant::now(),
|
||||
accumulator: Duration::ZERO,
|
||||
|
||||
@@ -238,9 +241,161 @@ impl HostRunner {
|
||||
audio: HostAudio::new(),
|
||||
render_frame_store,
|
||||
presentation: PresentationState::default(),
|
||||
studio_capture: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One canonical interactive slice, shared by desktop and Studio pacing.
|
||||
fn tick_machine(&mut self) {
|
||||
self.audio.service();
|
||||
if !self.debugger.waiting_for_start {
|
||||
if self.studio_capture {
|
||||
let mut platform = crate::studio::platform::StudioPlatform {
|
||||
hardware: &mut self.hardware,
|
||||
store: &self.render_frame_store,
|
||||
};
|
||||
self.firmware.tick(&self.input.signals, &mut platform);
|
||||
} else {
|
||||
self.firmware.tick(&self.input.signals, &mut self.hardware);
|
||||
}
|
||||
self.stats.record_host_cpu_time(self.firmware.os.vm().last_frame_cpu_time_us());
|
||||
}
|
||||
self.hardware.audio.set_paused(
|
||||
self.firmware.game_lifecycle_audio_paused()
|
||||
|| self.firmware.os.vm().paused()
|
||||
|| self.debugger.waiting_for_start,
|
||||
);
|
||||
self.audio.service();
|
||||
}
|
||||
|
||||
pub(crate) fn studio_audio_init(&mut self) {
|
||||
if let Err(error) = self.audio.init(self.hardware.audio.transport()) {
|
||||
eprintln!("[HostAudio] Disabled: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn studio_boot_step(&mut self, disposable: bool) -> Result<bool, String> {
|
||||
self.studio_capture = true;
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(true);
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
return Err("Cartridge failed during Studio boot".into());
|
||||
}
|
||||
self.firmware.os.memcard().poll(Instant::now());
|
||||
if let FirmwareState::LoadCartridge(step) = &mut self.firmware.state
|
||||
&& step.needs_memcard_choice()
|
||||
&& !self.firmware.os.memcard().preparation_active()
|
||||
{
|
||||
let choice = if disposable {
|
||||
prometeu_system::memcard::admission::Choice::MemoryFresh
|
||||
} else {
|
||||
prometeu_system::memcard::admission::Choice::Persistent
|
||||
};
|
||||
step.choose_memcard(
|
||||
&mut self.firmware.os,
|
||||
choice,
|
||||
self.hardware.wall_clock().utc_unix_seconds(),
|
||||
)
|
||||
.map_err(|e| format!("Studio save selection failed: {e:?}"))?;
|
||||
}
|
||||
self.tick_machine();
|
||||
self.studio_logs();
|
||||
Ok(matches!(self.firmware.state, FirmwareState::GameRunning(_)))
|
||||
}
|
||||
|
||||
pub(crate) fn studio_step(
|
||||
&mut self,
|
||||
signals: prometeu_hal::InputSignals,
|
||||
) -> Result<(), String> {
|
||||
self.input.signals = signals;
|
||||
self.tick_machine();
|
||||
self.studio_logs();
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
return Err("Cartridge faulted during Studio Play".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn studio_pause(&mut self, paused: bool) {
|
||||
self.input.clear_guest_signals();
|
||||
self.firmware.os.vm().set_paused(paused);
|
||||
self.hardware.audio.set_paused(paused);
|
||||
self.audio.service();
|
||||
}
|
||||
|
||||
pub(crate) fn studio_dimensions(&self) -> (usize, usize) {
|
||||
self.hardware.display_size()
|
||||
}
|
||||
pub(crate) fn studio_tick_index(&mut self) -> u64 {
|
||||
self.firmware.os.frame_index()
|
||||
}
|
||||
|
||||
pub(crate) fn studio_frame(
|
||||
&mut self,
|
||||
previous: Option<(RenderOwnership, prometeu_hal::FrameId)>,
|
||||
) -> Option<OwnedRgba8888Frame> {
|
||||
let active = self.firmware.os.vm().active_render_ownership();
|
||||
self.render_frame_store
|
||||
.latest_frame_after(previous)
|
||||
.filter(|frame| should_present_worker_frame(&self.firmware.state, frame, active))
|
||||
}
|
||||
|
||||
fn studio_logs(&mut self) {
|
||||
let last = self.log_sink.last_seq();
|
||||
let events = match last {
|
||||
Some(seq) => self.firmware.os.logs_after(seq),
|
||||
None => self.firmware.os.recent_logs(4096),
|
||||
};
|
||||
self.log_sink.process_events(events);
|
||||
}
|
||||
|
||||
pub(crate) fn studio_stop(&mut self, disposable: bool) -> Result<(), String> {
|
||||
self.studio_pause(true);
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
let service = self.firmware.os.memcard();
|
||||
service.poll(Instant::now());
|
||||
if !service.session.io_active()
|
||||
&& !service.session.has_deferred_write()
|
||||
&& !service.preparation_active()
|
||||
{
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err("Save IO has not finished; retry Stop".into());
|
||||
}
|
||||
let lane = service.lane.clone();
|
||||
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
|
||||
}
|
||||
if self.firmware.os.memcard().session.unsaved() && !disposable {
|
||||
return Err("Unsaved game data; resume and save before stopping".into());
|
||||
}
|
||||
self.firmware
|
||||
.os
|
||||
.stop_background_io()
|
||||
.map_err(|e| format!("Save shutdown failed: {e:?}"))?;
|
||||
self.firmware.os.memcard().session.end_session();
|
||||
self.firmware.os.memcard().poll(Instant::now());
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.uninstall_card()
|
||||
.map_err(|e| format!("Save detach failed: {e:?}"))?;
|
||||
self.firmware
|
||||
.os
|
||||
.vm()
|
||||
.stop_render_worker()
|
||||
.map_err(|e| format!("Render shutdown failed: {e:?}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn studio_abort(&mut self) {
|
||||
self.studio_pause(true);
|
||||
let _ = self.firmware.os.vm().stop_render_worker();
|
||||
let _ = self.firmware.os.stop_background_io();
|
||||
}
|
||||
|
||||
fn window(&self) -> &'static Window {
|
||||
self.window.expect("window not created yet")
|
||||
}
|
||||
@@ -277,15 +432,32 @@ impl HostRunner {
|
||||
fn machine_running(&mut self) -> bool {
|
||||
!self.firmware.os.vm().paused() && !self.debugger.waiting_for_start
|
||||
}
|
||||
|
||||
fn observe_latest_frame(&mut self) {
|
||||
let active_ownership = self.firmware.os.vm().active_render_ownership();
|
||||
if let Some(worker_frame) = self.render_frame_store.latest_frame()
|
||||
&& should_present_worker_frame(&self.firmware.state, &worker_frame, active_ownership)
|
||||
{
|
||||
self.presentation
|
||||
.note_published_frame(worker_frame.ownership, worker_frame.frame_id.get());
|
||||
} else {
|
||||
// Observe the actual front-buffer swap, including native Hub/Shell
|
||||
// publications which do not execute a VM frame.
|
||||
let publication = self.hardware.gfx.publication_count();
|
||||
if publication > 0 {
|
||||
self.presentation.note_published_frame(active_ownership, publication);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for HostRunner {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let attrs = WindowAttributes::default()
|
||||
.with_title(format!(
|
||||
"PROMETEU | GFX: {:.1} KB | FPS: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {} done {}",
|
||||
"PROMETEU | GFX: {:.1} KB | Host ticks/s: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {} done {}",
|
||||
0.0, 0.0, 0.0, 0, 0, 0, 0))
|
||||
.with_inner_size(LogicalSize::new(960.0, 540.0))
|
||||
.with_inner_size(LogicalSize::new((prometeu_hal::graphics_contract::WIDTH * 2) as f64, (prometeu_hal::graphics_contract::HEIGHT * 2) as f64))
|
||||
.with_min_inner_size(LogicalSize::new(320.0, 180.0));
|
||||
|
||||
let window = event_loop.create_window(attrs).expect("failed to create window");
|
||||
@@ -307,6 +479,7 @@ impl ApplicationHandler for HostRunner {
|
||||
|
||||
pixels.frame_mut().fill(0);
|
||||
|
||||
self.blit = Some(crate::presentation_blit::PresentationBlit::new(&pixels));
|
||||
self.pixels = Some(pixels);
|
||||
|
||||
if let Err(err) = self.audio.init(self.hardware.audio.transport()) {
|
||||
@@ -337,9 +510,16 @@ impl ApplicationHandler for HostRunner {
|
||||
self.request_redraw_if_needed();
|
||||
}
|
||||
|
||||
WindowEvent::Occluded(false) => {
|
||||
self.invalidate_host_surface();
|
||||
self.request_redraw_if_needed();
|
||||
}
|
||||
|
||||
WindowEvent::RedrawRequested => {
|
||||
let pixels = self.pixels.as_mut().expect("pixels not initialized");
|
||||
|
||||
let mut presented_worker = None;
|
||||
let mut presented_frame = None;
|
||||
{
|
||||
let frame = pixels.frame_mut();
|
||||
|
||||
@@ -351,20 +531,47 @@ impl ApplicationHandler for HostRunner {
|
||||
active_ownership,
|
||||
)
|
||||
{
|
||||
self.firmware
|
||||
.os
|
||||
.vm()
|
||||
.record_repeated_render_worker_frame(worker_frame.frame_id);
|
||||
presented_worker = Some((worker_frame.ownership, worker_frame.frame_id));
|
||||
presented_frame =
|
||||
Some((worker_frame.ownership, worker_frame.frame_id.get()));
|
||||
draw_owned_rgba8888_frame_to_rgba8(&worker_frame, frame);
|
||||
} else {
|
||||
let src = self.hardware.gfx.front_buffer();
|
||||
draw_rgba8888_to_rgba8(src, frame);
|
||||
let publication = self.hardware.gfx.publication_count();
|
||||
if publication > 0 {
|
||||
presented_frame = Some((active_ownership, publication));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if pixels.render().is_err() {
|
||||
let size = self.window.expect("window").inner_size();
|
||||
let rendered = std::cell::Cell::new(false);
|
||||
let viewport = crate::viewport::Viewport::new(
|
||||
(size.width, size.height),
|
||||
self.hardware.display_size(),
|
||||
);
|
||||
let present_start = Instant::now();
|
||||
let result = pixels.render_with(|encoder, target, _| {
|
||||
if let Some(viewport) = viewport {
|
||||
self.blit.as_ref().expect("blit").render(encoder, target, viewport);
|
||||
rendered.set(true);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
self.stats.record_present_time(present_start.elapsed());
|
||||
if result.is_err() {
|
||||
event_loop.exit();
|
||||
} else {
|
||||
} else if rendered.get() {
|
||||
if let Some((ownership, frame_id)) = presented_frame {
|
||||
self.stats.record_presented(ownership, frame_id);
|
||||
}
|
||||
if let Some((ownership, frame_id)) = presented_worker {
|
||||
self.firmware
|
||||
.os
|
||||
.vm()
|
||||
.record_presented_render_worker_frame(ownership, frame_id);
|
||||
}
|
||||
self.presentation.mark_presented();
|
||||
}
|
||||
}
|
||||
@@ -435,34 +642,12 @@ impl ApplicationHandler for HostRunner {
|
||||
while self.accumulator >= self.frame_target_dt {
|
||||
// Reclaim returned audio owners before another guest attempt, even
|
||||
// when the previous attempt paused or stopped at backpressure.
|
||||
self.audio.service();
|
||||
// Unless the debugger is waiting for a 'start' command, advance the system.
|
||||
if !self.debugger.waiting_for_start {
|
||||
self.firmware.tick(&self.input.signals, &mut self.hardware);
|
||||
self.stats.record_host_cpu_time(self.firmware.os.vm().last_frame_cpu_time_us());
|
||||
}
|
||||
|
||||
let is_paused = self.firmware.game_lifecycle_audio_paused()
|
||||
|| self.firmware.os.vm().paused()
|
||||
|| self.debugger.waiting_for_start;
|
||||
self.hardware.audio.set_paused(is_paused);
|
||||
self.audio.service();
|
||||
self.tick_machine();
|
||||
|
||||
self.accumulator -= self.frame_target_dt;
|
||||
self.stats.record_frame();
|
||||
}
|
||||
|
||||
let active_ownership = self.firmware.os.vm().active_render_ownership();
|
||||
if let Some(worker_frame) = self.render_frame_store.latest_frame()
|
||||
&& should_present_worker_frame(&self.firmware.state, &worker_frame, active_ownership)
|
||||
{
|
||||
self.presentation
|
||||
.note_published_frame(worker_frame.ownership, worker_frame.frame_id.get());
|
||||
} else {
|
||||
self.presentation
|
||||
.note_published_frame(active_ownership, self.firmware.os.frame_index());
|
||||
}
|
||||
|
||||
if was_debugger_connected != self.debugger.stream.is_some()
|
||||
|| was_waiting_for_start != self.debugger.waiting_for_start
|
||||
|| was_paused != self.firmware.os.vm().paused()
|
||||
@@ -471,6 +656,7 @@ impl ApplicationHandler for HostRunner {
|
||||
}
|
||||
|
||||
// 4. Feedback and Synchronization.
|
||||
self.observe_latest_frame();
|
||||
self.audio.update_stats(&mut self.stats);
|
||||
|
||||
// Update technical statistics displayed in the window title.
|
||||
@@ -500,6 +686,73 @@ impl ApplicationHandler for HostRunner {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn studio_can_boot_and_publish_without_a_window() {
|
||||
let cart = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../../test-cartridges/dummy-boy");
|
||||
let mut host = HostRunner::new(None, None);
|
||||
host.set_boot_target(BootTarget::Cartridge {
|
||||
path: cart.to_string_lossy().into_owned(),
|
||||
debug: false,
|
||||
debug_port: 0,
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !host.studio_boot_step(true).unwrap() {
|
||||
assert!(Instant::now() < deadline);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
host.studio_pause(true);
|
||||
host.studio_pause(false);
|
||||
for _ in 0..60 {
|
||||
host.studio_step(Default::default()).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
let frame = host.studio_frame(None);
|
||||
let published = host.render_frame_store.latest_frame().map(|f| (f.frame_id, f.ownership));
|
||||
let active = host.firmware.os.vm().active_render_ownership();
|
||||
assert!(
|
||||
frame.is_some(),
|
||||
"store {published:?}, owner {active:?}, state {:?}, frame {}",
|
||||
host.firmware.state,
|
||||
host.firmware.os.frame_index()
|
||||
);
|
||||
let frame = frame.unwrap();
|
||||
assert!(host.studio_frame(Some((frame.ownership, frame.frame_id))).is_none());
|
||||
// Exercise the same audio transport/callback through Studio lifecycle,
|
||||
// without requiring a physical output device in this contract test.
|
||||
use prometeu_hal::{AudioBridge, LoopMode, sample::Sample};
|
||||
let (mut callback, mut reclaimer) = crate::audio::AudioCallback::new();
|
||||
assert_eq!(
|
||||
host.hardware.audio.play_sample(
|
||||
Arc::new(Sample::new(48000, vec![1000; 32])),
|
||||
0,
|
||||
255,
|
||||
0,
|
||||
1.0,
|
||||
0,
|
||||
LoopMode::On,
|
||||
),
|
||||
prometeu_hal::AudioOpStatus::Ok
|
||||
);
|
||||
host.hardware.audio.finish_frame();
|
||||
let transport = host.hardware.audio.transport();
|
||||
let mut pcm = [0.0; 64];
|
||||
callback.render(&transport, &mut pcm);
|
||||
assert!(pcm.iter().any(|sample| *sample != 0.0));
|
||||
reclaimer.service(&transport);
|
||||
host.studio_pause(true);
|
||||
callback.render(&transport, &mut pcm);
|
||||
assert!(pcm.iter().all(|sample| *sample == 0.0));
|
||||
reclaimer.service(&transport);
|
||||
host.studio_pause(false);
|
||||
callback.render(&transport, &mut pcm);
|
||||
assert!(pcm.iter().any(|sample| *sample != 0.0));
|
||||
reclaimer.service(&transport);
|
||||
host.studio_stop(true).unwrap();
|
||||
callback.render(&transport, &mut pcm);
|
||||
assert!(pcm.iter().all(|sample| *sample == 0.0));
|
||||
}
|
||||
use prometeu_firmware::BootTarget;
|
||||
use prometeu_firmware::firmware::firmware_state::{
|
||||
GameRunningStep, HubHomeStep, ShellRunningStep,
|
||||
@@ -544,6 +797,15 @@ mod tests {
|
||||
for _ in 0..8 {
|
||||
runner.firmware.tick(&signals, &mut runner.hardware);
|
||||
}
|
||||
// Successful session publications must drive redraw even when the
|
||||
// physical surface has not otherwise been invalidated.
|
||||
let completed = runner.firmware.os.vm().logical_frame_index();
|
||||
assert!(completed > 0, "session published a frame in boot {cycle}");
|
||||
runner.observe_latest_frame();
|
||||
runner.presentation.mark_presented();
|
||||
runner.firmware.tick(&signals, &mut runner.hardware);
|
||||
runner.observe_latest_frame();
|
||||
assert!(runner.presentation.needs_redraw(), "new session frame must redraw");
|
||||
runner.firmware.request_home_from_host();
|
||||
for _ in 0..32 {
|
||||
runner.firmware.tick(&signals, &mut runner.hardware);
|
||||
@@ -552,6 +814,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
assert!(matches!(runner.firmware.state, FirmwareState::HubHome(_)), "home {cycle}");
|
||||
runner.observe_latest_frame();
|
||||
runner.presentation.mark_presented();
|
||||
let vm_frame = runner.firmware.os.vm().logical_frame_index();
|
||||
runner.firmware.tick(&signals, &mut runner.hardware);
|
||||
assert_eq!(runner.firmware.os.vm().logical_frame_index(), vm_frame);
|
||||
runner.observe_latest_frame();
|
||||
assert!(
|
||||
runner.presentation.needs_redraw(),
|
||||
"native Hub publication must redraw without a VM frame"
|
||||
);
|
||||
assert!(runner.firmware.resume_resident_game_from_home());
|
||||
for _ in 0..8 {
|
||||
runner.firmware.tick(&signals, &mut runner.hardware);
|
||||
|
||||
@@ -4,6 +4,13 @@ use winit::window::Window;
|
||||
|
||||
pub struct HostStats {
|
||||
pub last_stats_update: Instant,
|
||||
metrics_path: Option<std::path::PathBuf>,
|
||||
present_us: Vec<u64>,
|
||||
present_count: u64,
|
||||
ticks_total: u64,
|
||||
first_presentations: u64,
|
||||
repeated_presentations: u64,
|
||||
last_presented: Option<(prometeu_hal::RenderOwnership, u64)>,
|
||||
pub frames_since_last_update: u64,
|
||||
pub current_fps: f64,
|
||||
pub audio_load_accum_us: u64,
|
||||
@@ -23,6 +30,13 @@ impl HostStats {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
last_stats_update: Instant::now(),
|
||||
metrics_path: std::env::var_os("PROMETEU_GRAPHICS_METRICS").map(Into::into),
|
||||
present_us: Vec::new(),
|
||||
present_count: 0,
|
||||
ticks_total: 0,
|
||||
first_presentations: 0,
|
||||
repeated_presentations: 0,
|
||||
last_presented: None,
|
||||
frames_since_last_update: 0,
|
||||
current_fps: 0.0,
|
||||
audio_load_accum_us: 0,
|
||||
@@ -33,8 +47,31 @@ impl HostStats {
|
||||
}
|
||||
}
|
||||
|
||||
/// API latency, including texture upload/submit; not a physical scanout timestamp.
|
||||
pub fn record_present_time(&mut self, duration: Duration) {
|
||||
self.present_count += 1;
|
||||
if self.metrics_path.is_some() {
|
||||
let value = duration.as_micros() as u64;
|
||||
if self.present_us.len() < 16384 {
|
||||
self.present_us.push(value);
|
||||
} else {
|
||||
self.present_us[(self.present_count as usize - 1) % 16384] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn record_frame(&mut self) {
|
||||
self.frames_since_last_update += 1;
|
||||
self.ticks_total += 1;
|
||||
}
|
||||
|
||||
pub fn record_presented(&mut self, ownership: prometeu_hal::RenderOwnership, frame_id: u64) {
|
||||
let marker = (ownership, frame_id);
|
||||
if self.last_presented == Some(marker) {
|
||||
self.repeated_presentations += 1;
|
||||
} else {
|
||||
self.first_presentations += 1;
|
||||
}
|
||||
self.last_presented = Some(marker);
|
||||
}
|
||||
|
||||
pub fn record_audio_perf(&mut self, us: u64) {
|
||||
@@ -66,7 +103,8 @@ impl HostStats {
|
||||
|
||||
if let Some(window) = window {
|
||||
// Fixed comparison always against 60Hz, keep even when doing CPU stress tests
|
||||
let frame_budget_us = 16666.0;
|
||||
let frame_budget_us =
|
||||
1_000_000.0 / prometeu_hal::graphics_contract::REFRESH_HZ as f64;
|
||||
let cpu_load_core = (self.average_host_cpu_ms() * 1000.0 / frame_budget_us) * 100.0;
|
||||
|
||||
let cpu_load_audio = if self.audio_load_samples > 0 {
|
||||
@@ -76,7 +114,7 @@ impl HostStats {
|
||||
};
|
||||
|
||||
let title = format!(
|
||||
"PROMETEU | GFX: {:.1} KB | FPS: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {} done {}",
|
||||
"PROMETEU | GFX: {:.1} KB | Host ticks/s: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {} done {}",
|
||||
0,
|
||||
self.current_fps,
|
||||
cpu_load_core,
|
||||
@@ -95,3 +133,41 @@ impl HostStats {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HostStats {
|
||||
fn drop(&mut self) {
|
||||
if let Some(path) = &self.metrics_path {
|
||||
self.present_us.sort_unstable();
|
||||
let n = self.present_us.len();
|
||||
let percentile =
|
||||
|p: usize| if n == 0 { 0 } else { self.present_us[(n * p).div_ceil(100) - 1] };
|
||||
let report = serde_json::json!({"schema":1,"host_ticks":self.ticks_total,
|
||||
"first_presentations":self.first_presentations,"repeated_presentations":self.repeated_presentations,
|
||||
"present_api_calls":self.present_count,"samples":n,
|
||||
"present_api_mean_us":if n==0 {0.0} else {self.present_us.iter().sum::<u64>() as f64/n as f64},
|
||||
"present_api_p95_us":percentile(95),"present_api_p99_us":percentile(99),
|
||||
"present_api_max_us":self.present_us.last().copied().unwrap_or(0),
|
||||
"present_api_over_budget":self.present_us.iter().filter(|&&v|v > 1_000_000 / u64::from(prometeu_hal::graphics_contract::REFRESH_HZ)).count(),
|
||||
"physical_display_hz":null,"limitation":"bounded last 16384 API samples; API upload/submit/present time is not scanout latency"});
|
||||
if let Err(error) = std::fs::write(path, report.to_string()) {
|
||||
eprintln!("graphics metrics: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use prometeu_hal::{RenderOwnership, app_mode::AppMode};
|
||||
#[test]
|
||||
fn host_counts_actual_submissions_by_identity_and_epoch() {
|
||||
let mut stats = HostStats::new();
|
||||
let first = RenderOwnership::new(1, AppMode::Game, 2);
|
||||
stats.record_presented(first, 0);
|
||||
stats.record_presented(first, 0);
|
||||
stats.record_presented(RenderOwnership::new(2, AppMode::Game, 2), 0);
|
||||
assert_eq!(stats.first_presentations, 2);
|
||||
assert_eq!(stats.repeated_presentations, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Interactive Play integration, separate from the automation host.
|
||||
pub(crate) mod platform;
|
||||
mod transport;
|
||||
pub mod wire;
|
||||
|
||||
use crate::runner::HostRunner;
|
||||
use prometeu_hal::InputSignals;
|
||||
use std::{
|
||||
io,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use transport::Transport;
|
||||
use wire::*;
|
||||
|
||||
fn number64(p: &[u8]) -> u64 {
|
||||
u64::from_le_bytes(p.try_into().unwrap())
|
||||
}
|
||||
fn result(
|
||||
transport: &Transport,
|
||||
command: u16,
|
||||
request: u64,
|
||||
status: u16,
|
||||
epoch: u64,
|
||||
tick: u64,
|
||||
text: &str,
|
||||
) -> io::Result<()> {
|
||||
let mut p = Vec::with_capacity(20 + text.len());
|
||||
p.extend_from_slice(&command.to_le_bytes());
|
||||
p.extend_from_slice(&status.to_le_bytes());
|
||||
p.extend_from_slice(&epoch.to_le_bytes());
|
||||
p.extend_from_slice(&tick.to_le_bytes());
|
||||
p.extend_from_slice(text.as_bytes());
|
||||
transport.send(RESULT, request, p)
|
||||
}
|
||||
fn input(p: &[u8], width: usize, height: usize) -> io::Result<(u64, InputSignals)> {
|
||||
if p.len() != 20 {
|
||||
return Err(invalid("Invalid Studio input length"));
|
||||
}
|
||||
let mask = u16::from_le_bytes(p[8..10].try_into().unwrap());
|
||||
if mask & !0x1fff != 0 || p[10..12] != [0, 0] {
|
||||
return Err(invalid("Invalid Studio input bits"));
|
||||
}
|
||||
let x = i32::from_le_bytes(p[12..16].try_into().unwrap());
|
||||
let y = i32::from_le_bytes(p[16..20].try_into().unwrap());
|
||||
if mask & 0x1000 != 0 && (x < 0 || y < 0 || x as usize >= width || y as usize >= height) {
|
||||
return Err(invalid("Studio touch outside display"));
|
||||
}
|
||||
let bit = |n: u16| mask & (1u16 << n) != 0;
|
||||
Ok((
|
||||
number64(&p[..8]),
|
||||
InputSignals {
|
||||
up_signal: bit(0),
|
||||
down_signal: bit(1),
|
||||
left_signal: bit(2),
|
||||
right_signal: bit(3),
|
||||
a_signal: bit(4),
|
||||
b_signal: bit(5),
|
||||
x_signal: bit(6),
|
||||
y_signal: bit(7),
|
||||
l_signal: bit(8),
|
||||
r_signal: bit(9),
|
||||
start_signal: bit(10),
|
||||
select_signal: bit(11),
|
||||
f_signal: bit(12),
|
||||
x_pos: x,
|
||||
y_pos: y,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn run(mut runner: HostRunner, boot: Bootstrap) -> io::Result<()> {
|
||||
let transport = Transport::connect(&boot)?;
|
||||
runner.studio_audio_init();
|
||||
let (width, height) = runner.studio_dimensions();
|
||||
frame_bytes(width as u32, height as u32, width as u32)?;
|
||||
let mut ready = false;
|
||||
let mut started = false;
|
||||
let mut state = 0u32;
|
||||
let mut epoch = 1u64;
|
||||
let mut signals = InputSignals::default();
|
||||
let mut next_tick = Instant::now();
|
||||
let boot_deadline = Instant::now() + Duration::from_secs(10);
|
||||
let slice = Duration::from_nanos(
|
||||
1_000_000_000 / u64::from(prometeu_hal::graphics_contract::REFRESH_HZ),
|
||||
);
|
||||
let mut last_request = 0;
|
||||
let mut last_frame = None;
|
||||
let outcome = (|| -> io::Result<()> {
|
||||
loop {
|
||||
if let Some(error) = transport.failure() {
|
||||
return Err(invalid(&error));
|
||||
}
|
||||
if ready && transport.idle() > Duration::from_secs(5) {
|
||||
return Err(invalid("Studio control heartbeat expired"));
|
||||
}
|
||||
for _ in 0..64 {
|
||||
let Some(message) = transport.next() else {
|
||||
break;
|
||||
};
|
||||
let h = message.header;
|
||||
if h.kind == INPUT {
|
||||
let (received, input) = input(&message.payload, width, height)?;
|
||||
if received == epoch && state == 1 {
|
||||
signals = input;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if h.kind == PING {
|
||||
if !message.payload.is_empty() {
|
||||
return Err(invalid("Invalid PING payload"));
|
||||
}
|
||||
let mut p = Vec::with_capacity(20);
|
||||
p.extend_from_slice(&epoch.to_le_bytes());
|
||||
p.extend_from_slice(&runner.studio_tick_index().to_le_bytes());
|
||||
p.extend_from_slice(&state.to_le_bytes());
|
||||
transport.send(PONG, h.request, p)?;
|
||||
continue;
|
||||
}
|
||||
if !matches!(h.kind, START | PAUSE | RESUME | STOP)
|
||||
|| !message.payload.is_empty()
|
||||
|| h.request == 0
|
||||
{
|
||||
return Err(invalid("Invalid Studio control command"));
|
||||
}
|
||||
if h.request <= last_request {
|
||||
result(
|
||||
&transport,
|
||||
h.kind,
|
||||
h.request,
|
||||
1,
|
||||
epoch,
|
||||
runner.studio_tick_index(),
|
||||
"Stale or duplicate request",
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
last_request = h.request;
|
||||
if h.kind == STOP {
|
||||
signals = InputSignals::default();
|
||||
state = 2;
|
||||
epoch = epoch.checked_add(1).ok_or_else(|| invalid("epoch exhausted"))?;
|
||||
match runner.studio_stop(boot.disposable) {
|
||||
Ok(()) => {
|
||||
result(
|
||||
&transport,
|
||||
STOP,
|
||||
h.request,
|
||||
0,
|
||||
epoch,
|
||||
runner.studio_tick_index(),
|
||||
"",
|
||||
)?;
|
||||
transport.finish(h.request)?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => {
|
||||
result(
|
||||
&transport,
|
||||
STOP,
|
||||
h.request,
|
||||
2,
|
||||
epoch,
|
||||
runner.studio_tick_index(),
|
||||
&error,
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ready {
|
||||
result(
|
||||
&transport,
|
||||
h.kind,
|
||||
h.request,
|
||||
1,
|
||||
epoch,
|
||||
runner.studio_tick_index(),
|
||||
"Cartridge is not ready",
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
match h.kind {
|
||||
START if state == 0 => {
|
||||
started = true;
|
||||
state = 1;
|
||||
runner.studio_pause(false);
|
||||
next_tick = Instant::now();
|
||||
}
|
||||
START if state == 2 && !started => {
|
||||
started = true;
|
||||
}
|
||||
PAUSE if state == 1 || state == 0 => {
|
||||
state = 2;
|
||||
epoch += 1;
|
||||
signals = InputSignals::default();
|
||||
runner.studio_pause(true);
|
||||
}
|
||||
RESUME if state == 2 && started => {
|
||||
state = 1;
|
||||
epoch += 1;
|
||||
signals = InputSignals::default();
|
||||
runner.studio_pause(false);
|
||||
next_tick = Instant::now();
|
||||
}
|
||||
PAUSE if state == 2 => {}
|
||||
RESUME if state == 1 => {}
|
||||
_ => {
|
||||
result(
|
||||
&transport,
|
||||
h.kind,
|
||||
h.request,
|
||||
1,
|
||||
epoch,
|
||||
runner.studio_tick_index(),
|
||||
"Invalid execution state",
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result(&transport, h.kind, h.request, 0, epoch, runner.studio_tick_index(), "")?;
|
||||
}
|
||||
if !ready {
|
||||
if Instant::now() > boot_deadline {
|
||||
return Err(invalid("Studio cartridge boot timed out"));
|
||||
}
|
||||
ready = runner.studio_boot_step(boot.disposable).map_err(|e| invalid(&e))?;
|
||||
if ready {
|
||||
runner.studio_pause(true);
|
||||
let mut p = Vec::new();
|
||||
for n in [
|
||||
width as u32,
|
||||
height as u32,
|
||||
prometeu_hal::graphics_contract::REFRESH_HZ,
|
||||
RGBA8,
|
||||
] {
|
||||
p.extend_from_slice(&n.to_le_bytes());
|
||||
}
|
||||
p.extend_from_slice(env!("CARGO_PKG_VERSION").as_bytes());
|
||||
transport.send(READY, 0, p)?;
|
||||
}
|
||||
} else if state == 1 && Instant::now() >= next_tick {
|
||||
runner.studio_step(signals).map_err(|e| invalid(&e))?;
|
||||
next_tick += slice;
|
||||
if next_tick + Duration::from_millis(100) < Instant::now() {
|
||||
next_tick = Instant::now();
|
||||
}
|
||||
}
|
||||
// Completion is asynchronous and can arrive after Pause stopped logical ticks.
|
||||
if ready && let Some(frame) = runner.studio_frame(last_frame) {
|
||||
last_frame = Some((frame.ownership, frame.frame_id));
|
||||
transport.publish(epoch, frame);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
})();
|
||||
if let Err(error) = &outcome {
|
||||
eprintln!("[Studio] {error}");
|
||||
let _ = transport.send(ERROR, 0, error.to_string().into_bytes());
|
||||
runner.studio_abort();
|
||||
}
|
||||
outcome
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Observe complete synchronous submissions without changing machine/render semantics.
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_hal::*;
|
||||
use prometeu_system::LatestRenderFrameStore;
|
||||
|
||||
pub(crate) struct StudioPlatform<'a> {
|
||||
pub hardware: &'a mut Hardware,
|
||||
pub store: &'a LatestRenderFrameStore,
|
||||
}
|
||||
impl RenderSubmissionSink for StudioPlatform<'_> {
|
||||
fn submit_render_submission(
|
||||
&mut self,
|
||||
submission: RenderSubmission,
|
||||
) -> Result<(), RenderSubmitError> {
|
||||
let marker = (submission.frame_id, submission.ownership);
|
||||
self.hardware.submit_render_submission(submission)?;
|
||||
if marker.1.app_mode == app_mode::AppMode::Game {
|
||||
let (w, h) = self.hardware.display_size();
|
||||
let frame = OwnedRgba8888Frame::packed(
|
||||
marker.0,
|
||||
marker.1,
|
||||
w,
|
||||
h,
|
||||
self.hardware.gfx.front_buffer().to_vec(),
|
||||
)
|
||||
.map_err(|_| RenderSubmitError::SubmissionRejected)?;
|
||||
self.store.publish_frame(frame);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl RuntimePlatform for StudioPlatform<'_> {
|
||||
fn wall_clock(&self) -> &dyn WallClock {
|
||||
self.hardware.wall_clock()
|
||||
}
|
||||
fn display_size(&self) -> (usize, usize) {
|
||||
self.hardware.display_size()
|
||||
}
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||
self
|
||||
}
|
||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||
self.hardware
|
||||
}
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||
self.hardware
|
||||
}
|
||||
fn audio(&self) -> &dyn AudioBridge {
|
||||
self.hardware.audio()
|
||||
}
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||
self.hardware.audio_mut()
|
||||
}
|
||||
fn input(&self) -> &dyn InputPlatform {
|
||||
self.hardware.input()
|
||||
}
|
||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||
self.hardware.input_mut()
|
||||
}
|
||||
fn assets(&self) -> &dyn AssetBridge {
|
||||
self.hardware.assets()
|
||||
}
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||
self.hardware.assets_mut()
|
||||
}
|
||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||
self.hardware.telemetry()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
use super::wire::*;
|
||||
use prometeu_hal::OwnedRgba8888Frame;
|
||||
use std::io::{self, Read};
|
||||
use std::net::{Ipv4Addr, Shutdown, SocketAddr, TcpStream};
|
||||
use std::sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::{self, Receiver, SyncSender},
|
||||
};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct Publication {
|
||||
epoch: u64,
|
||||
frame: Arc<OwnedRgba8888Frame>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Video {
|
||||
latest: Option<Publication>,
|
||||
flight: Option<(u64, u64)>,
|
||||
}
|
||||
struct Shared {
|
||||
video: Mutex<Video>,
|
||||
wake: Condvar,
|
||||
closed: AtomicBool,
|
||||
failure: Mutex<Option<String>>,
|
||||
activity: Mutex<Instant>,
|
||||
}
|
||||
impl Shared {
|
||||
fn fail(&self, message: impl ToString) {
|
||||
if self.closed.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let mut failure = self.failure.lock().unwrap();
|
||||
if failure.is_none() {
|
||||
*failure = Some(message.to_string());
|
||||
}
|
||||
self.wake.notify_all();
|
||||
}
|
||||
fn stopped(&self) -> bool {
|
||||
self.closed.load(Ordering::Acquire) || self.failure.lock().unwrap().is_some()
|
||||
}
|
||||
}
|
||||
struct Outbound {
|
||||
kind: u16,
|
||||
request: u64,
|
||||
payload: Vec<u8>,
|
||||
flushed: Option<SyncSender<()>>,
|
||||
}
|
||||
|
||||
pub(super) struct Transport {
|
||||
shared: Arc<Shared>,
|
||||
outgoing: SyncSender<Outbound>,
|
||||
incoming: Receiver<Message>,
|
||||
control: TcpStream,
|
||||
video: TcpStream,
|
||||
workers: Vec<JoinHandle<()>>,
|
||||
}
|
||||
impl Transport {
|
||||
pub fn connect(boot: &Bootstrap) -> io::Result<Self> {
|
||||
fn connect(port: u16) -> io::Result<TcpStream> {
|
||||
let socket = TcpStream::connect_timeout(
|
||||
&SocketAddr::from((Ipv4Addr::LOCALHOST, port)),
|
||||
Duration::from_secs(5),
|
||||
)?;
|
||||
socket.set_nodelay(true)?;
|
||||
socket.set_write_timeout(Some(Duration::from_secs(2)))?;
|
||||
Ok(socket)
|
||||
}
|
||||
let control = connect(boot.control_port)?;
|
||||
let video = connect(boot.video_port)?;
|
||||
let mut writer = Writer::new(control.try_clone()?);
|
||||
writer.send(HELLO, 0, &boot.hello(1))?;
|
||||
let mut video_writer = Writer::new(video.try_clone()?);
|
||||
video_writer.send(HELLO, 0, &boot.hello(2))?;
|
||||
let shared = Arc::new(Shared {
|
||||
video: Mutex::new(Video::default()),
|
||||
wake: Condvar::new(),
|
||||
closed: AtomicBool::new(false),
|
||||
failure: Mutex::new(None),
|
||||
activity: Mutex::new(Instant::now()),
|
||||
});
|
||||
let (tx, rx) = mpsc::sync_channel::<Outbound>(256);
|
||||
let (commands, incoming) = mpsc::sync_channel(256);
|
||||
let mut workers = Vec::new();
|
||||
let state = shared.clone();
|
||||
workers.push(std::thread::Builder::new().name("studio-control-write".into()).spawn(
|
||||
move || {
|
||||
while !state.stopped() {
|
||||
let out = match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(out) => out,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(_) => break,
|
||||
};
|
||||
if let Err(error) = writer.send(out.kind, out.request, &out.payload) {
|
||||
state.fail(error);
|
||||
break;
|
||||
}
|
||||
if let Some(done) = out.flushed {
|
||||
let _ = done.send(());
|
||||
}
|
||||
}
|
||||
},
|
||||
)?);
|
||||
let state = shared.clone();
|
||||
let socket = control.try_clone()?;
|
||||
workers.push(std::thread::Builder::new().name("studio-control-read".into()).spawn(
|
||||
move || {
|
||||
let mut reader = Reader::new(socket);
|
||||
while !state.stopped() {
|
||||
let message = match reader.receive_control() {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
state.fail(format!("Studio control lost: {e}"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
*state.activity.lock().unwrap() = Instant::now();
|
||||
if message.header.kind == FRAME_RECEIVED {
|
||||
if message.payload.len() != 16 || message.header.request != 0 {
|
||||
state.fail("Invalid frame acknowledgement");
|
||||
break;
|
||||
}
|
||||
let p = &message.payload;
|
||||
let ack = (
|
||||
u64::from_le_bytes(p[..8].try_into().unwrap()),
|
||||
u64::from_le_bytes(p[8..].try_into().unwrap()),
|
||||
);
|
||||
let mut frames = state.video.lock().unwrap();
|
||||
if frames.flight != Some(ack) {
|
||||
drop(frames);
|
||||
state.fail("Unexpected frame acknowledgement");
|
||||
break;
|
||||
}
|
||||
frames.flight = None;
|
||||
state.wake.notify_all();
|
||||
} else if commands.try_send(message).is_err() {
|
||||
state.fail("Studio control queue saturated");
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
)?);
|
||||
let state = shared.clone();
|
||||
let session = boot.session;
|
||||
workers.push(std::thread::Builder::new().name("studio-video-write".into()).spawn(
|
||||
move || {
|
||||
let mut previous = None;
|
||||
let mut payload = Vec::new();
|
||||
while !state.stopped() {
|
||||
let (epoch, frame) = {
|
||||
let mut frames = state.video.lock().unwrap();
|
||||
loop {
|
||||
if state.stopped() {
|
||||
return;
|
||||
}
|
||||
if frames.flight.is_none()
|
||||
&& let Some(p) = &frames.latest
|
||||
{
|
||||
let marker = (p.epoch, p.frame.frame_id.get());
|
||||
if previous != Some(marker) {
|
||||
let result = (p.epoch, p.frame.clone());
|
||||
frames.flight = Some(marker);
|
||||
previous = Some(marker);
|
||||
break result;
|
||||
}
|
||||
}
|
||||
frames = state
|
||||
.wake
|
||||
.wait_timeout(frames, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.0;
|
||||
}
|
||||
};
|
||||
let size = match frame_bytes(
|
||||
frame.width as u32,
|
||||
frame.height as u32,
|
||||
frame.width as u32,
|
||||
) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
state.fail(e);
|
||||
break;
|
||||
}
|
||||
};
|
||||
payload.clear();
|
||||
payload.reserve(FRAME_METADATA_BYTES + size);
|
||||
payload.extend_from_slice(&session);
|
||||
payload.extend_from_slice(&epoch.to_le_bytes());
|
||||
payload.extend_from_slice(&frame.frame_id.get().to_le_bytes());
|
||||
for n in [frame.width as u32, frame.height as u32, frame.width as u32, RGBA8] {
|
||||
payload.extend_from_slice(&n.to_le_bytes());
|
||||
}
|
||||
for y in 0..frame.height {
|
||||
for pixel in &frame.pixels
|
||||
[y * frame.stride_pixels..y * frame.stride_pixels + frame.width]
|
||||
{
|
||||
payload.extend_from_slice(&pixel.to_be_bytes());
|
||||
}
|
||||
}
|
||||
if let Err(e) = video_writer.send(FRAME, 0, &payload) {
|
||||
state.fail(format!("Studio video lost: {e}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
)?);
|
||||
let state = shared.clone();
|
||||
let mut watch = video.try_clone()?;
|
||||
workers.push(std::thread::Builder::new().name("studio-video-watch".into()).spawn(
|
||||
move || {
|
||||
let mut byte = [0];
|
||||
match watch.read(&mut byte) {
|
||||
Ok(0) => state.fail("Studio video connection closed"),
|
||||
Ok(_) => state.fail("Unexpected data on video channel"),
|
||||
Err(e) => state.fail(format!("Studio video connection failed: {e}")),
|
||||
}
|
||||
},
|
||||
)?);
|
||||
Ok(Self { shared, outgoing: tx, incoming, control, video, workers })
|
||||
}
|
||||
pub fn send(&self, kind: u16, request: u64, payload: Vec<u8>) -> io::Result<()> {
|
||||
self.outgoing
|
||||
.try_send(Outbound { kind, request, payload, flushed: None })
|
||||
.map_err(|_| invalid("Studio output queue unavailable"))
|
||||
}
|
||||
pub fn finish(&self, request: u64) -> io::Result<()> {
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
self.outgoing
|
||||
.try_send(Outbound { kind: STOPPED, request, payload: Vec::new(), flushed: Some(tx) })
|
||||
.map_err(|_| invalid("Studio output queue unavailable"))?;
|
||||
rx.recv_timeout(Duration::from_secs(2))
|
||||
.map_err(|_| invalid("Studio shutdown acknowledgement failed"))
|
||||
}
|
||||
pub fn next(&self) -> Option<Message> {
|
||||
self.incoming.try_recv().ok()
|
||||
}
|
||||
pub fn failure(&self) -> Option<String> {
|
||||
self.shared.failure.lock().unwrap().clone()
|
||||
}
|
||||
pub fn idle(&self) -> Duration {
|
||||
self.shared.activity.lock().unwrap().elapsed()
|
||||
}
|
||||
pub fn publish(&self, epoch: u64, frame: OwnedRgba8888Frame) {
|
||||
self.shared.video.lock().unwrap().latest =
|
||||
Some(Publication { epoch, frame: Arc::new(frame) });
|
||||
self.shared.wake.notify_one();
|
||||
}
|
||||
}
|
||||
impl Drop for Transport {
|
||||
fn drop(&mut self) {
|
||||
self.shared.closed.store(true, Ordering::SeqCst);
|
||||
self.shared.wake.notify_all();
|
||||
let _ = self.control.shutdown(Shutdown::Both);
|
||||
let _ = self.video.shutdown(Shutdown::Both);
|
||||
for worker in self.workers.drain(..) {
|
||||
let _ = worker.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Bounded, explicitly little-endian Studio Play messages.
|
||||
use std::io::{self, Read, Write};
|
||||
pub const HEADER_BYTES: usize = 32;
|
||||
pub const CONTROL_LIMIT: usize = 64 * 1024;
|
||||
pub const FRAME_LIMIT: usize = 16 * 1024 * 1024;
|
||||
pub const FRAME_METADATA_BYTES: usize = 48;
|
||||
pub const HELLO: u16 = 1;
|
||||
pub const READY: u16 = 2;
|
||||
pub const START: u16 = 3;
|
||||
pub const PAUSE: u16 = 4;
|
||||
pub const RESUME: u16 = 5;
|
||||
pub const STOP: u16 = 6;
|
||||
pub const RESULT: u16 = 7;
|
||||
pub const INPUT: u16 = 8;
|
||||
pub const FRAME: u16 = 9;
|
||||
pub const FRAME_RECEIVED: u16 = 10;
|
||||
pub const PING: u16 = 11;
|
||||
pub const PONG: u16 = 12;
|
||||
pub const ERROR: u16 = 13;
|
||||
pub const STOPPED: u16 = 14;
|
||||
pub const BOOTSTRAP: u16 = 15;
|
||||
pub const RGBA8: u32 = 1;
|
||||
pub fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
pub kind: u16,
|
||||
pub length: usize,
|
||||
pub sequence: u64,
|
||||
pub request: u64,
|
||||
}
|
||||
impl Header {
|
||||
fn validate(self) -> io::Result<()> {
|
||||
if !(HELLO..=BOOTSTRAP).contains(&self.kind) || self.sequence == 0 {
|
||||
return Err(invalid("invalid Studio message type/sequence"));
|
||||
}
|
||||
if self.length > if self.kind == FRAME { FRAME_LIMIT } else { CONTROL_LIMIT } {
|
||||
return Err(invalid("Studio payload exceeds limit"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn encode(self) -> io::Result<[u8; HEADER_BYTES]> {
|
||||
self.validate()?;
|
||||
let mut b = [0; HEADER_BYTES];
|
||||
b[..4].copy_from_slice(b"PST1");
|
||||
b[4..6].copy_from_slice(&1u16.to_le_bytes());
|
||||
b[8..10].copy_from_slice(&self.kind.to_le_bytes());
|
||||
b[12..16].copy_from_slice(&(self.length as u32).to_le_bytes());
|
||||
b[16..24].copy_from_slice(&self.sequence.to_le_bytes());
|
||||
b[24..32].copy_from_slice(&self.request.to_le_bytes());
|
||||
Ok(b)
|
||||
}
|
||||
pub fn decode(b: &[u8; HEADER_BYTES]) -> io::Result<Self> {
|
||||
if &b[..4] != b"PST1" || b[4..8] != [1, 0, 0, 0] || b[10..12] != [0, 0] {
|
||||
return Err(invalid("invalid Studio magic/version/flags"));
|
||||
}
|
||||
let h = Self {
|
||||
kind: u16::from_le_bytes(b[8..10].try_into().unwrap()),
|
||||
length: u32::from_le_bytes(b[12..16].try_into().unwrap()) as usize,
|
||||
sequence: u64::from_le_bytes(b[16..24].try_into().unwrap()),
|
||||
request: u64::from_le_bytes(b[24..32].try_into().unwrap()),
|
||||
};
|
||||
h.validate()?;
|
||||
Ok(h)
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct Message {
|
||||
pub header: Header,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
pub struct Reader<R> {
|
||||
input: R,
|
||||
sequence: u64,
|
||||
}
|
||||
impl<R: Read> Reader<R> {
|
||||
pub fn new(input: R) -> Self {
|
||||
Self { input, sequence: 0 }
|
||||
}
|
||||
pub fn receive(&mut self) -> io::Result<Message> {
|
||||
self.receive_bounded(FRAME_LIMIT)
|
||||
}
|
||||
pub fn receive_control(&mut self) -> io::Result<Message> {
|
||||
self.receive_bounded(CONTROL_LIMIT)
|
||||
}
|
||||
fn receive_bounded(&mut self, limit: usize) -> io::Result<Message> {
|
||||
let mut bytes = [0; HEADER_BYTES];
|
||||
self.input.read_exact(&mut bytes)?;
|
||||
let header = Header::decode(&bytes)?;
|
||||
if header.length > limit {
|
||||
return Err(invalid("payload exceeds channel limit"));
|
||||
}
|
||||
if header.sequence <= self.sequence {
|
||||
return Err(invalid("non-monotonic Studio sequence"));
|
||||
}
|
||||
self.sequence = header.sequence;
|
||||
let mut payload = vec![0; header.length];
|
||||
self.input.read_exact(&mut payload)?;
|
||||
Ok(Message { header, payload })
|
||||
}
|
||||
}
|
||||
pub struct Writer<W> {
|
||||
output: W,
|
||||
sequence: u64,
|
||||
}
|
||||
impl<W: Write> Writer<W> {
|
||||
pub fn new(output: W) -> Self {
|
||||
Self { output, sequence: 0 }
|
||||
}
|
||||
pub fn send(&mut self, kind: u16, request: u64, payload: &[u8]) -> io::Result<()> {
|
||||
self.sequence =
|
||||
self.sequence.checked_add(1).ok_or_else(|| invalid("sequence exhausted"))?;
|
||||
self.output.write_all(
|
||||
&Header { kind, request, sequence: self.sequence, length: payload.len() }.encode()?,
|
||||
)?;
|
||||
self.output.write_all(payload)?;
|
||||
self.output.flush()
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct Bootstrap {
|
||||
pub session: [u8; 16],
|
||||
pub token: [u8; 32],
|
||||
pub control_port: u16,
|
||||
pub video_port: u16,
|
||||
pub disposable: bool,
|
||||
}
|
||||
impl Bootstrap {
|
||||
pub fn read(input: impl Read) -> io::Result<Self> {
|
||||
let m = Reader::new(input).receive()?;
|
||||
let p = &m.payload;
|
||||
if m.header.kind != BOOTSTRAP || m.header.request != 0 || p.len() != 53 || p[52] > 1 {
|
||||
return Err(invalid("invalid Studio bootstrap"));
|
||||
}
|
||||
let b = Self {
|
||||
session: p[..16].try_into().unwrap(),
|
||||
token: p[16..48].try_into().unwrap(),
|
||||
control_port: u16::from_le_bytes(p[48..50].try_into().unwrap()),
|
||||
video_port: u16::from_le_bytes(p[50..52].try_into().unwrap()),
|
||||
disposable: p[52] != 0,
|
||||
};
|
||||
if b.control_port == 0 || b.video_port == 0 || b.control_port == b.video_port {
|
||||
return Err(invalid("invalid Studio ports"));
|
||||
}
|
||||
Ok(b)
|
||||
}
|
||||
pub fn hello(&self, role: u8) -> Vec<u8> {
|
||||
let mut p = Vec::with_capacity(49);
|
||||
p.extend_from_slice(&self.session);
|
||||
p.extend_from_slice(&self.token);
|
||||
p.push(role);
|
||||
p
|
||||
}
|
||||
}
|
||||
pub fn frame_bytes(width: u32, height: u32, stride: u32) -> io::Result<usize> {
|
||||
if width == 0 || height == 0 || stride != width {
|
||||
return Err(invalid("invalid frame dimensions/stride"));
|
||||
}
|
||||
(stride as usize)
|
||||
.checked_mul(height as usize)
|
||||
.and_then(|n| n.checked_mul(4))
|
||||
.filter(|n| *n <= FRAME_LIMIT - FRAME_METADATA_BYTES)
|
||||
.ok_or_else(|| invalid("frame exceeds limit"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn fixture() -> Vec<u8> {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../../devtools/studio-protocol/fixtures/pause.hex");
|
||||
std::fs::read_to_string(root)
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.map(|s| u8::from_str_radix(s, 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
#[test]
|
||||
fn header_matches_shared_fixture() {
|
||||
let expected = fixture();
|
||||
let actual = Header { kind: PAUSE, length: 0, sequence: 1, request: 42 }.encode().unwrap();
|
||||
assert_eq!(actual.as_slice(), expected);
|
||||
assert_eq!(Header::decode(&actual).unwrap().request, 42);
|
||||
}
|
||||
#[test]
|
||||
fn truncation_replay_and_invalid_header_fail() {
|
||||
let bytes = fixture();
|
||||
assert!(Reader::new(&bytes[..31]).receive().is_err());
|
||||
let repeated = [bytes.as_slice(), bytes.as_slice()].concat();
|
||||
let mut r = Reader::new(repeated.as_slice());
|
||||
assert!(r.receive().is_ok());
|
||||
assert!(r.receive().is_err());
|
||||
for offset in [0, 4, 6, 8, 10] {
|
||||
let mut bad: [u8; 32] = bytes.clone().try_into().unwrap();
|
||||
bad[offset] = 255;
|
||||
assert!(Header::decode(&bad).is_err());
|
||||
}
|
||||
assert!(
|
||||
Header { kind: INPUT, length: CONTROL_LIMIT + 1, sequence: 1, request: 0 }
|
||||
.encode()
|
||||
.is_err()
|
||||
);
|
||||
assert!(frame_bytes(u32::MAX, u32::MAX, u32::MAX).is_err());
|
||||
assert!(frame_bytes(640, 360, 641).is_err());
|
||||
assert_eq!(frame_bytes(640, 360, 640).unwrap(), 921600);
|
||||
}
|
||||
#[test]
|
||||
fn fragmented_reads_and_writes_preserve_messages() {
|
||||
struct Short<'a>(&'a [u8]);
|
||||
impl Read for Short<'_> {
|
||||
fn read(&mut self, b: &mut [u8]) -> io::Result<usize> {
|
||||
let n = b.len().min(3).min(self.0.len());
|
||||
b[..n].copy_from_slice(&self.0[..n]);
|
||||
self.0 = &self.0[n..];
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
Writer::new(&mut bytes).send(INPUT, 9, &[1, 2, 3]).unwrap();
|
||||
let m = Reader::new(Short(&bytes)).receive().unwrap();
|
||||
assert_eq!(m.payload, [1, 2, 3]);
|
||||
assert_eq!(m.header.request, 9);
|
||||
assert!(Reader::new(&bytes[..bytes.len() - 1]).receive().is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Physical surface geometry shared by the nearest blit and pointer normalization.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Viewport {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub scale: f32,
|
||||
native: (usize, usize),
|
||||
}
|
||||
impl Viewport {
|
||||
pub fn new(surface: (u32, u32), native: (usize, usize)) -> Option<Self> {
|
||||
if surface.0 == 0 || surface.1 == 0 || native.0 == 0 || native.1 == 0 {
|
||||
return None;
|
||||
}
|
||||
let fit = (surface.0 as f32 / native.0 as f32).min(surface.1 as f32 / native.1 as f32);
|
||||
let scale = if fit >= 1.0 { fit.floor() } else { fit };
|
||||
let width = native.0 as f32 * scale;
|
||||
let height = native.1 as f32 * scale;
|
||||
Some(Self {
|
||||
x: ((surface.0 as f32 - width) / 2.0).floor(),
|
||||
y: ((surface.1 as f32 - height) / 2.0).floor(),
|
||||
width,
|
||||
height,
|
||||
scale,
|
||||
native,
|
||||
})
|
||||
}
|
||||
pub fn inverse(self, x: f64, y: f64) -> Option<(i32, i32)> {
|
||||
let (x, y) = (x - self.x as f64, y - self.y as f64);
|
||||
if !x.is_finite()
|
||||
|| !y.is_finite()
|
||||
|| x < 0.0
|
||||
|| y < 0.0
|
||||
|| x >= self.width as f64
|
||||
|| y >= self.height as f64
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
((x / self.scale as f64).floor() as i32).min(self.native.0 as i32 - 1),
|
||||
((y / self.scale as f64).floor() as i32).min(self.native.1 as i32 - 1),
|
||||
))
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn physical_scaling_and_inverse_share_bounds() {
|
||||
for (surface, scale, offset) in [
|
||||
((1280, 720), 2.0, (0.0, 0.0)),
|
||||
((1920, 1080), 3.0, (0.0, 0.0)),
|
||||
((1000, 700), 1.0, (180.0, 170.0)),
|
||||
((320, 240), 0.5, (0.0, 30.0)),
|
||||
((2560, 1440), 4.0, (0.0, 0.0)),
|
||||
] {
|
||||
let v = Viewport::new(surface, (640, 360)).unwrap();
|
||||
assert_eq!((v.scale, v.x, v.y), (scale, offset.0, offset.1));
|
||||
assert_eq!(v.inverse(v.x as f64, v.y as f64), Some((0, 0)));
|
||||
assert_eq!(
|
||||
v.inverse((v.x + v.width - 0.01) as f64, (v.y + v.height - 0.01) as f64),
|
||||
Some((639, 359))
|
||||
);
|
||||
assert_eq!(v.inverse((v.x + v.width) as f64, v.y as f64), None);
|
||||
assert_eq!(v.inverse(v.x as f64, (v.y + v.height) as f64), None);
|
||||
assert_eq!(v.inverse(v.x as f64 - 0.01, v.y as f64), None);
|
||||
}
|
||||
assert!(Viewport::new((0, 0), (640, 360)).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Real process qualification: no window, slow consumer, pause and broken IPC.
|
||||
use prometeu_host_desktop_winit::studio::wire::*;
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct Session {
|
||||
child: Child,
|
||||
control: Reader<TcpStream>,
|
||||
writer: Writer<TcpStream>,
|
||||
video: Reader<TcpStream>,
|
||||
control_socket: TcpStream,
|
||||
video_socket: TcpStream,
|
||||
logs: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
impl Session {
|
||||
fn start() -> Self {
|
||||
let control = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let video = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let cart = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../../test-cartridges/dummy-boy");
|
||||
let child = Command::new(env!("CARGO_BIN_EXE_prometeu-host-desktop-winit"))
|
||||
.args(["--studio", "--run"])
|
||||
.arg(cart)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let logs = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut session_child = child;
|
||||
for stream in [
|
||||
Box::new(session_child.stdout.take().unwrap()) as Box<dyn io::Read + Send>,
|
||||
Box::new(session_child.stderr.take().unwrap()) as Box<dyn io::Read + Send>,
|
||||
] {
|
||||
let log = logs.clone();
|
||||
std::thread::spawn(move || {
|
||||
for line in io::BufReader::new(stream).lines().map_while(Result::ok) {
|
||||
let mut lines = log.lock().unwrap();
|
||||
if lines.len() == 200 {
|
||||
lines.remove(0);
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut p = vec![3; 16];
|
||||
p.extend_from_slice(&[7; 32]);
|
||||
p.extend_from_slice(&control.local_addr().unwrap().port().to_le_bytes());
|
||||
p.extend_from_slice(&video.local_addr().unwrap().port().to_le_bytes());
|
||||
p.push(1);
|
||||
Writer::new(session_child.stdin.take().unwrap()).send(BOOTSTRAP, 0, &p).unwrap();
|
||||
fn accept(listener: TcpListener) -> TcpStream {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
match listener.accept() {
|
||||
Ok((s, _)) => {
|
||||
s.set_nonblocking(false).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
return s;
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
assert!(Instant::now() < deadline, "child did not connect");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(e) => panic!("accept: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
let control = accept(control);
|
||||
let video = accept(video);
|
||||
let mut c = Reader::new(control.try_clone().unwrap());
|
||||
let mut v = Reader::new(video.try_clone().unwrap());
|
||||
for (message, role) in [(c.receive().unwrap(), 1), (v.receive().unwrap(), 2)] {
|
||||
assert_eq!(message.header.kind, HELLO);
|
||||
assert_eq!(&message.payload[..16], &[3; 16]);
|
||||
assert_eq!(&message.payload[16..48], &[7; 32]);
|
||||
assert_eq!(message.payload[48], role);
|
||||
}
|
||||
let control_socket = control.try_clone().unwrap();
|
||||
let mut session = Self {
|
||||
child: session_child,
|
||||
control: c,
|
||||
writer: Writer::new(control),
|
||||
video: v,
|
||||
control_socket,
|
||||
video_socket: video,
|
||||
logs,
|
||||
};
|
||||
let ready = session.control.receive().unwrap();
|
||||
assert_eq!(ready.header.kind, READY, "{:?}", session.logs.lock().unwrap());
|
||||
assert_eq!(u32::from_le_bytes(ready.payload[..4].try_into().unwrap()), 640);
|
||||
session
|
||||
}
|
||||
fn command(&mut self, kind: u16, request: u64) -> Message {
|
||||
self.writer.send(kind, request, &[]).unwrap();
|
||||
let r = self.control.receive().unwrap();
|
||||
assert_eq!(r.header.kind, RESULT, "{:?}", self.logs.lock().unwrap());
|
||||
assert_eq!(r.header.request, request);
|
||||
assert_eq!(u16::from_le_bytes(r.payload[2..4].try_into().unwrap()), 0, "{:?}", r.payload);
|
||||
r
|
||||
}
|
||||
fn ping(&mut self) -> (u64, u64, u32) {
|
||||
self.writer.send(PING, 0, &[]).unwrap();
|
||||
let m = self.control.receive().unwrap();
|
||||
assert_eq!(m.header.kind, PONG);
|
||||
(
|
||||
u64::from_le_bytes(m.payload[..8].try_into().unwrap()),
|
||||
u64::from_le_bytes(m.payload[8..16].try_into().unwrap()),
|
||||
u32::from_le_bytes(m.payload[16..20].try_into().unwrap()),
|
||||
)
|
||||
}
|
||||
fn frame(&mut self) -> Message {
|
||||
let m = self
|
||||
.video
|
||||
.receive()
|
||||
.unwrap_or_else(|e| panic!("video: {e}; logs: {:?}", self.logs.lock().unwrap()));
|
||||
assert_eq!(m.header.kind, FRAME);
|
||||
assert_eq!(m.payload.len(), 48 + 640 * 360 * 4);
|
||||
m
|
||||
}
|
||||
fn ack(&mut self, frame: &Message) {
|
||||
self.writer.send(FRAME_RECEIVED, 0, &frame.payload[16..32]).unwrap();
|
||||
}
|
||||
fn exit(&mut self) -> ExitStatus {
|
||||
let deadline = Instant::now() + Duration::from_secs(4);
|
||||
loop {
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
return status;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"runtime did not exit: {:?}",
|
||||
self.logs.lock().unwrap()
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slow_video_does_not_stop_ticks_and_pause_resumes_same_process() {
|
||||
let mut s = Session::start();
|
||||
let pid = s.child.id();
|
||||
s.command(START, 1);
|
||||
let first = s.frame();
|
||||
let initial = s.ping();
|
||||
std::thread::sleep(Duration::from_millis(150));
|
||||
let later = s.ping();
|
||||
assert!(later.1 > initial.1);
|
||||
// No credit was returned while the runtime kept publishing. The next frame skips old presentations.
|
||||
s.ack(&first);
|
||||
let recent = s.frame();
|
||||
assert!(
|
||||
u64::from_le_bytes(recent.payload[24..32].try_into().unwrap())
|
||||
> u64::from_le_bytes(first.payload[24..32].try_into().unwrap()) + 1
|
||||
);
|
||||
s.command(PAUSE, 2);
|
||||
let paused = s.ping();
|
||||
assert_eq!(paused.2, 2);
|
||||
std::thread::sleep(Duration::from_millis(80));
|
||||
assert_eq!(s.ping().1, paused.1);
|
||||
s.command(RESUME, 3);
|
||||
std::thread::sleep(Duration::from_millis(60));
|
||||
assert!(s.ping().1 > paused.1);
|
||||
assert_eq!(s.child.id(), pid);
|
||||
s.command(STOP, 4);
|
||||
assert_eq!(s.control.receive().unwrap().header.kind, STOPPED);
|
||||
assert!(s.exit().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_video_ends_runtime_even_when_paused() {
|
||||
let mut s = Session::start();
|
||||
s.command(START, 1);
|
||||
s.command(PAUSE, 2);
|
||||
s.video_socket.shutdown(Shutdown::Both).unwrap();
|
||||
assert!(!s.exit().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_focus_loss_arms_game_without_advancing_until_manual_resume() {
|
||||
let mut s = Session::start();
|
||||
let initial = s.ping().1;
|
||||
s.command(PAUSE, 1);
|
||||
s.command(START, 2);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let paused = s.ping();
|
||||
assert_eq!(paused.1, initial);
|
||||
assert_eq!(paused.2, 2);
|
||||
s.command(RESUME, 3);
|
||||
let _ = s.frame();
|
||||
assert!(s.ping().1 > initial);
|
||||
s.command(STOP, 4);
|
||||
assert_eq!(s.control.receive().unwrap().header.kind, STOPPED);
|
||||
assert!(s.exit().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_control_ends_only_its_owned_runtime() {
|
||||
let mut s = Session::start();
|
||||
s.command(START, 1);
|
||||
s.control_socket.write_all(b"PST").unwrap();
|
||||
s.control_socket.shutdown(Shutdown::Write).unwrap();
|
||||
assert!(!s.exit().success());
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use prometeu_host_desktop_winit::studio::wire::*;
|
||||
|
||||
#[test]
|
||||
fn rgba_fixture_pins_channel_order_and_metadata() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../../devtools/studio-protocol/fixtures/rgba.hex");
|
||||
let bytes: Vec<u8> = std::fs::read_to_string(path)
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.map(|s| u8::from_str_radix(s, 16).unwrap())
|
||||
.collect();
|
||||
let m = Reader::new(bytes.as_slice()).receive().unwrap();
|
||||
assert_eq!(m.header.kind, FRAME);
|
||||
assert_eq!(m.header.length, 56);
|
||||
assert_eq!(&m.payload[..16], &(0u8..16).collect::<Vec<_>>());
|
||||
assert_eq!(
|
||||
&m.payload[48..],
|
||||
&[0xff0000ffu32.to_be_bytes(), 0x0000ff80u32.to_be_bytes()].concat()
|
||||
);
|
||||
assert_eq!(frame_bytes(2, 1, 2).unwrap() + FRAME_METADATA_BYTES, m.payload.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_rejects_wrong_roles_lengths_and_ports() {
|
||||
let mut p = vec![0; 53];
|
||||
p[48..50].copy_from_slice(&1234u16.to_le_bytes());
|
||||
p[50..52].copy_from_slice(&1235u16.to_le_bytes());
|
||||
p[52] = 1;
|
||||
let mut bytes = Vec::new();
|
||||
Writer::new(&mut bytes).send(BOOTSTRAP, 0, &p).unwrap();
|
||||
let boot = Bootstrap::read(bytes.as_slice()).unwrap();
|
||||
assert!(boot.disposable);
|
||||
assert_eq!(boot.hello(1).len(), 49);
|
||||
p[50..52].copy_from_slice(&1234u16.to_le_bytes());
|
||||
bytes.clear();
|
||||
Writer::new(&mut bytes).send(BOOTSTRAP, 0, &p).unwrap();
|
||||
assert!(Bootstrap::read(bytes.as_slice()).is_err());
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Unpaced logical-frame and capture timing through the real headless host.
|
||||
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
|
||||
use std::time::Instant;
|
||||
|
||||
fn stats(mut times: Vec<u64>) -> serde_json::Value {
|
||||
times.sort_unstable();
|
||||
let n = times.len();
|
||||
serde_json::json!({"mean_us":times.iter().sum::<u64>() as f64/n as f64/1000.0,
|
||||
"p95_us":times[(n*95).div_ceil(100)-1] as f64/1000.0,
|
||||
"p99_us":times[(n*99).div_ceil(100)-1] as f64/1000.0,
|
||||
"max_us":times[n-1] as f64/1000.0,
|
||||
"over_60hz_budget":times.iter().filter(|&&t|t>1_000_000_000/60).count()})
|
||||
}
|
||||
fn main() {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let cartridge = args.next().expect("cartridge directory");
|
||||
let count: usize = args.next().map(|s| s.parse().expect("frame count")).unwrap_or(600);
|
||||
assert!(count > 0);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(cartridge).expect("boot");
|
||||
let mut advance = Vec::with_capacity(count);
|
||||
let mut capture = Vec::with_capacity(count);
|
||||
let mut previous = None;
|
||||
let mut published = 0;
|
||||
let mut checksum = 0;
|
||||
for i in 0..count + 120 {
|
||||
let start = Instant::now();
|
||||
assert!(matches!(
|
||||
host.advance_frame().expect("advance"),
|
||||
AdvanceFrameOutcome::FrameCompleted { .. }
|
||||
));
|
||||
let elapsed = start.elapsed().as_nanos() as u64;
|
||||
let start = Instant::now();
|
||||
let frame = host.capture_frame().expect("published frame").frame;
|
||||
let capture_ns = start.elapsed().as_nanos() as u64;
|
||||
assert_eq!((frame.width, frame.height, frame.stride_pixels), (640, 360, 640));
|
||||
assert_ne!(previous, Some((frame.ownership, frame.frame_id)));
|
||||
previous = Some((frame.ownership, frame.frame_id));
|
||||
checksum ^= frame.pixels[(i * 173) % frame.pixels.len()];
|
||||
if i >= 120 {
|
||||
advance.push(elapsed);
|
||||
capture.push(capture_ns);
|
||||
published += 1;
|
||||
}
|
||||
}
|
||||
let state = host.get_state();
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"schema":1,"width":640,"height":360,"frames":count,"warmup_frames":120,
|
||||
"completed_logical_frames_total":state.frame_index,"host_ticks_total":state.tick_index,
|
||||
"published_frames_measured":published,"repeated_publications_measured":0,
|
||||
"advance_including_vm_render_publish":stats(advance),"owned_capture":stats(capture),"checksum":checksum,
|
||||
"vm_hz":null,"physical_display_hz":null,
|
||||
"limitations":"unpaced real VM/headless; capture copies owned pixels; no GPU, realtime cadence or physical display"})
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
mod wire;
|
||||
pub use wire::Limits;
|
||||
|
||||
use crate::{AdvanceFrameOutcome, HeadlessHost};
|
||||
use crate::{AdvanceFrameOutcome, HeadlessHost, PendingWrites, TeardownPolicy};
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
@@ -16,7 +16,8 @@ struct Control {
|
||||
}
|
||||
|
||||
enum Job {
|
||||
Work(String, Command),
|
||||
Work(String, Command, bool),
|
||||
Shutdown(String, TeardownPolicy, bool, mpsc::Sender<bool>),
|
||||
Stop(Option<String>),
|
||||
ReadError(io::Error),
|
||||
}
|
||||
@@ -104,6 +105,8 @@ fn read_commands<R: BufRead, W: Write>(
|
||||
limits: &Limits,
|
||||
) -> io::Result<()> {
|
||||
let mut initialized = false;
|
||||
let mut memcard = false;
|
||||
let mut log_read = false;
|
||||
loop {
|
||||
let bytes = match read_line(&mut input, limits.max_command_bytes)? {
|
||||
Line::Eof => break,
|
||||
@@ -142,11 +145,36 @@ fn read_commands<R: BufRead, W: Write>(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Command::Shutdown = command {
|
||||
let mut c = control.lock().unwrap();
|
||||
c.canceled = true;
|
||||
sender.send(Job::Stop(Some(id))).map_err(|_| io::Error::other("execution stopped"))?;
|
||||
return Ok(());
|
||||
if matches!(command, Command::GetLogs(_)) && !log_read {
|
||||
output.reply(
|
||||
Some(&id),
|
||||
Err(WireError::new(
|
||||
"unsupported_capability",
|
||||
"negotiate minor 1.2 and require log_read first",
|
||||
)),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if command.needs_memcard() && !memcard {
|
||||
output.reply(
|
||||
Some(&id),
|
||||
Err(WireError::new(
|
||||
"unsupported_capability",
|
||||
"negotiate minor 1.1 and require memcard first",
|
||||
)),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if let Command::Shutdown(params) = command {
|
||||
control.lock().unwrap().canceled = true;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
sender
|
||||
.send(Job::Shutdown(id, params.policy(), memcard, tx))
|
||||
.map_err(|_| io::Error::other("execution stopped"))?;
|
||||
if rx.recv().map_err(|_| io::Error::other("execution stopped"))? {
|
||||
return Ok(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Command::Initialize(params) = command {
|
||||
let result = if initialized {
|
||||
@@ -159,9 +187,23 @@ fn read_commands<R: BufRead, W: Write>(
|
||||
.any(|c| !CAPABILITIES.contains(&c.as_str()))
|
||||
{
|
||||
Err(WireError::new("unsupported_capability", "required capability unavailable"))
|
||||
} else if params.protocol_version.minor == 0
|
||||
&& params.required_capabilities.iter().any(|c| c == "memcard")
|
||||
{
|
||||
Err(WireError::new("incompatible_version", "memcard requires protocol minor >= 1"))
|
||||
} else if params.protocol_version.minor < 2
|
||||
&& params.required_capabilities.iter().any(|c| c == "log_read")
|
||||
{
|
||||
Err(WireError::new("incompatible_version", "log_read requires protocol minor >= 2"))
|
||||
} else {
|
||||
initialized = true;
|
||||
Ok(json!({"protocolVersion":{"major":1,"minor":0},"capabilities":CAPABILITIES}))
|
||||
memcard = params.protocol_version.minor >= 1
|
||||
&& params.required_capabilities.iter().any(|c| c == "memcard");
|
||||
log_read = params.protocol_version.minor >= 2
|
||||
&& params.required_capabilities.iter().any(|c| c == "log_read");
|
||||
Ok(
|
||||
json!({"protocolVersion":{"major":1,"minor":params.protocol_version.minor.min(2)},"capabilities":CAPABILITIES}),
|
||||
)
|
||||
};
|
||||
output.reply(Some(&id), result)?;
|
||||
continue;
|
||||
@@ -197,7 +239,9 @@ fn read_commands<R: BufRead, W: Write>(
|
||||
c.active = Some(id.clone());
|
||||
c.advancing = matches!(command, Command::Advance(_));
|
||||
c.canceled = false;
|
||||
sender.send(Job::Work(id, command)).map_err(|_| io::Error::other("execution stopped"))?;
|
||||
sender
|
||||
.send(Job::Work(id, command, memcard))
|
||||
.map_err(|_| io::Error::other("execution stopped"))?;
|
||||
}
|
||||
let mut c = control.lock().unwrap();
|
||||
c.canceled = true;
|
||||
@@ -210,14 +254,39 @@ fn execute<W: Write>(
|
||||
id: &str,
|
||||
output: &Output<W>,
|
||||
control: &Mutex<Control>,
|
||||
memcard: bool,
|
||||
) -> io::Result<Result<Value, WireError>> {
|
||||
Ok(match command {
|
||||
Command::Boot(p) => {
|
||||
host.boot(p.path).map(|()| wire::state(host.get_state())).map_err(wire::host_error)
|
||||
let result = if let Some(choice) = p.memcard_choice {
|
||||
host.boot_with_memcard_choice(p.path, choice.into())
|
||||
} else {
|
||||
host.boot(p.path)
|
||||
};
|
||||
result.map(|()| wire::state(host.get_state())).map_err(wire::host_error)
|
||||
}
|
||||
Command::Reset => {
|
||||
host.reset();
|
||||
Ok(wire::state(host.get_state()))
|
||||
Command::Reset(params) => host
|
||||
.reset_with_policy(params.policy())
|
||||
.map(|snapshot| {
|
||||
let mut state = wire::state(host.get_state());
|
||||
if memcard {
|
||||
state["memcard"] = json!(snapshot);
|
||||
}
|
||||
state
|
||||
})
|
||||
.map_err(wire::host_error),
|
||||
Command::MemcardMount(p) => {
|
||||
host.mount_memcard(p).map(|s| json!(s)).map_err(wire::host_error)
|
||||
}
|
||||
Command::MemcardUnmount => {
|
||||
host.unmount_memcard().map(|s| json!(s)).map_err(wire::host_error)
|
||||
}
|
||||
Command::GetMemcardState => Ok(json!(host.get_memcard_state())),
|
||||
Command::MemcardReconcile => {
|
||||
host.reconcile_memcard().map(|s| json!(s)).map_err(wire::host_error)
|
||||
}
|
||||
Command::MemcardContinueInMemory => {
|
||||
host.continue_memcard_in_memory().map(|s| json!(s)).map_err(wire::host_error)
|
||||
}
|
||||
Command::SetInput(p) => {
|
||||
host.set_input(p.into());
|
||||
@@ -229,6 +298,7 @@ fn execute<W: Write>(
|
||||
}
|
||||
Command::GetState => Ok(wire::state(host.get_state())),
|
||||
Command::GetFault => Ok(host.get_fault().as_ref().map(wire::fault).unwrap_or(Value::Null)),
|
||||
Command::GetLogs(params) => wire::logs(host, params, &output.session),
|
||||
Command::Capture => host.capture_frame().map_err(wire::host_error).and_then(wire::capture),
|
||||
Command::Advance(p) => {
|
||||
let mut result = json!({"requested":p.frames,"completed":0,"stop":"completed"});
|
||||
@@ -254,6 +324,10 @@ fn execute<W: Write>(
|
||||
result["stop"] = json!("terminated");
|
||||
break;
|
||||
}
|
||||
Ok(AdvanceFrameOutcome::ActionRequired) => {
|
||||
result["stop"] = json!("action_required");
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
result["stop"] = json!("host_error");
|
||||
result["error"] = serde_json::to_value(wire::host_error(error))?;
|
||||
@@ -283,7 +357,7 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
|
||||
let output =
|
||||
Arc::new(Output { writer: Mutex::new(writer), session, limit: limits.max_response_bytes });
|
||||
output.send(
|
||||
json!({"type":"hello","sessionId":output.session,"protocolVersion":{"major":1,"minor":0},
|
||||
json!({"type":"hello","sessionId":output.session,"protocolVersion":{"major":1,"minor":2},
|
||||
"runtimeVersion":runtime_version,"capabilities":CAPABILITIES,"limits":limits}),
|
||||
)?;
|
||||
let control = Arc::new(Mutex::new(Control::default()));
|
||||
@@ -298,18 +372,58 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
|
||||
}
|
||||
});
|
||||
let mut host = HeadlessHost::new();
|
||||
while let Ok(job) = receiver.recv() {
|
||||
loop {
|
||||
host.poll_memcard();
|
||||
let job = match receiver.recv_timeout(std::time::Duration::from_millis(5)) {
|
||||
Ok(job) => job,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
};
|
||||
match job {
|
||||
Job::Work(id, command) => {
|
||||
let result = execute(&mut host, command, &id, &output, &control)?;
|
||||
Job::Work(id, command, memcard) => {
|
||||
let result = match execute(&mut host, command, &id, &output, &control, memcard) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
cleanup_after_loss(&mut host);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
// Release authority under the same lock as response publication:
|
||||
// a client reacting to this reply cannot race a stale busy flag.
|
||||
let mut c = control.lock().unwrap();
|
||||
output.reply(Some(&id), result)?;
|
||||
if let Err(error) = output.reply(Some(&id), result) {
|
||||
drop(c);
|
||||
cleanup_after_loss(&mut host);
|
||||
return Err(error);
|
||||
}
|
||||
c.active = None;
|
||||
c.advancing = false;
|
||||
}
|
||||
Job::Shutdown(id, policy, memcard, ack) => match host.shutdown(policy) {
|
||||
Ok(snapshot) => {
|
||||
drop(host);
|
||||
let mut value = json!({"closed":true});
|
||||
if memcard {
|
||||
value["memcard"] = json!(snapshot);
|
||||
}
|
||||
output.reply(Some(&id), Ok(value))?;
|
||||
let _ = ack.send(true);
|
||||
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => {
|
||||
if let Err(error) = output.reply(Some(&id), Err(wire::host_error(error))) {
|
||||
cleanup_after_loss(&mut host);
|
||||
return Err(error);
|
||||
}
|
||||
let _ = ack.send(false);
|
||||
}
|
||||
},
|
||||
Job::Stop(id) => {
|
||||
let _ = host.shutdown(TeardownPolicy {
|
||||
discard_unsaved: true,
|
||||
pending_writes: PendingWrites::Cancel,
|
||||
});
|
||||
drop(host);
|
||||
if let Some(id) = id {
|
||||
output.reply(Some(&id), Ok(json!({"closed":true})))?;
|
||||
@@ -317,13 +431,24 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
|
||||
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
|
||||
return Ok(());
|
||||
}
|
||||
Job::ReadError(error) => return Err(error),
|
||||
Job::ReadError(error) => {
|
||||
let _ = host.shutdown(TeardownPolicy {
|
||||
discard_unsaved: true,
|
||||
pending_writes: PendingWrites::Cancel,
|
||||
});
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_after_loss(host: &mut HeadlessHost) {
|
||||
let _ = host
|
||||
.shutdown(TeardownPolicy { discard_unsaved: true, pending_writes: PendingWrites::Cancel });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -369,7 +494,7 @@ mod tests {
|
||||
"../../../../../devtools/headless-protocol/requests.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(requests.len(), 11);
|
||||
assert!(!requests.is_empty());
|
||||
for request in requests {
|
||||
wire::parse(serde_json::from_value(request).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ use std::io;
|
||||
#[cfg(test)]
|
||||
mod fault_tests;
|
||||
|
||||
use crate::{CapturedFrame, HostError, HostExecutionStatus, HostState};
|
||||
use crate::{
|
||||
CapturedFrame, HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction,
|
||||
MemcardChoice, MemcardMount, PendingWrites, TeardownPolicy,
|
||||
};
|
||||
|
||||
pub const CAPABILITIES: &[&str] = &[
|
||||
"boot",
|
||||
@@ -19,8 +22,15 @@ pub const CAPABILITIES: &[&str] = &[
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -95,6 +105,33 @@ pub(super) struct Initialize {
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Boot {
|
||||
pub path: String,
|
||||
#[serde(default, rename = "memcardChoice", deserialize_with = "present")]
|
||||
pub memcard_choice: Option<MemcardChoice>,
|
||||
}
|
||||
|
||||
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
|
||||
d: D,
|
||||
) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(d).map(Some)
|
||||
}
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct Teardown {
|
||||
#[serde(deserialize_with = "present")]
|
||||
pub discard_unsaved: Option<bool>,
|
||||
#[serde(deserialize_with = "present")]
|
||||
pub pending_writes: Option<PendingWrites>,
|
||||
}
|
||||
impl Teardown {
|
||||
pub fn explicit(&self) -> bool {
|
||||
self.discard_unsaved.is_some() || self.pending_writes.is_some()
|
||||
}
|
||||
pub fn policy(&self) -> TeardownPolicy {
|
||||
TeardownPolicy {
|
||||
discard_unsaved: self.discard_unsaved.unwrap_or(false),
|
||||
pending_writes: self.pending_writes.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -103,6 +140,19 @@ pub(super) struct Advance {
|
||||
pub frames: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct GetLogs {
|
||||
// Explicit deserializer makes the nullable field required, including on first read.
|
||||
#[serde(deserialize_with = "nullable_cursor")]
|
||||
pub after_sequence: Option<u64>,
|
||||
pub limit: u16,
|
||||
}
|
||||
|
||||
fn nullable_cursor<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
|
||||
Option::<u64>::deserialize(d)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct Cancel {
|
||||
@@ -155,15 +205,35 @@ impl From<Input> for InputSignals {
|
||||
pub(super) enum Command {
|
||||
Initialize(Initialize),
|
||||
Boot(Boot),
|
||||
Reset,
|
||||
Reset(Teardown),
|
||||
MemcardMount(MemcardMount),
|
||||
MemcardUnmount,
|
||||
GetMemcardState,
|
||||
MemcardReconcile,
|
||||
MemcardContinueInMemory,
|
||||
SetInput(Input),
|
||||
ClearInput,
|
||||
Advance(Advance),
|
||||
Capture,
|
||||
GetState,
|
||||
GetFault,
|
||||
GetLogs(GetLogs),
|
||||
Cancel(Cancel),
|
||||
Shutdown,
|
||||
Shutdown(Teardown),
|
||||
}
|
||||
impl Command {
|
||||
pub fn needs_memcard(&self) -> bool {
|
||||
match self {
|
||||
Self::MemcardMount(_)
|
||||
| Self::MemcardUnmount
|
||||
| Self::GetMemcardState
|
||||
| Self::MemcardReconcile
|
||||
| Self::MemcardContinueInMemory => true,
|
||||
Self::Boot(p) => p.memcard_choice.is_some(),
|
||||
Self::Reset(p) | Self::Shutdown(p) => p.explicit(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn params<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, WireError> {
|
||||
@@ -192,6 +262,24 @@ pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
|
||||
Command::Boot(p)
|
||||
}
|
||||
"advance" => Command::Advance(params(req.params)?),
|
||||
"get_logs" => {
|
||||
let p: GetLogs = params(req.params)?;
|
||||
if !(1..=1024).contains(&p.limit) {
|
||||
return Err(WireError::new("invalid_params", "limit must be 1..1024"));
|
||||
}
|
||||
Command::GetLogs(p)
|
||||
}
|
||||
"reset" => Command::Reset(params(req.params)?),
|
||||
"shutdown" => Command::Shutdown(params(req.params)?),
|
||||
"memcard_mount" => {
|
||||
let p: MemcardMount = params(req.params)?;
|
||||
if p.path.trim().is_empty()
|
||||
|| matches!((p.action, p.access), (MediaAction::Create, MediaAccess::ReadOnly))
|
||||
{
|
||||
return Err(WireError::new("invalid_params", "invalid media path/action/access"));
|
||||
}
|
||||
Command::MemcardMount(p)
|
||||
}
|
||||
"set_input" => Command::SetInput(params(req.params)?),
|
||||
"cancel" => {
|
||||
let p: Cancel = params(req.params)?;
|
||||
@@ -200,15 +288,25 @@ pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
|
||||
}
|
||||
Command::Cancel(p)
|
||||
}
|
||||
"reset" | "clear_input" | "capture" | "get_state" | "get_fault" | "shutdown" => {
|
||||
"clear_input"
|
||||
| "capture"
|
||||
| "get_state"
|
||||
| "get_fault"
|
||||
| "memcard_unmount"
|
||||
| "get_memcard_state"
|
||||
| "memcard_reconcile"
|
||||
| "memcard_continue_in_memory" => {
|
||||
empty(&req.params)?;
|
||||
match req.command.as_str() {
|
||||
"reset" => Command::Reset,
|
||||
"memcard_unmount" => Command::MemcardUnmount,
|
||||
"get_memcard_state" => Command::GetMemcardState,
|
||||
"memcard_reconcile" => Command::MemcardReconcile,
|
||||
"memcard_continue_in_memory" => Command::MemcardContinueInMemory,
|
||||
"clear_input" => Command::ClearInput,
|
||||
"capture" => Command::Capture,
|
||||
"get_state" => Command::GetState,
|
||||
"get_fault" => Command::GetFault,
|
||||
_ => Command::Shutdown,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
_ => return Err(WireError::new("unknown_command", "unknown command")),
|
||||
@@ -231,6 +329,9 @@ impl WireError {
|
||||
|
||||
pub(super) fn host_error(error: HostError) -> WireError {
|
||||
let (code, details) = match &error {
|
||||
HostError::Memcard(e) => {
|
||||
("memcard_error", json!({"operation":e.operation,"reason":e.reason,"state":e.state}))
|
||||
}
|
||||
HostError::AlreadyBooted => ("already_booted", json!({})),
|
||||
HostError::BootFailed { reason, report } => {
|
||||
("boot_failed", json!({"reason":reason,"fault":report.as_deref().map(fault)}))
|
||||
@@ -278,6 +379,48 @@ pub(super) fn state(s: HostState) -> Value {
|
||||
"status":status_name(s.status)})
|
||||
}
|
||||
|
||||
pub(super) fn logs(
|
||||
host: &crate::HeadlessHost,
|
||||
params: GetLogs,
|
||||
session: &str,
|
||||
) -> Result<Value, WireError> {
|
||||
let (events, oldest, newest) =
|
||||
host.log_snapshot(params.after_sequence, usize::from(params.limit));
|
||||
if params.after_sequence.is_some_and(|after| newest.is_none_or(|newest| after > newest)) {
|
||||
return Err(WireError::new("invalid_cursor", "afterSequence exceeds the log stream"));
|
||||
}
|
||||
let gap = oldest.is_some_and(|oldest| match params.after_sequence {
|
||||
None => oldest > 0,
|
||||
Some(after) => after.checked_add(1).is_some_and(|next| next < oldest),
|
||||
});
|
||||
let next = events.last().map(|event| event.seq).or(params.after_sequence);
|
||||
Ok(
|
||||
json!({"sessionId":session,"logEpoch":0,"events":events.iter().map(log_event).collect::<Vec<_>>(),
|
||||
"oldestSequence":oldest,"newestSequence":newest,"nextAfterSequence":next,
|
||||
"gap":gap,"overflow":oldest.is_some_and(|oldest| oldest > 0)}),
|
||||
)
|
||||
}
|
||||
|
||||
fn log_event(event: &prometeu_hal::log::LogEvent) -> Value {
|
||||
use prometeu_hal::log::{LogLevel, LogSource};
|
||||
let level = match event.level {
|
||||
LogLevel::Trace => "trace",
|
||||
LogLevel::Debug => "debug",
|
||||
LogLevel::Info => "info",
|
||||
LogLevel::Warn => "warn",
|
||||
LogLevel::Error => "error",
|
||||
};
|
||||
let (source, app_id) = match event.source {
|
||||
LogSource::Pos => ("pos", None),
|
||||
LogSource::Hub => ("hub", None),
|
||||
LogSource::Vm => ("vm", None),
|
||||
LogSource::Fs => ("fs", None),
|
||||
LogSource::App { app_id } => ("app", Some(app_id)),
|
||||
};
|
||||
json!({"sequence":event.seq,"frame":event.frame,"timestampMs":event.ts_ms,
|
||||
"level":level,"source":source,"appId":app_id,"tag":event.tag,"message":event.msg})
|
||||
}
|
||||
|
||||
pub(super) fn fault(report: &CrashReport) -> Value {
|
||||
let mut result = json!({"kind":report.kind(),"pc":report.pc(),"summary":report.summary()});
|
||||
match report {
|
||||
@@ -323,3 +466,105 @@ pub(super) fn capture(c: CapturedFrame) -> Result<Value, WireError> {
|
||||
"width":width,"height":height,"stridePixels":frame.stride_pixels,"pixelFormat":"RGBA8888",
|
||||
"logicalFrameIndex":c.logical_frame_index,"frameId":frame.frame_id.get()}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod log_tests {
|
||||
use super::*;
|
||||
use prometeu_hal::log::{LogEvent, LogLevel, LogSource};
|
||||
|
||||
#[test]
|
||||
fn oversized_native_event_is_an_error_without_partial_result() {
|
||||
let event = LogEvent {
|
||||
seq: 0,
|
||||
frame: 0,
|
||||
ts_ms: 0,
|
||||
level: LogLevel::Error,
|
||||
source: LogSource::Vm,
|
||||
tag: 0,
|
||||
msg: "x".repeat(8192),
|
||||
};
|
||||
let output = super::super::Output {
|
||||
writer: std::sync::Mutex::new(Vec::new()),
|
||||
session: "session".into(),
|
||||
limit: 4096,
|
||||
};
|
||||
output.reply(Some("logs"), Ok(json!({"events":[log_event(&event)]}))).unwrap();
|
||||
let bytes = output.writer.into_inner().unwrap();
|
||||
assert!(bytes.len() <= 4097);
|
||||
let response: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(response["error"]["code"], "response_too_large");
|
||||
assert_eq!(response["requestId"], "logs");
|
||||
assert!(response.get("result").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_records_preserve_unsigned_maxima_and_typed_sources() {
|
||||
for (source, name, app_id) in [
|
||||
(LogSource::Pos, "pos", None),
|
||||
(LogSource::Hub, "hub", None),
|
||||
(LogSource::Vm, "vm", None),
|
||||
(LogSource::Fs, "fs", None),
|
||||
(LogSource::App { app_id: u32::MAX }, "app", Some(u32::MAX)),
|
||||
] {
|
||||
for (level, level_name) in [
|
||||
(LogLevel::Trace, "trace"),
|
||||
(LogLevel::Debug, "debug"),
|
||||
(LogLevel::Info, "info"),
|
||||
(LogLevel::Warn, "warn"),
|
||||
(LogLevel::Error, "error"),
|
||||
] {
|
||||
let event = LogEvent {
|
||||
seq: u64::MAX,
|
||||
frame: u64::MAX,
|
||||
ts_ms: u64::MAX,
|
||||
level,
|
||||
source,
|
||||
tag: u16::MAX,
|
||||
msg: "complete native message".into(),
|
||||
};
|
||||
let encoded = log_event(&event);
|
||||
let decoded: Value =
|
||||
serde_json::from_slice(&serde_json::to_vec(&encoded).unwrap()).unwrap();
|
||||
for key in ["sequence", "frame", "timestampMs"] {
|
||||
assert_eq!(decoded[key].as_u64(), Some(u64::MAX));
|
||||
}
|
||||
assert_eq!(decoded["level"], level_name);
|
||||
assert_eq!(decoded["source"], name);
|
||||
assert_eq!(decoded["appId"], json!(app_id));
|
||||
assert_eq!(decoded["tag"], u16::MAX);
|
||||
assert_eq!(decoded["message"], event.msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_nullable_cursor_and_limit_reject_malformed_values() {
|
||||
for value in [
|
||||
json!({"limit":1}),
|
||||
json!({"afterSequence":null}),
|
||||
json!({"afterSequence":-1,"limit":1}),
|
||||
json!({"afterSequence":1.5,"limit":1}),
|
||||
json!({"afterSequence":"0","limit":1}),
|
||||
json!({"afterSequence":null,"limit":0}),
|
||||
json!({"afterSequence":null,"limit":1025}),
|
||||
json!({"afterSequence":null,"limit":1,"filter":"app"}),
|
||||
] {
|
||||
assert!(
|
||||
parse(Request {
|
||||
request_id: "logs".into(),
|
||||
command: "get_logs".into(),
|
||||
params: value
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
parse(Request {
|
||||
request_id: "logs".into(),
|
||||
command: "get_logs".into(),
|
||||
params: json!({"afterSequence":u64::MAX,"limit":1024})
|
||||
})
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_drivers::{ControlledWallClock, MemoryBanks};
|
||||
@@ -11,9 +12,30 @@ use prometeu_hal::{
|
||||
RuntimePlatform, TelemetryPlatform, WallClock,
|
||||
};
|
||||
use prometeu_system::{CrashReport, LatestRenderFrameStore};
|
||||
#[path = "memcard.rs"]
|
||||
mod memcard;
|
||||
pub use memcard::{
|
||||
MediaAccess, MediaAction, MemcardChoice, MemcardFailure, MemcardMount, MemcardState,
|
||||
PendingWrites, TeardownPolicy,
|
||||
};
|
||||
|
||||
const BOOT_TICK_LIMIT: usize = 5000;
|
||||
const HOST_FRAME_ADVANCE_TICK_LIMIT: usize = 100_000;
|
||||
const BOOTSTRAP_IO_WAIT_QUANTUM: Duration = Duration::from_millis(5);
|
||||
const BOOTSTRAP_IO_WAIT_LIMIT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// One deadline for the entire advance, including repeated admission to the gate.
|
||||
#[derive(Default)]
|
||||
struct BootstrapIoWait {
|
||||
deadline: Option<Instant>,
|
||||
}
|
||||
impl BootstrapIoWait {
|
||||
fn next_wait(&mut self, now: Instant) -> Option<Duration> {
|
||||
let deadline = *self.deadline.get_or_insert(now + BOOTSTRAP_IO_WAIT_LIMIT);
|
||||
let remaining = deadline.saturating_duration_since(now);
|
||||
(!remaining.is_zero()).then_some(remaining.min(BOOTSTRAP_IO_WAIT_QUANTUM))
|
||||
}
|
||||
}
|
||||
|
||||
/// One published logical frame plus the automation counter.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -46,6 +68,7 @@ pub enum AdvanceFrameOutcome {
|
||||
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
ActionRequired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -53,6 +76,7 @@ pub enum AdvanceFramesStop {
|
||||
Completed,
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
ActionRequired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -64,6 +88,7 @@ pub struct AdvanceFramesOutcome {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HostError {
|
||||
Memcard(Box<MemcardFailure>),
|
||||
AlreadyBooted,
|
||||
BootFailed { reason: String, report: Option<Box<CrashReport>> },
|
||||
InvalidState { operation: &'static str, status: HostExecutionStatus },
|
||||
@@ -75,6 +100,7 @@ pub enum HostError {
|
||||
impl fmt::Display for HostError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Memcard(error) => write!(f, "{}: {}", error.operation, error.reason),
|
||||
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
|
||||
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
|
||||
Self::InvalidState { operation, status } => {
|
||||
@@ -104,6 +130,7 @@ pub struct HeadlessHost {
|
||||
boot_attempted: bool,
|
||||
last_completed_frame: Option<CompletedFrame>,
|
||||
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
|
||||
media: memcard::MediaSelection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -153,6 +180,7 @@ impl HeadlessHost {
|
||||
boot_attempted: false,
|
||||
last_completed_frame: None,
|
||||
controlled_wall_clock,
|
||||
media: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,6 +194,15 @@ impl HeadlessHost {
|
||||
self.controlled_wall_clock.as_deref()
|
||||
}
|
||||
|
||||
/// Observe native log history without advancing, draining or changing lifecycle.
|
||||
pub fn log_snapshot(
|
||||
&self,
|
||||
after: Option<u64>,
|
||||
limit: usize,
|
||||
) -> (Vec<prometeu_hal::log::LogEvent>, Option<u64>, Option<u64>) {
|
||||
self.firmware.os.log_snapshot(after, limit)
|
||||
}
|
||||
|
||||
/// Load `path` and tick until the firmware is in `GameRunning`.
|
||||
///
|
||||
/// The transition into `GameRunning` is the last tick. The first game
|
||||
@@ -189,15 +226,20 @@ impl HeadlessHost {
|
||||
return Err(HostError::AlreadyBooted);
|
||||
}
|
||||
self.boot_attempted = true;
|
||||
self.media.choice = choice;
|
||||
self.media.boot_phase = "loading";
|
||||
let path = path.into();
|
||||
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
||||
|
||||
let boot_deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
let mut choice_submitted = false;
|
||||
for _ in 0..BOOT_TICK_LIMIT {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
self.media.boot_phase = "running";
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
self.media.boot_phase = "failed";
|
||||
let report = self.get_fault();
|
||||
let reason = report
|
||||
.as_ref()
|
||||
@@ -206,33 +248,55 @@ impl HeadlessHost {
|
||||
return Err(HostError::BootFailed { reason, report: report.map(Box::new) });
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(HostError::BootFailed {
|
||||
reason: "cartridge did not load".to_string(),
|
||||
report: None,
|
||||
});
|
||||
}
|
||||
let progress = self.firmware.os.memcard().lane.progress_stamp();
|
||||
if let FirmwareState::LoadCartridge(step) = &self.firmware.state
|
||||
&& step.cartridge.memcard_slots.is_none()
|
||||
&& choice.is_some()
|
||||
{
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", "invalid_state"));
|
||||
}
|
||||
if choice_submitted
|
||||
&& let prometeu_system::memcard::admission::PreparationState::Failed(error) =
|
||||
self.firmware.os.memcard().admission.state
|
||||
{
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", memcard::error_name(error)));
|
||||
}
|
||||
let waiting = matches!(&self.firmware.state,FirmwareState::LoadCartridge(step) if step.needs_memcard_choice());
|
||||
if waiting {
|
||||
let Some(choice) = choice else {
|
||||
return Err(HostError::BootFailed {
|
||||
reason: "Memory-card choice required; use boot_with_memcard_choice".into(),
|
||||
report: None,
|
||||
});
|
||||
self.media.boot_phase = "choice_required";
|
||||
return Err(self.memcard_error("boot", "choice_required"));
|
||||
};
|
||||
self.signals = InputSignals::default();
|
||||
self.tick_once();
|
||||
self.signals = match choice {
|
||||
prometeu_system::memcard::admission::Choice::Persistent => {
|
||||
InputSignals { a_signal: true, ..Default::default() }
|
||||
}
|
||||
prometeu_system::memcard::admission::Choice::MemoryFresh => {
|
||||
InputSignals { x_signal: true, ..Default::default() }
|
||||
}
|
||||
prometeu_system::memcard::admission::Choice::MemoryExisting => {
|
||||
InputSignals { y_signal: true, ..Default::default() }
|
||||
if self.firmware.os.memcard().preparation_active() {
|
||||
self.poll_memcard();
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.lane
|
||||
.wait_for_progress(progress, std::time::Duration::from_millis(5));
|
||||
continue;
|
||||
}
|
||||
let created_at = self.platform.wall_clock().utc_unix_seconds();
|
||||
let result = match &mut self.firmware.state {
|
||||
FirmwareState::LoadCartridge(step) => {
|
||||
step.choose_memcard(&mut self.firmware.os, choice, created_at)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", memcard::error_name(error)));
|
||||
}
|
||||
choice_submitted = true;
|
||||
self.media.boot_phase = "preparing";
|
||||
}
|
||||
self.tick_once();
|
||||
self.signals = InputSignals::default();
|
||||
@@ -251,6 +315,7 @@ impl HeadlessHost {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
Ok(())
|
||||
} else {
|
||||
self.media.boot_phase = "failed";
|
||||
Err(HostError::BootFailed {
|
||||
reason: "boot did not reach the game".to_string(),
|
||||
report: self.get_fault().map(Box::new),
|
||||
@@ -258,7 +323,10 @@ impl HeadlessHost {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
pub fn reset(&mut self) -> Result<(), HostError> {
|
||||
self.reset_with_policy(TeardownPolicy::default()).map(|_| ())
|
||||
}
|
||||
fn reset_inner(&mut self) {
|
||||
self.signals = InputSignals::default();
|
||||
self.firmware.change_state(
|
||||
FirmwareState::Reset(ResetStep),
|
||||
@@ -296,7 +364,11 @@ impl HeadlessHost {
|
||||
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(AdvanceFrameOutcome::Terminated);
|
||||
return Ok(if self.host_action_required() {
|
||||
AdvanceFrameOutcome::ActionRequired
|
||||
} else {
|
||||
AdvanceFrameOutcome::Terminated
|
||||
});
|
||||
}
|
||||
|
||||
let start = self.firmware.os.vm().logical_frame_index();
|
||||
@@ -304,7 +376,13 @@ impl HeadlessHost {
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
|
||||
let mut io_wait = BootstrapIoWait::default();
|
||||
for _ in 0..HOST_FRAME_ADVANCE_TICK_LIMIT {
|
||||
// A controlled lifecycle slice can consume the runtime step marker
|
||||
// without closing a logical frame. This operation still owns the
|
||||
// request until its first frame or an explicit stop boundary.
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
self.tick_once();
|
||||
if let Some(report) = self.get_fault() {
|
||||
self.finish_frame_advance();
|
||||
@@ -312,7 +390,11 @@ impl HeadlessHost {
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
self.finish_frame_advance();
|
||||
return Ok(AdvanceFrameOutcome::Terminated);
|
||||
return Ok(if self.host_action_required() {
|
||||
AdvanceFrameOutcome::ActionRequired
|
||||
} else {
|
||||
AdvanceFrameOutcome::Terminated
|
||||
});
|
||||
}
|
||||
|
||||
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
|
||||
@@ -333,6 +415,24 @@ impl HeadlessHost {
|
||||
frame_id: frame.frame_id,
|
||||
});
|
||||
}
|
||||
|
||||
loop {
|
||||
// Refresh before every observation/poll: another lane job may
|
||||
// have progressed without completing this publication.
|
||||
let progress = self.firmware.os.memcard().lane.progress_stamp();
|
||||
if !self.bootstrap_io_pending() {
|
||||
break;
|
||||
}
|
||||
// Native polling and waiting do not execute machine ticks.
|
||||
self.poll_memcard();
|
||||
if self.host_action_required() {
|
||||
self.finish_frame_advance();
|
||||
return Ok(AdvanceFrameOutcome::ActionRequired);
|
||||
}
|
||||
if self.bootstrap_io_pending() {
|
||||
self.wait_for_bootstrap_io(&mut io_wait, progress)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.finish_frame_advance();
|
||||
@@ -341,6 +441,32 @@ impl HeadlessHost {
|
||||
})
|
||||
}
|
||||
|
||||
fn bootstrap_io_pending(&mut self) -> bool {
|
||||
let FirmwareState::GameRunning(step) = &self.firmware.state else { return false };
|
||||
let task = step.task_id;
|
||||
let hook_complete = self
|
||||
.firmware
|
||||
.os
|
||||
.sessions()
|
||||
.vm_session_for_task(task)
|
||||
.is_some_and(|session| session.vm.memcard_boot_result() == Some(0));
|
||||
let service = self.firmware.os.memcard();
|
||||
hook_complete && service.session.boot_pending() && service.session.io_active()
|
||||
}
|
||||
|
||||
fn wait_for_bootstrap_io(
|
||||
&mut self,
|
||||
wait: &mut BootstrapIoWait,
|
||||
progress: u64,
|
||||
) -> Result<(), HostError> {
|
||||
let Some(timeout) = wait.next_wait(Instant::now()) else {
|
||||
self.finish_frame_advance();
|
||||
return Err(self.memcard_error("advance", "restart_required"));
|
||||
};
|
||||
self.firmware.os.memcard().lane.wait_for_progress(progress, timeout);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn advance_frames(&mut self, count: u64) -> Result<AdvanceFramesOutcome, HostError> {
|
||||
let mut completed = 0;
|
||||
for _ in 0..count {
|
||||
@@ -360,6 +486,13 @@ impl HeadlessHost {
|
||||
stop: AdvanceFramesStop::Terminated,
|
||||
});
|
||||
}
|
||||
AdvanceFrameOutcome::ActionRequired => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::ActionRequired,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
|
||||
@@ -416,6 +549,8 @@ impl HeadlessHost {
|
||||
fn execution_status(&mut self) -> HostExecutionStatus {
|
||||
if self.fault_is_visible() {
|
||||
HostExecutionStatus::Faulted
|
||||
} else if self.host_action_required() {
|
||||
HostExecutionStatus::Paused
|
||||
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
HostExecutionStatus::Terminated
|
||||
} else if self.firmware.os.vm().paused() {
|
||||
@@ -432,7 +567,9 @@ impl HeadlessHost {
|
||||
|
||||
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||
let status = self.execution_status();
|
||||
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) {
|
||||
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused)
|
||||
&& !self.host_action_required()
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(HostError::InvalidState { operation, status })
|
||||
@@ -463,6 +600,11 @@ impl RenderSubmissionSink for HeadlessPlatform {
|
||||
let frame_id = submission.frame_id;
|
||||
let ownership = submission.ownership;
|
||||
self.hardware.submit_render_submission(submission)?;
|
||||
// Host dialogs use their own producer and may reuse FrameId::ZERO.
|
||||
// Capture/advance observe only canonical game publications.
|
||||
if ownership.app_mode != prometeu_hal::app_mode::AppMode::Game {
|
||||
return Ok(());
|
||||
}
|
||||
let (width, height) = self.hardware.gfx.size();
|
||||
let pixels = self.hardware.gfx.front_buffer().to_vec();
|
||||
let frame = OwnedRgba8888Frame::packed(frame_id, ownership, width, height, pixels)
|
||||
|
||||
@@ -11,5 +11,6 @@ mod host;
|
||||
|
||||
pub use host::{
|
||||
AdvanceFrameOutcome, AdvanceFramesOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost,
|
||||
HostError, HostExecutionStatus, HostState,
|
||||
HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction, MemcardChoice,
|
||||
MemcardFailure, MemcardMount, MemcardState, PendingWrites, TeardownPolicy,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Public native host controls; all image policy stays in the shared system service.
|
||||
use super::{HeadlessHost, HostError};
|
||||
use prometeu_drivers::memcard::FileMemcard;
|
||||
use prometeu_firmware::FirmwareState;
|
||||
use prometeu_hal::memcard::{MemcardIoError, MemcardStorage};
|
||||
use prometeu_system::memcard::{
|
||||
admission::{Choice, PreparationState},
|
||||
image::{Error, IMAGE_BYTES},
|
||||
session::{Mode, RequestReason, RequestState},
|
||||
transaction::Card,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MediaAction {
|
||||
Open,
|
||||
Create,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MediaAccess {
|
||||
ReadWrite,
|
||||
ReadOnly,
|
||||
}
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MemcardMount {
|
||||
pub path: String,
|
||||
pub action: MediaAction,
|
||||
pub access: MediaAccess,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PendingWrites {
|
||||
#[default]
|
||||
Wait,
|
||||
Cancel,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub struct TeardownPolicy {
|
||||
pub discard_unsaved: bool,
|
||||
pub pending_writes: PendingWrites,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MemcardChoice {
|
||||
Persistent,
|
||||
MemoryFresh,
|
||||
MemoryExisting,
|
||||
}
|
||||
impl From<MemcardChoice> for Choice {
|
||||
fn from(c: MemcardChoice) -> Self {
|
||||
match c {
|
||||
MemcardChoice::Persistent => Self::Persistent,
|
||||
MemcardChoice::MemoryFresh => Self::MemoryFresh,
|
||||
MemcardChoice::MemoryExisting => Self::MemoryExisting,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn choice_name(c: Choice) -> &'static str {
|
||||
match c {
|
||||
Choice::Persistent => "persistent",
|
||||
Choice::MemoryFresh => "memory_fresh",
|
||||
Choice::MemoryExisting => "memory_existing",
|
||||
}
|
||||
}
|
||||
pub(super) fn error_name(e: Error) -> &'static str {
|
||||
match e {
|
||||
Error::Io(e) => match e {
|
||||
MemcardIoError::Unavailable => "unavailable",
|
||||
MemcardIoError::ReadOnly => "read_only",
|
||||
MemcardIoError::InvalidRange => "invalid_range",
|
||||
MemcardIoError::NoSpace => "no_space",
|
||||
MemcardIoError::Unsupported => "unsupported",
|
||||
MemcardIoError::Busy => "busy",
|
||||
MemcardIoError::AccessDenied => "access_denied",
|
||||
MemcardIoError::AlreadyExists => "already_exists",
|
||||
MemcardIoError::Indeterminate => "indeterminate",
|
||||
MemcardIoError::IoError => "io_error",
|
||||
},
|
||||
Error::Corrupt => "corrupt",
|
||||
Error::Unsupported => "unsupported",
|
||||
Error::NoSpace => "no_space",
|
||||
Error::InvalidRange => "invalid_range",
|
||||
Error::CounterExhausted => "counter_exhausted",
|
||||
Error::ReadOnly => "read_only",
|
||||
Error::Indeterminate => "indeterminate",
|
||||
Error::Busy => "busy",
|
||||
Error::Canceled => "canceled",
|
||||
Error::OutOfMemory => "out_of_memory",
|
||||
Error::AccessDenied => "access_denied",
|
||||
Error::InvalidState => "invalid_state",
|
||||
Error::IdentityMismatch => "identity_mismatch",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MemcardState {
|
||||
pub media: MediaState,
|
||||
pub session: SessionState,
|
||||
pub dirty: bool,
|
||||
pub dirty_slots: Vec<usize>,
|
||||
pub request: Option<RequestObservation>,
|
||||
pub io: IoState,
|
||||
pub recovery: RecoveryState,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MediaState {
|
||||
pub path: Option<PathBuf>,
|
||||
pub card_id: Option<String>,
|
||||
pub access: Option<MediaAccess>,
|
||||
pub mount_epoch: String,
|
||||
pub preparation: &'static str,
|
||||
pub error: Option<&'static str>,
|
||||
pub recovered: bool,
|
||||
pub degraded: bool,
|
||||
pub write_blocked: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SessionState {
|
||||
pub app_id: Option<u32>,
|
||||
pub choice: Option<&'static str>,
|
||||
pub mode: Option<&'static str>,
|
||||
pub boot_attempted: bool,
|
||||
pub boot_phase: &'static str,
|
||||
pub resident: bool,
|
||||
pub action_required: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RequestObservation {
|
||||
pub id: String,
|
||||
pub state: &'static str,
|
||||
pub reason: &'static str,
|
||||
pub storage_error: Option<&'static str>,
|
||||
pub operation: &'static str,
|
||||
pub slot: Option<usize>,
|
||||
pub retained: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct IoState {
|
||||
pub active: bool,
|
||||
pub deferred: bool,
|
||||
pub phase: &'static str,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RecoveryState {
|
||||
pub removal_pending: bool,
|
||||
pub reconciliation_required: bool,
|
||||
pub restart_required: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MemcardFailure {
|
||||
pub operation: &'static str,
|
||||
pub reason: &'static str,
|
||||
pub state: MemcardState,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct MediaSelection {
|
||||
path: Option<PathBuf>,
|
||||
access: Option<MediaAccess>,
|
||||
card_id: Option<[u8; 16]>,
|
||||
error: Option<&'static str>,
|
||||
pub choice: Option<Choice>,
|
||||
pub boot_phase: &'static str,
|
||||
shutdown_failed: bool,
|
||||
}
|
||||
|
||||
impl HeadlessHost {
|
||||
/// Poll only native work. This does not tick firmware or execute guest code.
|
||||
pub fn poll_memcard(&mut self) {
|
||||
self.firmware.os.poll_background_io(&mut self.platform);
|
||||
}
|
||||
pub(super) fn memcard_error(
|
||||
&mut self,
|
||||
operation: &'static str,
|
||||
reason: &'static str,
|
||||
) -> HostError {
|
||||
HostError::Memcard(Box::new(MemcardFailure {
|
||||
operation,
|
||||
reason,
|
||||
state: self.get_memcard_state(),
|
||||
}))
|
||||
}
|
||||
pub fn get_memcard_state(&mut self) -> MemcardState {
|
||||
let resident = self.firmware.os.lifecycle().resident_game_task().is_some();
|
||||
let service = self.firmware.os.memcard();
|
||||
let d = service.session_diagnostics();
|
||||
let preparation = service.preparation_active();
|
||||
let host_faulted = service.host_faulted() || self.media.shutdown_failed;
|
||||
let (state, error) = match service.admission.state {
|
||||
PreparationState::Idle => ("idle", None),
|
||||
PreparationState::Pending => ("pending", None),
|
||||
PreparationState::Ready => ("ready", None),
|
||||
PreparationState::Failed(e) => ("failed", Some(error_name(e))),
|
||||
};
|
||||
let id = d.card_id.or(service.installed_card_id()).or(self.media.card_id);
|
||||
let health = if d.mode.is_some() {
|
||||
d.health
|
||||
} else {
|
||||
service.installed_health().unwrap_or((false, false, false))
|
||||
};
|
||||
let phase = if preparation {
|
||||
"preparing"
|
||||
} else if d.request.as_ref().is_some_and(|r| r.deferred) {
|
||||
"deferred"
|
||||
} else if d.io_active {
|
||||
if service.lane.telemetry().active_job_id == service.session.pending_job() {
|
||||
"running"
|
||||
} else {
|
||||
"queued"
|
||||
}
|
||||
} else if d.request.is_some() {
|
||||
"returned"
|
||||
} else {
|
||||
"idle"
|
||||
};
|
||||
MemcardState {
|
||||
media: MediaState {
|
||||
path: self.media.path.clone(),
|
||||
access: self.media.access,
|
||||
card_id: id.map(|id| id.iter().map(|v| format!("{v:02x}")).collect()),
|
||||
mount_epoch: d.epoch.to_string(),
|
||||
preparation: state,
|
||||
error: error.or(self.media.error),
|
||||
recovered: health.0,
|
||||
degraded: health.1,
|
||||
write_blocked: health.2,
|
||||
},
|
||||
session: SessionState {
|
||||
app_id: d.app_id,
|
||||
choice: self.media.choice.map(choice_name),
|
||||
mode: d.mode.map(|m| match m {
|
||||
Mode::Persistent => "persistent",
|
||||
Mode::MemoryOnly => "memory_only",
|
||||
}),
|
||||
boot_attempted: self.boot_attempted,
|
||||
boot_phase: if self.media.boot_phase.is_empty() {
|
||||
"idle"
|
||||
} else {
|
||||
self.media.boot_phase
|
||||
},
|
||||
resident,
|
||||
action_required: d.mode.is_some()
|
||||
&& resident
|
||||
&& (d.removal_pending
|
||||
|| host_faulted
|
||||
|| !matches!(self.firmware.state, FirmwareState::GameRunning(_))),
|
||||
},
|
||||
dirty: !d.dirty_slots.is_empty(),
|
||||
dirty_slots: d.dirty_slots,
|
||||
request: d.request.map(|r| RequestObservation {
|
||||
id: r.result.id.to_string(),
|
||||
state: match r.result.state {
|
||||
RequestState::Pending => "pending",
|
||||
RequestState::Success => "success",
|
||||
RequestState::Failure => "failure",
|
||||
RequestState::Indeterminate => "indeterminate",
|
||||
RequestState::MemoryOnly => "memory_only",
|
||||
},
|
||||
reason: match r.result.reason {
|
||||
RequestReason::None => "none",
|
||||
RequestReason::Timeout => "timeout",
|
||||
RequestReason::RestartRequired => "restart_required",
|
||||
RequestReason::Storage(e) => error_name(e),
|
||||
},
|
||||
storage_error: r.storage_error.map(error_name),
|
||||
operation: r.operation,
|
||||
slot: r.slot,
|
||||
retained: r.retained,
|
||||
}),
|
||||
io: IoState {
|
||||
active: preparation || d.io_active,
|
||||
deferred: phase == "deferred",
|
||||
phase,
|
||||
},
|
||||
recovery: RecoveryState {
|
||||
removal_pending: d.removal_pending,
|
||||
reconciliation_required: d.reconciliation_required,
|
||||
restart_required: host_faulted,
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn mount_memcard(&mut self, options: MemcardMount) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if self.firmware.os.lifecycle().resident_game_task().is_some() {
|
||||
return Err(self.memcard_error("memcard_mount", "invalid_state"));
|
||||
}
|
||||
if options.path.trim().is_empty()
|
||||
|| matches!(
|
||||
(options.action, options.access),
|
||||
(MediaAction::Create, MediaAccess::ReadOnly)
|
||||
)
|
||||
{
|
||||
return Err(self.memcard_error("memcard_mount", "invalid_state"));
|
||||
}
|
||||
let path = std::path::absolute(&options.path)
|
||||
.map_err(|_| self.memcard_error("memcard_mount", "unavailable"))?;
|
||||
// Do not change selection when admission is refused as busy.
|
||||
let open_path = path.clone();
|
||||
let result = self.firmware.os.memcard().mount_card_with(move || {
|
||||
let io = match options.action {
|
||||
MediaAction::Open => {
|
||||
FileMemcard::open(&open_path, options.access == MediaAccess::ReadOnly)?
|
||||
}
|
||||
MediaAction::Create => FileMemcard::create(&open_path, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
})?,
|
||||
};
|
||||
Ok(Box::new(io) as Box<dyn MemcardStorage>)
|
||||
});
|
||||
result.map_err(|e| self.memcard_error("memcard_mount", error_name(e)))?;
|
||||
self.media.path = Some(path);
|
||||
self.media.access = Some(options.access);
|
||||
self.media.error = None;
|
||||
self.media.card_id = None;
|
||||
if let Err(error) = self.wait_preparation("memcard_mount") {
|
||||
if let HostError::Memcard(e) = &error {
|
||||
self.media.error = Some(e.reason);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
self.media.card_id = self.firmware.os.memcard().installed_card_id();
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn unmount_memcard(&mut self) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if self.firmware.os.lifecycle().resident_game_task().is_some() {
|
||||
return Err(self.memcard_error("memcard_unmount", "invalid_state"));
|
||||
}
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.uninstall_card()
|
||||
.map_err(|e| self.memcard_error("memcard_unmount", error_name(e)))?;
|
||||
self.media = MediaSelection { boot_phase: self.media.boot_phase, ..Default::default() };
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
fn wait_preparation(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
self.poll_memcard();
|
||||
match self.firmware.os.memcard().admission.state {
|
||||
PreparationState::Ready => return Ok(()),
|
||||
PreparationState::Failed(e) => {
|
||||
let reason = if self.firmware.os.memcard().host_faulted() {
|
||||
"restart_required"
|
||||
} else {
|
||||
error_name(e)
|
||||
};
|
||||
return Err(self.memcard_error(operation, reason));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(self.memcard_error(operation, "restart_required"));
|
||||
}
|
||||
let lane = self.firmware.os.memcard().lane.clone();
|
||||
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
pub fn prepare_teardown(
|
||||
&mut self,
|
||||
policy: TeardownPolicy,
|
||||
operation: &'static str,
|
||||
) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if matches!(policy.pending_writes, PendingWrites::Cancel) {
|
||||
self.firmware.os.memcard().cancel_pending();
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
self.poll_memcard();
|
||||
let state = self.get_memcard_state();
|
||||
if !state.io.active && !state.io.deferred {
|
||||
break;
|
||||
}
|
||||
if state.recovery.restart_required || Instant::now() >= deadline {
|
||||
return Err(self.memcard_error(operation, "restart_required"));
|
||||
}
|
||||
let lane = self.firmware.os.memcard().lane.clone();
|
||||
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
|
||||
}
|
||||
if self.get_memcard_state().dirty && !policy.discard_unsaved {
|
||||
return Err(self.memcard_error(operation, "unsaved_changes"));
|
||||
}
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn reset_with_policy(&mut self, policy: TeardownPolicy) -> Result<MemcardState, HostError> {
|
||||
self.prepare_teardown(policy, "reset")?;
|
||||
self.reset_inner();
|
||||
self.media.choice = None;
|
||||
self.media.boot_phase = "idle";
|
||||
self.poll_memcard();
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn shutdown(&mut self, policy: TeardownPolicy) -> Result<MemcardState, HostError> {
|
||||
let state = self.prepare_teardown(policy, "shutdown")?;
|
||||
if self.firmware.os.stop_background_io().is_err() {
|
||||
self.media.shutdown_failed = true;
|
||||
return Err(self.memcard_error("shutdown", "restart_required"));
|
||||
}
|
||||
self.firmware.os.memcard().session.end_session();
|
||||
self.firmware.os.memcard().poll(Instant::now());
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.uninstall_card()
|
||||
.map_err(|e| self.memcard_error("shutdown", error_name(e)))?;
|
||||
Ok(state)
|
||||
}
|
||||
pub fn reconcile_memcard(&mut self) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if !self.suspended_for_memcard() {
|
||||
return Err(self.memcard_error("memcard_reconcile", "invalid_state"));
|
||||
}
|
||||
let path = self
|
||||
.media
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| self.memcard_error("memcard_reconcile", "invalid_state"))?;
|
||||
let read_only = self.media.access == Some(MediaAccess::ReadOnly);
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.reconcile_card_with(move || {
|
||||
Ok(Box::new(FileMemcard::open(&path, read_only)?) as Box<dyn MemcardStorage>)
|
||||
})
|
||||
.map_err(|e| self.memcard_error("memcard_reconcile", error_name(e)))?;
|
||||
self.wait_preparation("memcard_reconcile")?;
|
||||
self.media.error = None;
|
||||
if !self.firmware.resume_resident_game_from_home() {
|
||||
return Err(self.memcard_error("memcard_reconcile", "invalid_state"));
|
||||
}
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn continue_memcard_in_memory(&mut self) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if !self.suspended_for_memcard() {
|
||||
return Err(self.memcard_error("memcard_continue_in_memory", "invalid_state"));
|
||||
}
|
||||
self.firmware
|
||||
.os
|
||||
.detach_memcard()
|
||||
.map_err(|e| self.memcard_error("memcard_continue_in_memory", error_name(e)))?;
|
||||
if !self.firmware.resume_resident_game_from_home() {
|
||||
return Err(self.memcard_error("memcard_continue_in_memory", "invalid_state"));
|
||||
}
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
fn suspended_for_memcard(&mut self) -> bool {
|
||||
let Some(task) = self.firmware.os.lifecycle().resident_game_task() else { return false };
|
||||
self.firmware.os.lifecycle().task_state(task)
|
||||
== Some(prometeu_system::task::TaskState::Suspended)
|
||||
&& (self.firmware.os.memcard().session.removal_pending()
|
||||
|| self.firmware.os.memcard().session.diagnostics().reconciliation_required
|
||||
|| self.firmware.os.memcard().session.host_faulted())
|
||||
}
|
||||
pub(super) fn host_action_required(&mut self) -> bool {
|
||||
self.firmware.os.memcard().session.mode().is_some()
|
||||
&& self.firmware.os.lifecycle().resident_game_task().is_some()
|
||||
&& (self.firmware.os.memcard().session.removal_pending()
|
||||
|| self.firmware.os.memcard().host_faulted()
|
||||
|| !matches!(self.firmware.state, FirmwareState::GameRunning(_)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "memcard_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,487 @@
|
||||
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<Result<(), MemcardIoError>>,
|
||||
held: bool,
|
||||
}
|
||||
impl MemcardStorage for BootstrapStore {
|
||||
fn len(&self) -> Result<u64, MemcardIoError> {
|
||||
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<Result<(), MemcardIoError>>) {
|
||||
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<u64, MemcardIoError> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ fn thousand_reset_reload_cycles_release_session_owners_and_preserve_controls() {
|
||||
));
|
||||
assert_eq!(&*host.get_state().stack_top, &[Value::Int32(73)]);
|
||||
assert!(host.get_fault().is_none());
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
assert_eq!(host.firmware.os.sessions().vm_session_count(), 0);
|
||||
assert_eq!(
|
||||
observer.diagnostic_snapshot().used,
|
||||
|
||||
@@ -37,7 +37,7 @@ fn controlled_civil_time_is_independent_of_frames_pause_and_reset() {
|
||||
host.controlled_wall_clock().unwrap().set(10);
|
||||
host.advance_frame().expect("frame after clock adjustment");
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
|
||||
host.boot(&cartridge).expect("reboot");
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
|
||||
@@ -57,7 +57,7 @@ fn injected_civil_clock_remains_the_runtime_source_across_lifecycle() {
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), u64::MAX);
|
||||
clock.set(42);
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 42);
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
clock.advance(3);
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 45);
|
||||
}
|
||||
@@ -171,7 +171,7 @@ fn one_frame_returns_and_captures_the_exact_published_frame() {
|
||||
assert_eq!(captured.frame.ownership.app_mode, AppMode::Game);
|
||||
assert_eq!(captured.frame.ownership.app_id, 41);
|
||||
assert_eq!(captured.frame.stride_pixels, captured.frame.width);
|
||||
assert_eq!(captured.frame.pixels.len(), 480 * 270);
|
||||
assert_eq!(captured.frame.pixels.len(), 640 * 360);
|
||||
assert_eq!(host.capture_frame().expect("repeat capture"), captured);
|
||||
|
||||
let mut mutated_clone = captured.clone();
|
||||
@@ -290,7 +290,7 @@ fn two_runs_match_oracle() {
|
||||
fn reset_matches_fresh_host() {
|
||||
let mut host = boot_color();
|
||||
let _ = run_on(&mut host);
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
|
||||
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
|
||||
host.boot(color_cartridge()).expect("reboot");
|
||||
@@ -357,7 +357,7 @@ fn batch_stops_early_on_fault_and_reports_partial_progress() {
|
||||
#[test]
|
||||
fn advance_after_reset_reports_termination_without_ticking() {
|
||||
let mut host = boot_color();
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
let before = host.get_state().tick_index;
|
||||
|
||||
assert_eq!(host.advance_frame().expect("termination outcome"), AdvanceFrameOutcome::Terminated);
|
||||
@@ -477,8 +477,8 @@ fn assert_completed(outcome: prometeu_host_headless::AdvanceFramesOutcome, expec
|
||||
}
|
||||
|
||||
fn assert_color(captured: &CapturedFrame, color: u32) {
|
||||
assert_eq!(captured.frame.width, 480);
|
||||
assert_eq!(captured.frame.height, 270);
|
||||
assert_eq!(captured.frame.width, 640);
|
||||
assert_eq!(captured.frame.height, 360);
|
||||
assert!(captured.frame.pixels.iter().all(|pixel| *pixel == color));
|
||||
}
|
||||
|
||||
|
||||
@@ -50,15 +50,17 @@ pub fn build_program() -> Vec<u8> {
|
||||
|
||||
let draw = rom.len() as u32;
|
||||
rom.extend(asm(&format!(
|
||||
"PUSH_I32 180\n\
|
||||
PUSH_I32 75\n\
|
||||
"PUSH_I32 {x}\n\
|
||||
PUSH_I32 {y}\n\
|
||||
PUSH_I32 120\n\
|
||||
PUSH_I32 120\n\
|
||||
PUSH_I64 {}\n\
|
||||
GET_LOCAL 0\n\
|
||||
HOSTCALL 1\n\
|
||||
RET",
|
||||
Color::WHITE.raw()
|
||||
Color::WHITE.raw(),
|
||||
x = (prometeu_hal::graphics_contract::WIDTH - 120) / 2,
|
||||
y = (prometeu_hal::graphics_contract::HEIGHT - 120) / 2
|
||||
)));
|
||||
|
||||
patch_jump(&mut rom, jump_to_green_case_offset, green_case);
|
||||
|
||||
@@ -27,8 +27,8 @@ use std::path::PathBuf;
|
||||
|
||||
const STRESS_GLYPH_ASSET_ID: AssetId = 100;
|
||||
const STRESS_SCENE_ASSET_ID: AssetId = 1;
|
||||
const STRESS_VIEWPORT_W: i32 = 480;
|
||||
const STRESS_VIEWPORT_H: i32 = 270;
|
||||
const STRESS_VIEWPORT_W: i32 = prometeu_hal::graphics_contract::WIDTH as i32;
|
||||
const STRESS_VIEWPORT_H: i32 = prometeu_hal::graphics_contract::HEIGHT as i32;
|
||||
const STRESS_SPRITE_COLS: i32 = 48;
|
||||
const STRESS_SPRITE_ROWS: i32 = 24;
|
||||
const STRESS_SPRITE_SPACING_PX: i32 = 10;
|
||||
|
||||
@@ -2,6 +2,28 @@
|
||||
use clap::Args;
|
||||
use prometeu_host_headless::automation::Limits;
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct DesktopMediaArgs {
|
||||
/// Explicit memory-card image used by the desktop host.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub memcard: Option<String>,
|
||||
/// Create a new image; never replace an existing destination.
|
||||
#[arg(long, requires = "memcard")]
|
||||
pub create_memcard: bool,
|
||||
}
|
||||
impl DesktopMediaArgs {
|
||||
pub fn forwarded_args(&self) -> Vec<String> {
|
||||
let mut args = Vec::new();
|
||||
if let Some(path) = &self.memcard {
|
||||
args.extend(["--memcard".into(), path.clone()]);
|
||||
}
|
||||
if self.create_memcard {
|
||||
args.push("--create-memcard".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct HeadlessArgs {
|
||||
/// Use the versioned JSONL stdin/stdout protocol (required).
|
||||
|
||||
@@ -25,6 +25,8 @@ enum Commands {
|
||||
Run {
|
||||
/// Path to the cartridge (directory or .pmc file).
|
||||
cart: String,
|
||||
#[command(flatten)]
|
||||
media: prometeu_cli::DesktopMediaArgs,
|
||||
},
|
||||
/// Executes a cartridge in Assisted Mode (Debug).
|
||||
/// The runtime will wait for a DevTools connection before starting.
|
||||
@@ -34,6 +36,8 @@ enum Commands {
|
||||
/// TCP port for the DevTools server (default: 7777).
|
||||
#[arg(long, default_value_t = 7777)]
|
||||
port: u16,
|
||||
#[command(flatten)]
|
||||
media: prometeu_cli::DesktopMediaArgs,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -72,15 +76,17 @@ fn main() {
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
dispatch(&exe_dir, "prometeu-headless", &borrowed);
|
||||
}
|
||||
Some(Commands::Run { cart }) => {
|
||||
dispatch(&exe_dir, "prometeu-runtime", &["--run", &cart]);
|
||||
Some(Commands::Run { cart, media }) => {
|
||||
let mut args = vec!["--run".into(), cart];
|
||||
args.extend(media.forwarded_args());
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
dispatch(&exe_dir, "prometeu-runtime", &borrowed);
|
||||
}
|
||||
Some(Commands::Debug { cart, port }) => {
|
||||
dispatch(
|
||||
&exe_dir,
|
||||
"prometeu-runtime",
|
||||
&["--debug", &cart, "--port", &port.to_string()],
|
||||
);
|
||||
Some(Commands::Debug { cart, port, media }) => {
|
||||
let mut args = vec!["--debug".into(), cart, "--port".into(), port.to_string()];
|
||||
args.extend(media.forwarded_args());
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
dispatch(&exe_dir, "prometeu-runtime", &borrowed);
|
||||
}
|
||||
None => {
|
||||
use clap::CommandFactory;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use prometeu_bytecode::SourceSpan;
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::{DebugInfo, Export, SyscallDecl};
|
||||
use prometeu_bytecode::model::{ConstantPoolEntry, DebugInfo, Export, SyscallDecl};
|
||||
use prometeu_bytecode::registry::FunctionDecl;
|
||||
use prometeu_host_headless::{AdvanceFramesStop, HeadlessHost};
|
||||
use prometeu_test_support::program::{TestProgram, int64_signature};
|
||||
@@ -16,6 +16,8 @@ use std::sync::{
|
||||
mpsc,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
#[path = "support/memcard_process.rs"]
|
||||
mod memcard_process;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
@@ -221,6 +223,48 @@ fn cartridge_bytes(code: Vec<u8>, gfx: bool) -> TempDir {
|
||||
fn colored_cart() -> TempDir {
|
||||
cartridge("PUSH_I64 4278190335\nHOSTCALL 0\nRET\n", true)
|
||||
}
|
||||
|
||||
fn logging_cart(messages_per_frame: usize, message: &str) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
let code = assemble(&format!(
|
||||
"{}RET\n",
|
||||
"PUSH_I64 2\nPUSH_I64 41000\nPUSH_CONST 0\nHOSTCALL 0\n".repeat(messages_per_frame)
|
||||
))
|
||||
.unwrap();
|
||||
let mut module = TestProgram::single(code, int64_signature(0, 0), 0, 3);
|
||||
module.const_pool = vec![ConstantPoolEntry::String(message.into())];
|
||||
module.exports = vec![Export { symbol: "main".into(), func_idx: 0 }];
|
||||
module.syscalls = vec![SyscallDecl {
|
||||
module: "log".into(),
|
||||
name: "write_tag".into(),
|
||||
version: 1,
|
||||
arg_slots: 3,
|
||||
ret_slots: 0,
|
||||
}];
|
||||
fs::write(dir.0.join("program.pbx"), module.serialize()).unwrap();
|
||||
fs::write(
|
||||
dir.0.join("manifest.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"magic":"PMTU","cartridge_version":1,"app_id":41,"title":"Native log test",
|
||||
"app_version":"0.1.0","app_mode":"Game","capabilities":["log"]}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn initialize_logs(client: &mut Client) {
|
||||
let result = client.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":2},
|
||||
"requiredCapabilities":["log_read"]}),
|
||||
);
|
||||
assert_eq!(result["protocolVersion"]["minor"], 2);
|
||||
}
|
||||
|
||||
fn read_log_page(client: &mut Client, after: Value, limit: u16) -> Value {
|
||||
client.ok("get_logs", json!({"afterSequence":after,"limit":limit}))
|
||||
}
|
||||
fn boot(client: &mut Client, dir: &TempDir) {
|
||||
client.ok("boot", json!({"path":dir.0}));
|
||||
}
|
||||
@@ -241,7 +285,7 @@ fn png_bytes(capture: &Value) -> Vec<u8> {
|
||||
fn handshake_versions_capabilities_and_limits_are_explicit() {
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
assert_eq!(c.hello["runtimeVersion"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(c.hello["protocolVersion"], json!({"major":1,"minor":0}));
|
||||
assert_eq!(c.hello["protocolVersion"], json!({"major":1,"minor":2}));
|
||||
assert_eq!(
|
||||
c.hello["limits"],
|
||||
json!({"maxFrames":600,"maxCommandBytes":65536,"maxResponseBytes":33554432,
|
||||
@@ -267,7 +311,7 @@ fn handshake_versions_capabilities_and_limits_are_explicit() {
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":42},"requiredCapabilities":[]})
|
||||
)["protocolVersion"]["minor"],
|
||||
0
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
c.call(
|
||||
@@ -430,11 +474,15 @@ fn faults_and_boot_failures_are_structured_not_log_parsing() {
|
||||
fn conflicting_work_is_rejected_and_cancellation_reports_partial_progress() {
|
||||
let dir = colored_cart();
|
||||
let mut c = Client::new(&["--stdio", "--max-frames", "100000"]);
|
||||
c.initialize();
|
||||
initialize_logs(&mut c);
|
||||
boot(&mut c, &dir);
|
||||
let advance = c.send("advance", json!({"frames":100000}));
|
||||
assert_eq!(c.event()["type"], "progress");
|
||||
assert_eq!(c.call("reset", json!({}))["error"]["code"], "busy");
|
||||
assert_eq!(
|
||||
c.call("get_logs", json!({"afterSequence":null,"limit":1}))["error"]["code"],
|
||||
"busy"
|
||||
);
|
||||
c.ok("cancel", json!({"targetRequestId":advance}));
|
||||
let response = c.response(&advance);
|
||||
let result = &response["result"];
|
||||
@@ -549,6 +597,187 @@ fn missing_binary_and_invalid_cli_limits_fail_explicitly() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_read_requires_explicit_capability_and_minor_two() {
|
||||
for minor in [0, 1, 2] {
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
assert!(c.hello["capabilities"].as_array().unwrap().contains(&json!("log_read")));
|
||||
if minor < 2 {
|
||||
assert_eq!(
|
||||
c.call(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":minor},
|
||||
"requiredCapabilities":["log_read"]})
|
||||
)["error"]["code"],
|
||||
"incompatible_version"
|
||||
);
|
||||
}
|
||||
let initialized = c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":minor},
|
||||
"requiredCapabilities":[]}),
|
||||
);
|
||||
assert_eq!(initialized["protocolVersion"]["minor"], minor);
|
||||
assert_eq!(
|
||||
c.call("get_logs", json!({"afterSequence":null,"limit":1}))["error"]["code"],
|
||||
"unsupported_capability"
|
||||
);
|
||||
assert_eq!(c.ok("get_state", json!({}))["logicalFrameIndex"], 0);
|
||||
c.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_log_pages_are_read_only_replayable_and_survive_reset() {
|
||||
let dir = logging_cart(2, "{\"native\":\"é\"}");
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
initialize_logs(&mut c);
|
||||
let initial = read_log_page(&mut c, Value::Null, 1);
|
||||
assert_eq!(initial["events"][0]["sequence"], 0);
|
||||
assert_eq!(initial["events"][0]["source"], "pos");
|
||||
assert_eq!(initial["events"][0]["appId"], Value::Null);
|
||||
assert_eq!(initial["sessionId"], c.hello["sessionId"]);
|
||||
assert_eq!(initial["logEpoch"], 0);
|
||||
assert_eq!(initial["gap"], false);
|
||||
assert_eq!(initial["overflow"], false);
|
||||
boot(&mut c, &dir);
|
||||
c.ok("advance", json!({"frames":2}));
|
||||
let state = c.ok("get_state", json!({}));
|
||||
let fault = c.ok("get_fault", json!({}));
|
||||
let all = read_log_page(&mut c, Value::Null, 1024);
|
||||
let native = all["events"].as_array().unwrap();
|
||||
let app: Vec<_> = native.iter().filter(|event| event["source"] == "app").collect();
|
||||
assert_eq!(app.len(), 4);
|
||||
assert!(app.iter().all(|event| event["tag"] == 41000
|
||||
&& event["appId"] == 41
|
||||
&& event["level"] == "info"
|
||||
&& event["message"] == "{\"native\":\"é\"}"));
|
||||
let mut cursor = Value::Null;
|
||||
let mut paged = Vec::new();
|
||||
loop {
|
||||
let page = read_log_page(&mut c, cursor.clone(), 2);
|
||||
assert_eq!(page, read_log_page(&mut c, cursor.clone(), 2));
|
||||
paged.extend(page["events"].as_array().unwrap().iter().cloned());
|
||||
cursor = page["nextAfterSequence"].clone();
|
||||
if cursor == page["newestSequence"] {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(&paged, native);
|
||||
let empty = read_log_page(&mut c, cursor.clone(), 1);
|
||||
assert!(empty["events"].as_array().unwrap().is_empty());
|
||||
assert_eq!(empty["nextAfterSequence"], cursor);
|
||||
assert_eq!(state, c.ok("get_state", json!({})));
|
||||
assert_eq!(fault, c.ok("get_fault", json!({})));
|
||||
assert_eq!(
|
||||
c.call("get_logs", json!({"afterSequence":u64::MAX,"limit":1}))["error"]["code"],
|
||||
"invalid_cursor"
|
||||
);
|
||||
c.ok("reset", json!({}));
|
||||
let reset = read_log_page(&mut c, Value::Null, 1024);
|
||||
assert_eq!(&reset["events"].as_array().unwrap()[..native.len()], native);
|
||||
let after_reset = read_log_page(&mut c, cursor, 1024);
|
||||
assert!(!after_reset["events"].as_array().unwrap().is_empty());
|
||||
assert_eq!(after_reset["gap"], false);
|
||||
assert_eq!(after_reset["logEpoch"], 0);
|
||||
assert_eq!(after_reset["sessionId"], all["sessionId"]);
|
||||
c.close();
|
||||
let mut other = Client::new(&["--stdio"]);
|
||||
initialize_logs(&mut other);
|
||||
let fresh = read_log_page(&mut other, Value::Null, 1);
|
||||
assert_ne!(fresh["sessionId"], all["sessionId"]);
|
||||
assert_eq!(fresh["events"][0]["sequence"], 0);
|
||||
assert_eq!(
|
||||
other.call("get_logs", json!({"afterSequence":all["newestSequence"],"limit":1}))["error"]["code"],
|
||||
"invalid_cursor"
|
||||
);
|
||||
other.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timely_readers_outlive_ring_capacity_while_stale_cursors_report_gaps() {
|
||||
let dir = logging_cart(10, "retention");
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
initialize_logs(&mut c);
|
||||
boot(&mut c, &dir);
|
||||
let mut cursor = Value::Null;
|
||||
let mut count = 0;
|
||||
let mut saw_eviction = false;
|
||||
for _ in 0..5 {
|
||||
assert_eq!(c.ok("advance", json!({"frames":100}))["completed"], 100);
|
||||
loop {
|
||||
let page = read_log_page(&mut c, cursor.clone(), 128);
|
||||
assert_eq!(page["gap"], false);
|
||||
saw_eviction |= page["overflow"] == true;
|
||||
for event in page["events"].as_array().unwrap() {
|
||||
assert_eq!(event["sequence"].as_u64().unwrap(), count);
|
||||
count += 1;
|
||||
}
|
||||
cursor = page["nextAfterSequence"].clone();
|
||||
if cursor == page["newestSequence"] {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(count > 4096 && saw_eviction);
|
||||
for stale in [Value::Null, json!(0)] {
|
||||
let page = read_log_page(&mut c, stale, 1);
|
||||
assert_eq!(page["gap"], true);
|
||||
assert_eq!(page["overflow"], true);
|
||||
assert!(page["oldestSequence"].as_u64().unwrap() > 0);
|
||||
assert_eq!(page["events"][0]["sequence"], page["oldestSequence"]);
|
||||
}
|
||||
let empty = read_log_page(&mut c, cursor.clone(), 1);
|
||||
assert_eq!(empty["gap"], false);
|
||||
assert_eq!(empty["overflow"], true);
|
||||
assert_eq!(empty["nextAfterSequence"], cursor);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_log_responses_can_be_retried_without_draining() {
|
||||
let dir = logging_cart(10, &"x".repeat(200));
|
||||
let mut c = Client::new(&["--stdio", "--max-response-bytes", "4096"]);
|
||||
initialize_logs(&mut c);
|
||||
boot(&mut c, &dir);
|
||||
c.ok("advance", json!({"frames":5}));
|
||||
let state = c.ok("get_state", json!({}));
|
||||
let response = c.call("get_logs", json!({"afterSequence":null,"limit":1024}));
|
||||
assert_eq!(response["error"]["code"], "response_too_large");
|
||||
assert!(response.get("result").is_none());
|
||||
let first = read_log_page(&mut c, Value::Null, 1);
|
||||
assert_eq!(first["events"][0]["sequence"], 0);
|
||||
assert_eq!(first, read_log_page(&mut c, Value::Null, 1));
|
||||
assert_eq!(state, c.ok("get_state", json!({})));
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_observation_preserves_existing_guest_length_and_rate_limits() {
|
||||
let dir = logging_cart(12, &"x".repeat(300));
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
initialize_logs(&mut c);
|
||||
boot(&mut c, &dir);
|
||||
c.ok("advance", json!({"frames":1}));
|
||||
let page = read_log_page(&mut c, Value::Null, 1024);
|
||||
let app: Vec<_> = page["events"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|event| event["source"] == "app")
|
||||
.collect();
|
||||
let messages: Vec<_> = app.iter().filter(|event| event["tag"] == 41000).collect();
|
||||
assert_eq!(messages.len(), 10);
|
||||
assert!(messages.iter().all(|event| event["message"].as_str().unwrap().len() == 256));
|
||||
assert_eq!(app.len(), 11);
|
||||
assert!(app.iter().any(|event| event["tag"] == 0
|
||||
&& event["level"] == "warn"
|
||||
&& event["message"] == "App exceeded log limit per frame"));
|
||||
assert_eq!(page["gap"], false);
|
||||
assert_eq!(page["overflow"], false);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_distributed_request_fixtures_are_consistent() {
|
||||
let request: Value = serde_json::from_str(include_str!(
|
||||
@@ -614,3 +843,47 @@ fn packaged_installation_smoke() {
|
||||
c.input.take();
|
||||
c.wait_exit();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an isolated installation"]
|
||||
fn packaged_memcard_reopen_first_frame() {
|
||||
let installation = PathBuf::from(
|
||||
std::env::var_os("PROMETEU_PROTOCOL_TEST_INSTALL").expect("set isolated installation path"),
|
||||
);
|
||||
memcard_process::presentation_reopen(&installation.join("prometeu"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an isolated installation"]
|
||||
fn packaged_native_log_observation() {
|
||||
let installation = PathBuf::from(
|
||||
std::env::var_os("PROMETEU_PROTOCOL_TEST_INSTALL").expect("set isolated installation path"),
|
||||
);
|
||||
let cwd = TempDir::new();
|
||||
let dir = logging_cart(1, "installed native log");
|
||||
let mut c =
|
||||
Client::spawn(&installation.join("prometeu"), &["headless", "--stdio"], Some(&cwd.0));
|
||||
initialize_logs(&mut c);
|
||||
boot(&mut c, &dir);
|
||||
c.ok("advance", json!({"frames":1}));
|
||||
let page = read_log_page(&mut c, Value::Null, 1024);
|
||||
assert_eq!(page["gap"], false);
|
||||
assert!(
|
||||
page["events"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|event| event["source"] == "app" && event["message"] == "installed native log")
|
||||
);
|
||||
let installed_schema: Value = serde_json::from_slice(
|
||||
&fs::read(installation.join("headless-protocol/response.schema.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
jsonschema::validator_for(&installed_schema)
|
||||
.unwrap()
|
||||
.validate(&json!({
|
||||
"type":"response","sessionId":c.hello["sessionId"],"requestId":"logs","result":page,
|
||||
}))
|
||||
.unwrap();
|
||||
c.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
use super::*;
|
||||
use prometeu_test_support::memcard_fixture::{MemcardFixture, memcard_program};
|
||||
|
||||
fn card(kind: MemcardFixture, version: &str) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
fs::write(dir.0.join("program.pbx"), memcard_program(kind)).unwrap();
|
||||
fs::write(
|
||||
dir.0.join("manifest.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"magic":"PMTU","cartridge_version":1,"app_id":4294967295u32,
|
||||
"title":"Neutral persistence","app_version":version,"app_mode":"Game",
|
||||
"capabilities":["memcard"],"memcard_slots":1
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
dir
|
||||
}
|
||||
fn start_at(binary: &Path) -> Client {
|
||||
let mut c = Client::spawn(binary, &["headless", "--stdio"], Some(&std::env::temp_dir()));
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
|
||||
);
|
||||
c
|
||||
}
|
||||
fn start() -> Client {
|
||||
start_at(Path::new(env!("CARGO_BIN_EXE_prometeu")))
|
||||
}
|
||||
fn mount(c: &mut Client, path: &Path, action: &str, access: &str) -> Value {
|
||||
c.ok("memcard_mount", json!({"path":path,"action":action,"access":access}))
|
||||
}
|
||||
fn launch(c: &mut Client, dir: &TempDir, choice: &str) {
|
||||
c.ok("boot", json!({"path":dir.0,"memcardChoice":choice}));
|
||||
}
|
||||
fn oracle(c: &mut Client, expected: i64) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let advance = c.ok("advance", json!({"frames":1}));
|
||||
assert_eq!(
|
||||
advance["stop"],
|
||||
"completed",
|
||||
"{advance}; state={}; mem={}; fault={}",
|
||||
c.ok("get_state", json!({})),
|
||||
c.ok("get_memcard_state", json!({})),
|
||||
c.ok("get_fault", json!({}))
|
||||
);
|
||||
let state = c.ok("get_state", json!({}));
|
||||
let top = state["stackTop"].as_array().unwrap();
|
||||
if top.last().and_then(|v| v["value"].as_str()) == Some(&expected.to_string()) {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "oracle {expected} not reached: {state}");
|
||||
}
|
||||
}
|
||||
fn reason(c: &mut Client, command: &str, params: Value, expected: &str) -> Value {
|
||||
let error = c.call(command, params)["error"].clone();
|
||||
assert_eq!(error["code"], "memcard_error", "{error}");
|
||||
assert_eq!(error["details"]["reason"], expected, "{error}");
|
||||
error["details"]["state"].clone()
|
||||
}
|
||||
fn persistence(binary: &Path) {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("save.pmc");
|
||||
let write = card(MemcardFixture::Write, "1");
|
||||
let mut first = start_at(binary);
|
||||
let mounted = mount(&mut first, &image, "create", "read_write");
|
||||
assert_eq!(mounted["media"]["cardId"].as_str().unwrap().len(), 32);
|
||||
launch(&mut first, &write, "persistent");
|
||||
oracle(&mut first, 101);
|
||||
let saved = first.ok("get_memcard_state", json!({}));
|
||||
assert_eq!(saved["request"]["state"], "success");
|
||||
assert_eq!(saved["request"]["retained"], true);
|
||||
assert_eq!(saved["dirty"], false);
|
||||
assert_eq!(saved["io"]["active"], false);
|
||||
first.close();
|
||||
let bytes = fs::read(&image).unwrap();
|
||||
for version in ["1", "2"] {
|
||||
let read = card(MemcardFixture::Read, version);
|
||||
let mut next = start_at(binary);
|
||||
mount(&mut next, &image, "open", "read_write");
|
||||
launch(&mut next, &read, "persistent");
|
||||
oracle(&mut next, 201);
|
||||
assert_eq!(next.ok("get_state", json!({}))["appId"], 4294967295u32);
|
||||
assert_eq!(
|
||||
next.ok("get_memcard_state", json!({}))["request"],
|
||||
Value::Null,
|
||||
"reader must not submit a save"
|
||||
);
|
||||
next.close();
|
||||
assert!(fs::read(&image).unwrap() == bytes, "readback must not rewrite the image");
|
||||
}
|
||||
let read = card(MemcardFixture::Read, "2");
|
||||
let mut memory = start_at(binary);
|
||||
mount(&mut memory, &image, "open", "read_only");
|
||||
reason(&mut memory, "boot", json!({"path":read.0,"memcardChoice":"persistent"}), "read_only");
|
||||
memory.ok("reset", json!({}));
|
||||
launch(&mut memory, &read, "memory_existing");
|
||||
oracle(&mut memory, 201);
|
||||
assert_eq!(memory.ok("get_memcard_state", json!({}))["session"]["mode"], "memory_only");
|
||||
memory.close();
|
||||
assert!(fs::read(&image).unwrap() == bytes);
|
||||
}
|
||||
|
||||
pub(super) fn presentation_reopen(binary: &Path) {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("presentation-reopen.pmc");
|
||||
let write = card(MemcardFixture::Write, "1");
|
||||
let mut writer = start_at(binary);
|
||||
mount(&mut writer, &image, "create", "read_write");
|
||||
launch(&mut writer, &write, "persistent");
|
||||
oracle(&mut writer, 101);
|
||||
assert_eq!(writer.ok("get_memcard_state", json!({}))["dirty"], false);
|
||||
writer.close();
|
||||
|
||||
for version in ["1", "2"] {
|
||||
let read = card(MemcardFixture::ReadWithPresentation, version);
|
||||
let mut reader = start_at(binary);
|
||||
mount(&mut reader, &image, "open", "read_write");
|
||||
launch(&mut reader, &read, "persistent");
|
||||
let booted = reader.ok("get_state", json!({}));
|
||||
assert_eq!(booted["pc"], 0);
|
||||
assert_eq!(booted["tickIndex"], 0);
|
||||
assert_eq!(booted["logicalFrameIndex"], 0);
|
||||
// Exactly one command owns the first frame; there is no oracle retry.
|
||||
let advanced = reader.ok("advance", json!({"frames":1}));
|
||||
assert_eq!(advanced, json!({"requested":1,"completed":1,"stop":"completed"}));
|
||||
let state = reader.ok("get_state", json!({}));
|
||||
assert_eq!(state["logicalFrameIndex"], 1);
|
||||
assert_eq!(state["tickIndex"], 2);
|
||||
assert_eq!(state["status"], "paused");
|
||||
assert_eq!(state["appId"], 4294967295u32);
|
||||
assert_eq!(state["stackTop"].as_array().unwrap().last().unwrap()["value"], "201");
|
||||
assert_eq!(reader.ok("get_fault", json!({})), Value::Null);
|
||||
let media = reader.ok("get_memcard_state", json!({}));
|
||||
assert_eq!(
|
||||
media["request"],
|
||||
Value::Null,
|
||||
"presentation must finish without a payload save"
|
||||
);
|
||||
assert_eq!(media["io"]["active"], false);
|
||||
assert_eq!(media["dirty"], false);
|
||||
assert_eq!(reader.ok("capture", json!({}))["logicalFrameIndex"], 1);
|
||||
reader.close();
|
||||
}
|
||||
// Preserve the original reader's independent read-without-writing oracle.
|
||||
let bytes = fs::read(&image).unwrap();
|
||||
let read = card(MemcardFixture::Read, "2");
|
||||
let mut reader = start_at(binary);
|
||||
mount(&mut reader, &image, "open", "read_write");
|
||||
launch(&mut reader, &read, "persistent");
|
||||
oracle(&mut reader, 201);
|
||||
reader.close();
|
||||
assert_eq!(fs::read(&image).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memcard_reopen_presentation_completes_exactly_one_first_frame() {
|
||||
presentation_reopen(Path::new(env!("CARGO_BIN_EXE_prometeu")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memcard_public_distinct_process_save_readback_and_version_identity() {
|
||||
persistence(Path::new(env!("CARGO_BIN_EXE_prometeu")));
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive"]
|
||||
fn packaged_memcard_process_persistence() {
|
||||
let installation = PathBuf::from(
|
||||
std::env::var_os("PROMETEU_PROTOCOL_TEST_INSTALL").expect("extracted distribution"),
|
||||
);
|
||||
persistence(&installation.join("prometeu"));
|
||||
}
|
||||
#[test]
|
||||
fn memcard_dirty_refusal_retains_channel_and_explicit_ram_has_no_save() {
|
||||
let dirty = card(MemcardFixture::Dirty, "1");
|
||||
let mut c = start();
|
||||
launch(&mut c, &dirty, "memory_fresh");
|
||||
oracle(&mut c, 301);
|
||||
for command in ["shutdown", "reset"] {
|
||||
let state = reason(&mut c, command, json!({}), "unsaved_changes");
|
||||
assert_eq!(state["dirty"], true);
|
||||
assert_eq!(state["session"]["resident"], true);
|
||||
assert_eq!(c.ok("get_state", json!({}))["appId"], 4294967295u32);
|
||||
}
|
||||
let reset = c.ok("reset", json!({"discardUnsaved":true,"pendingWrites":"cancel"}));
|
||||
assert_eq!(reset["memcard"]["dirty"], false);
|
||||
let write = card(MemcardFixture::Write, "1");
|
||||
launch(&mut c, &write, "memory_fresh");
|
||||
oracle(&mut c, 104);
|
||||
let state = c.ok("get_memcard_state", json!({}));
|
||||
assert_eq!(state["request"]["state"], "memory_only");
|
||||
assert_eq!(state["dirty"], true);
|
||||
assert_eq!(state["io"]["active"], false);
|
||||
assert_eq!(state["media"]["path"], Value::Null);
|
||||
c.ok("shutdown", json!({"discardUnsaved":true}));
|
||||
c.wait_exit();
|
||||
}
|
||||
#[test]
|
||||
fn memcard_media_errors_and_negotiation_never_select_a_fallback() {
|
||||
let root = TempDir::new();
|
||||
let missing = root.0.join("missing.pmc");
|
||||
let mut old = Client::new(&["--stdio"]);
|
||||
old.initialize();
|
||||
assert_eq!(
|
||||
old.call("memcard_mount", json!({"path":missing,"action":"create","access":"read_write"}))
|
||||
["error"]["code"],
|
||||
"unsupported_capability"
|
||||
);
|
||||
assert!(!missing.exists());
|
||||
old.close();
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
assert_eq!(
|
||||
c.call(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":0},"requiredCapabilities":["memcard"]})
|
||||
)["error"]["code"],
|
||||
"incompatible_version"
|
||||
);
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
|
||||
);
|
||||
reason(
|
||||
&mut c,
|
||||
"memcard_mount",
|
||||
json!({"path":missing,"action":"open","access":"read_write"}),
|
||||
"unavailable",
|
||||
);
|
||||
assert!(!missing.exists());
|
||||
let cart = card(MemcardFixture::Write, "1");
|
||||
reason(&mut c, "boot", json!({"path":cart.0}), "choice_required");
|
||||
assert_eq!(c.ok("get_state", json!({}))["logicalFrameIndex"], 0);
|
||||
c.ok("reset", json!({}));
|
||||
let corrupt = root.0.join("corrupt.pmc");
|
||||
let mut bytes = vec![0; 5_259_264];
|
||||
bytes[..8].copy_from_slice(b"PMCARD1\0");
|
||||
bytes[8] = 1;
|
||||
fs::write(&corrupt, &bytes).unwrap();
|
||||
reason(
|
||||
&mut c,
|
||||
"memcard_mount",
|
||||
json!({"path":corrupt,"action":"open","access":"read_write"}),
|
||||
"corrupt",
|
||||
);
|
||||
assert!(fs::read(&corrupt).unwrap() == bytes);
|
||||
assert_eq!(c.ok("get_memcard_state", json!({}))["session"]["mode"], Value::Null);
|
||||
c.close();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn memcard_process_ownership_covers_aliases_readers_and_release() {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("save.pmc");
|
||||
let hard = root.0.join("hard.pmc");
|
||||
let sym = root.0.join("sym.pmc");
|
||||
let mut owner = start();
|
||||
mount(&mut owner, &image, "create", "read_write");
|
||||
fs::hard_link(&image, &hard).unwrap();
|
||||
std::os::unix::fs::symlink(&image, &sym).unwrap();
|
||||
let bytes = fs::read(&image).unwrap();
|
||||
let mut contender = start();
|
||||
for path in [&image, &hard, &sym] {
|
||||
for access in ["read_only", "read_write"] {
|
||||
reason(
|
||||
&mut contender,
|
||||
"memcard_mount",
|
||||
json!({"path":path,"action":"open","access":access}),
|
||||
"busy",
|
||||
);
|
||||
}
|
||||
}
|
||||
reason(
|
||||
&mut contender,
|
||||
"memcard_mount",
|
||||
json!({"path":image,"action":"create","access":"read_write"}),
|
||||
"already_exists",
|
||||
);
|
||||
assert!(fs::read(&image).unwrap() == bytes);
|
||||
owner.ok("memcard_unmount", json!({}));
|
||||
mount(&mut contender, &image, "open", "read_only");
|
||||
reason(
|
||||
&mut owner,
|
||||
"memcard_mount",
|
||||
json!({"path":image,"action":"open","access":"read_only"}),
|
||||
"busy",
|
||||
);
|
||||
contender.close();
|
||||
mount(&mut owner, &image, "open", "read_write");
|
||||
owner.close();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn memcard_creation_race_and_process_death_release_real_ownership() {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("race.pmc");
|
||||
// Kill the actual storage-owning process rather than its dispatcher parent.
|
||||
let mut a = Client::new(&["--stdio"]);
|
||||
let mut b = Client::new(&["--stdio"]);
|
||||
for c in [&mut a, &mut b] {
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
|
||||
);
|
||||
}
|
||||
let params = json!({"path":image,"action":"create","access":"read_write"});
|
||||
let aid = a.send("memcard_mount", params.clone());
|
||||
let bid = b.send("memcard_mount", params);
|
||||
let ar = a.response(&aid);
|
||||
let br = b.response(&bid);
|
||||
assert_ne!(
|
||||
ar.get("result").is_some(),
|
||||
br.get("result").is_some(),
|
||||
"exactly one creator must win"
|
||||
);
|
||||
let (winner, loser, error) =
|
||||
if ar.get("result").is_some() { (&mut a, &mut b, br) } else { (&mut b, &mut a, ar) };
|
||||
assert_eq!(error["error"]["details"]["reason"], "already_exists");
|
||||
let before = fs::read(&image).unwrap();
|
||||
winner.child.kill().unwrap();
|
||||
winner.child.wait().unwrap();
|
||||
mount(loser, &image, "open", "read_write");
|
||||
loser.close();
|
||||
assert!(fs::read(&image).unwrap() == before);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn memcard_access_denial_is_typed_and_does_not_create_or_modify_media() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("denied.pmc");
|
||||
let mut creator = start();
|
||||
mount(&mut creator, &image, "create", "read_write");
|
||||
creator.close();
|
||||
let before = fs::read(&image).unwrap();
|
||||
fs::set_permissions(&image, fs::Permissions::from_mode(0o0)).unwrap();
|
||||
let mut c = start();
|
||||
reason(
|
||||
&mut c,
|
||||
"memcard_mount",
|
||||
json!({"path":image,"action":"open","access":"read_write"}),
|
||||
"access_denied",
|
||||
);
|
||||
c.close();
|
||||
fs::set_permissions(&image, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
assert!(fs::read(&image).unwrap() == before);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn desktop_dispatch_forwards_explicit_media_without_interpreting_player_policy() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let installation = TempDir::new();
|
||||
let dispatcher = installation.0.join("prometeu");
|
||||
fs::copy(env!("CARGO_BIN_EXE_prometeu"), &dispatcher).unwrap();
|
||||
let runtime = installation.0.join("prometeu-runtime");
|
||||
fs::write(&runtime, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n").unwrap();
|
||||
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
for command in ["run", "debug"] {
|
||||
let output = Command::new(&dispatcher)
|
||||
.args([command, "cartridge", "--memcard", "image with spaces.pmc", "--create-memcard"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let actual = String::from_utf8(output.stdout).unwrap();
|
||||
let mut expected = vec![format!("--{command}"), "cartridge".into()];
|
||||
if command == "debug" {
|
||||
expected.extend(["--port".into(), "7777".into()]);
|
||||
}
|
||||
expected.extend([
|
||||
"--memcard".into(),
|
||||
"image with spaces.pmc".into(),
|
||||
"--create-memcard".into(),
|
||||
]);
|
||||
assert_eq!(actual.lines().collect::<Vec<_>>(), expected);
|
||||
}
|
||||
assert!(
|
||||
!Command::new(&dispatcher)
|
||||
.args(["run", "cartridge", "--create-memcard"])
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn memcard_idle_observation_never_advances_guest_counters() {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("save.pmc");
|
||||
let cart = card(MemcardFixture::Write, "1");
|
||||
let mut c = start();
|
||||
mount(&mut c, &image, "create", "read_write");
|
||||
launch(&mut c, &cart, "persistent");
|
||||
c.ok("advance", json!({"frames":1}));
|
||||
let before = c.ok("get_state", json!({}));
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let state = c.ok("get_memcard_state", json!({}));
|
||||
if !state["io"]["active"].as_bool().unwrap() {
|
||||
assert_eq!(state["request"]["state"], "success");
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline);
|
||||
}
|
||||
let after = c.ok("get_state", json!({}));
|
||||
for field in ["pc", "logicalFrameIndex", "tickIndex", "stackTop"] {
|
||||
assert_eq!(before[field], after[field], "{field}");
|
||||
}
|
||||
c.close();
|
||||
}
|
||||
@@ -45,5 +45,138 @@
|
||||
"requestId": "null-params",
|
||||
"command": "get_state",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-8",
|
||||
"command": "memcard_mount",
|
||||
"params": {
|
||||
"path": "x",
|
||||
"action": "create",
|
||||
"access": "read_only"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-9",
|
||||
"command": "memcard_mount",
|
||||
"params": {
|
||||
"path": "x",
|
||||
"action": "open"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-10",
|
||||
"command": "boot",
|
||||
"params": {
|
||||
"path": "x",
|
||||
"memcardChoice": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-11",
|
||||
"command": "boot",
|
||||
"params": {
|
||||
"path": "x",
|
||||
"memcardChoice": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-12",
|
||||
"command": "shutdown",
|
||||
"params": {
|
||||
"discardUnsaved": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-13",
|
||||
"command": "reset",
|
||||
"params": {
|
||||
"pendingWrites": "save"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-mem-14",
|
||||
"command": "get_memcard_state",
|
||||
"params": {
|
||||
"anything": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-0",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-1",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-2",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-3",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 1025
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-4",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 1.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-5",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": -1,
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-6",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": 18446744073709551616,
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-7",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": "0",
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-8",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": 0.5,
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "bad-logs-9",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 1,
|
||||
"filter": "app"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://prometeu.dev/headless/v1/request.schema.json",
|
||||
"title": "Prometeu Headless v1 Request",
|
||||
"title": "Prometeu Headless v1.2 Request",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
@@ -65,6 +65,13 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"pattern": "\\S"
|
||||
},
|
||||
"memcardChoice": {
|
||||
"enum": [
|
||||
"persistent",
|
||||
"memory_fresh",
|
||||
"memory_existing"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,7 +136,19 @@
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"maxProperties": 0
|
||||
"properties": {
|
||||
"discardUnsaved": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pendingWrites": {
|
||||
"enum": [
|
||||
"wait",
|
||||
"cancel"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -184,7 +203,150 @@
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"maxProperties": 0
|
||||
"properties": {
|
||||
"discardUnsaved": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pendingWrites": {
|
||||
"enum": [
|
||||
"wait",
|
||||
"cancel"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"command": {
|
||||
"const": "memcard_mount"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"pattern": "\\S"
|
||||
},
|
||||
"action": {
|
||||
"enum": [
|
||||
"open",
|
||||
"create"
|
||||
]
|
||||
},
|
||||
"access": {
|
||||
"enum": [
|
||||
"read_write",
|
||||
"read_only"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"action",
|
||||
"access"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"not": {
|
||||
"properties": {
|
||||
"action": {
|
||||
"const": "create"
|
||||
},
|
||||
"access": {
|
||||
"const": "read_only"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action",
|
||||
"access"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"command": {
|
||||
"const": "memcard_unmount"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"command": {
|
||||
"const": "get_memcard_state"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"command": {
|
||||
"const": "memcard_reconcile"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"command": {
|
||||
"const": "memcard_continue_in_memory"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"command": {
|
||||
"const": "get_logs"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"afterSequence",
|
||||
"limit"
|
||||
],
|
||||
"properties": {
|
||||
"afterSequence": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 1024
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,5 +74,116 @@
|
||||
"params": {
|
||||
"targetRequestId": "advance"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-11",
|
||||
"command": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 1
|
||||
},
|
||||
"requiredCapabilities": [
|
||||
"memcard"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-12",
|
||||
"command": "memcard_mount",
|
||||
"params": {
|
||||
"path": "/save.pmc",
|
||||
"action": "open",
|
||||
"access": "read_only"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-13",
|
||||
"command": "memcard_mount",
|
||||
"params": {
|
||||
"path": "/new.pmc",
|
||||
"action": "create",
|
||||
"access": "read_write"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-14",
|
||||
"command": "boot",
|
||||
"params": {
|
||||
"path": "/cartridge",
|
||||
"memcardChoice": "memory_existing"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-15",
|
||||
"command": "get_memcard_state",
|
||||
"params": {}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-16",
|
||||
"command": "memcard_unmount",
|
||||
"params": {}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-17",
|
||||
"command": "memcard_reconcile",
|
||||
"params": {}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-18",
|
||||
"command": "memcard_continue_in_memory",
|
||||
"params": {}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-19",
|
||||
"command": "reset",
|
||||
"params": {
|
||||
"discardUnsaved": true,
|
||||
"pendingWrites": "cancel"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "mem-20",
|
||||
"command": "shutdown",
|
||||
"params": {
|
||||
"pendingWrites": "wait"
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "logs-init",
|
||||
"command": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"requiredCapabilities": [
|
||||
"log_read"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "logs-first",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "logs-next",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": 0,
|
||||
"limit": 1024
|
||||
}
|
||||
},
|
||||
{
|
||||
"requestId": "logs-u64",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": 18446744073709551615,
|
||||
"limit": 128
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "Prometeu headless server messages v1.0",
|
||||
"$comment": "requestId additionally has a 128 UTF-8-byte bound; uint counters require lossless decoding. v1.0 producers are checked strictly. Consumers must allow compatible minor extensions.",
|
||||
"title": "Prometeu Headless v1.2 Response",
|
||||
"$comment": "Producer schema for supported 1.0/1.1/1.2 shapes. Consumers permit compatible minor additions; 64-bit identities require lossless decoding.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
@@ -167,12 +167,21 @@
|
||||
"properties": {
|
||||
"closed": {
|
||||
"const": true
|
||||
},
|
||||
"memcard": {
|
||||
"$ref": "#/$defs/memcard"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"closed"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/memcard"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/logPage"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -222,7 +231,42 @@
|
||||
"message",
|
||||
"details"
|
||||
],
|
||||
"additionalProperties": false
|
||||
"additionalProperties": false,
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"code": {
|
||||
"const": "memcard_error"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"details": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"operation": {
|
||||
"type": "string"
|
||||
},
|
||||
"reason": {
|
||||
"$ref": "#/$defs/memcardReason"
|
||||
},
|
||||
"state": {
|
||||
"$ref": "#/$defs/memcard"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"operation",
|
||||
"reason",
|
||||
"state"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"stack": {
|
||||
"oneOf": [
|
||||
@@ -271,8 +315,24 @@
|
||||
"const": "heap_ref"
|
||||
},
|
||||
"value": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"generation": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"index",
|
||||
"generation"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -347,6 +407,9 @@
|
||||
"terminated",
|
||||
"faulted"
|
||||
]
|
||||
},
|
||||
"memcard": {
|
||||
"$ref": "#/$defs/memcard"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -694,7 +757,8 @@
|
||||
"faulted",
|
||||
"terminated",
|
||||
"canceled",
|
||||
"host_error"
|
||||
"host_error",
|
||||
"action_required"
|
||||
]
|
||||
},
|
||||
"fault": {
|
||||
@@ -952,7 +1016,7 @@
|
||||
"DuplicateFn",
|
||||
"StructuralTypeCycle",
|
||||
"CaptureIndex",
|
||||
"CaptureCount",
|
||||
"CaptureCount",
|
||||
"CapturedDirectCall",
|
||||
"RemovedOpcode",
|
||||
"ArrayCycle",
|
||||
@@ -1368,6 +1432,490 @@
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"memcardReason": {
|
||||
"enum": [
|
||||
"choice_required",
|
||||
"unavailable",
|
||||
"corrupt",
|
||||
"unsupported",
|
||||
"read_only",
|
||||
"access_denied",
|
||||
"already_exists",
|
||||
"busy",
|
||||
"no_space",
|
||||
"out_of_memory",
|
||||
"invalid_state",
|
||||
"invalid_range",
|
||||
"counter_exhausted",
|
||||
"identity_mismatch",
|
||||
"unsaved_changes",
|
||||
"indeterminate",
|
||||
"restart_required",
|
||||
"io_error",
|
||||
"canceled"
|
||||
]
|
||||
},
|
||||
"memcard": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"media": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"cardId": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{32}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"access": {
|
||||
"anyOf": [
|
||||
{
|
||||
"enum": [
|
||||
"read_write",
|
||||
"read_only"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mountEpoch": {
|
||||
"type": "string",
|
||||
"pattern": "^(0|[1-9][0-9]*)$"
|
||||
},
|
||||
"preparation": {
|
||||
"enum": [
|
||||
"idle",
|
||||
"pending",
|
||||
"ready",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"error": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/memcardReason"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"recovered": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"degraded": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"writeBlocked": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"cardId",
|
||||
"access",
|
||||
"mountEpoch",
|
||||
"preparation",
|
||||
"error",
|
||||
"recovered",
|
||||
"degraded",
|
||||
"writeBlocked"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"appId": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"choice": {
|
||||
"anyOf": [
|
||||
{
|
||||
"enum": [
|
||||
"persistent",
|
||||
"memory_fresh",
|
||||
"memory_existing"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"enum": [
|
||||
"persistent",
|
||||
"memory_only"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"bootAttempted": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"bootPhase": {
|
||||
"enum": [
|
||||
"idle",
|
||||
"loading",
|
||||
"choice_required",
|
||||
"preparing",
|
||||
"running",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"resident": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"actionRequired": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"appId",
|
||||
"choice",
|
||||
"mode",
|
||||
"bootAttempted",
|
||||
"bootPhase",
|
||||
"resident",
|
||||
"actionRequired"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"dirty": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"dirtySlots": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 63
|
||||
},
|
||||
"uniqueItems": true,
|
||||
"maxItems": 64
|
||||
},
|
||||
"request": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^(0|[1-9][0-9]*)$"
|
||||
},
|
||||
"state": {
|
||||
"enum": [
|
||||
"pending",
|
||||
"success",
|
||||
"failure",
|
||||
"indeterminate",
|
||||
"memory_only"
|
||||
]
|
||||
},
|
||||
"reason": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/memcardReason"
|
||||
},
|
||||
{
|
||||
"enum": [
|
||||
"none",
|
||||
"timeout"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"storageError": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/memcardReason"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"operation": {
|
||||
"enum": [
|
||||
"commit",
|
||||
"presentation"
|
||||
]
|
||||
},
|
||||
"slot": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 63
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"retained": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"state",
|
||||
"reason",
|
||||
"storageError",
|
||||
"operation",
|
||||
"slot",
|
||||
"retained"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"io": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"active": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"deferred": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"phase": {
|
||||
"enum": [
|
||||
"idle",
|
||||
"preparing",
|
||||
"deferred",
|
||||
"queued",
|
||||
"running",
|
||||
"returned"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"active",
|
||||
"deferred",
|
||||
"phase"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"recovery": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"removalPending": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"reconciliationRequired": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartRequired": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"removalPending",
|
||||
"reconciliationRequired",
|
||||
"restartRequired"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"media",
|
||||
"session",
|
||||
"dirty",
|
||||
"dirtySlots",
|
||||
"request",
|
||||
"io",
|
||||
"recovery"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"logEvent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sequence": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"frame": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"timestampMs": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"level": {
|
||||
"enum": [
|
||||
"trace",
|
||||
"debug",
|
||||
"info",
|
||||
"warn",
|
||||
"error"
|
||||
]
|
||||
},
|
||||
"source": {
|
||||
"enum": [
|
||||
"pos",
|
||||
"hub",
|
||||
"vm",
|
||||
"fs",
|
||||
"app"
|
||||
]
|
||||
},
|
||||
"appId": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"tag": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"sequence",
|
||||
"frame",
|
||||
"timestampMs",
|
||||
"level",
|
||||
"source",
|
||||
"appId",
|
||||
"tag",
|
||||
"message"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"source": {
|
||||
"const": "app"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"appId": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"else": {
|
||||
"properties": {
|
||||
"appId": {
|
||||
"type": "null"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"logPage": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sessionId": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"logEpoch": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"events": {
|
||||
"type": "array",
|
||||
"maxItems": 1024,
|
||||
"items": {
|
||||
"$ref": "#/$defs/logEvent"
|
||||
}
|
||||
},
|
||||
"oldestSequence": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"newestSequence": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"nextAfterSequence": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"minimum": 0,
|
||||
"maximum": 18446744073709551615
|
||||
},
|
||||
"gap": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"overflow": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"sessionId",
|
||||
"logEpoch",
|
||||
"events",
|
||||
"oldestSequence",
|
||||
"newestSequence",
|
||||
"nextAfterSequence",
|
||||
"gap",
|
||||
"overflow"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
50 53 54 31 01 00 00 00 04 00 00 00 00 00 00 00
|
||||
01 00 00 00 00 00 00 00 2a 00 00 00 00 00 00 00
|
||||
@@ -0,0 +1,6 @@
|
||||
50 53 54 31 01 00 00 00 09 00 00 00 38 00 00 00
|
||||
01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
|
||||
01 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00
|
||||
02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00
|
||||
ff 00 00 ff 00 00 ff 80
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
---
|
||||
id: LSN-0073
|
||||
ticket: memcard-public-host-persistence
|
||||
title: Public persistence is a process and ownership contract
|
||||
created: 2026-10-30
|
||||
tags: [memcard, persistence, headless, host, ownership]
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
The runtime now exposes media preparation, three explicit boot choices, native
|
||||
observation, protected teardown and same-media recovery through its installed
|
||||
headless protocol. The file backend has a single owner across compatible hosts,
|
||||
including read-only opens. Runtime tests remain neutral PBX/ABI programs and do
|
||||
not depend on a source-language frontend or another application's build.
|
||||
|
||||
Historical source: accepted decision DEC-0068, executed through PLN-0199 from
|
||||
AGD-0071. Their workflow files are disposable. The published contracts are
|
||||
[Save Memory and MEMCARD](../../../docs/specs/runtime/08-save-memory-and-memcard.md)
|
||||
and [Headless Automation](../../../docs/specs/runtime/11a-headless-automation-protocol.md#memcard-controls).
|
||||
This lesson explains those published results rather than defining new behavior.
|
||||
|
||||
## A native API is not an installed integration surface
|
||||
|
||||
Injecting storage into an in-process host is useful for controlled faults, but
|
||||
does not establish that a consumer can configure the distributed executable.
|
||||
Media preparation and player choice therefore became explicit operations of
|
||||
the existing transport. The negotiated minor and capability identify support;
|
||||
an executable version string alone does not. A client without the extension
|
||||
continues using the original non-memcard shapes.
|
||||
|
||||
Preparing media separately from boot lets missing, corrupt, read-only and busy
|
||||
files produce native domain errors before game initialization. Opening is not
|
||||
creation. A persistent choice does not turn into fresh RAM after a failure.
|
||||
These distinctions belong to the provider so every consumer sees the same
|
||||
storage and admission policy.
|
||||
|
||||
## Result knowledge, RAM state and resource lifetime are separate
|
||||
|
||||
A retained terminal result is a statement about an attempt. It is not evidence
|
||||
that a worker still owns the source, and absence of a mounted backend is not
|
||||
evidence that the worker is active. In particular, reacquisition can fail after
|
||||
the previous IO safely returned. An explicit worker-return observation separates
|
||||
that case from an outstanding operation.
|
||||
|
||||
This distinction also matters after watchdog escalation. A late completion can
|
||||
provide the original worker error and return its resources without rewriting the
|
||||
terminal result already exposed to the game. Same-card reconciliation keeps that
|
||||
original result available until guest release. It does not consume the result
|
||||
to make media operations easier. Controlled tests exercise both a refusal before
|
||||
publication and an uncertain attempt inside metadata publication.
|
||||
|
||||
Ending a session does not establish media health. An installed image with an
|
||||
indeterminate publication stays write-blocked after reset, and a new persistent
|
||||
admission cannot bypass the need for explicit revalidation.
|
||||
|
||||
RAM has its own state. A memory-only commit completes without a durability claim
|
||||
and leaves modified RAM dirty. Teardown first waits for or cancels already
|
||||
admitted IO, then reevaluates RAM. It can avoid an unnecessary discard prompt if
|
||||
the save completes cleanly during that wait. If dirty data remains, refusal keeps
|
||||
the process, session and channel available for a later explicit decision.
|
||||
|
||||
## A process boundary makes file ownership visible
|
||||
|
||||
Serializing one runtime's transactions does not exclude another process that
|
||||
opened the same image from making decisions against an older map. The shared
|
||||
file backend now attaches an exclusive OS lock to the open file, including
|
||||
read-only access. Hardlink and symlink tests exercise identity rather than path
|
||||
string equality. Creation locks its new file before publishing a non-replacing
|
||||
name. Resource ownership continues through cancellation, result release and
|
||||
blocked teardown until IO actually ceases or the owner process dies.
|
||||
|
||||
Recovery has to account for the lock held by the same host. Opening another
|
||||
descriptor before relinquishing the safely quiescent backend can conflict with
|
||||
that host's own lock. The recovery boundary transfers ownership, validates the
|
||||
expected card identity before mutation and preserves local RAM on failure.
|
||||
The selected path containing a different card is an identity error, not implicit
|
||||
permission to register or load a replacement game record.
|
||||
|
||||
## Deterministic guest progress and asynchronous observation coexist
|
||||
|
||||
The headless owner polls native IO between commands. Completion and deadlines
|
||||
can become observable while guest PC, stack, tick and frame remain unchanged.
|
||||
Driving IO does not require inventing game frames or restarting initialization.
|
||||
|
||||
Two integration details were exposed by the first real memcard frame. A
|
||||
controlled bootstrap slice can consume the runtime's step marker before a logical
|
||||
frame closes; the host retains its requested advancement until the frame or an
|
||||
explicit stop boundary. Also, a host dialog can reuse frame ID zero. Its producer
|
||||
is excluded from canonical game capture, so an initial game frame is neither
|
||||
mistaken for the dialog nor rejected merely for sharing that numeric ID.
|
||||
|
||||
A resident game waiting for external media action is paused rather than
|
||||
terminated. Recovery preserves its continuation and admitted RAM. It does not
|
||||
call bootstrap again. Explicit continuation in RAM uses the existing SO choice
|
||||
and remains distinct from restarting a game with fresh memory.
|
||||
|
||||
## A readback oracle should be unable to save its own answer
|
||||
|
||||
The neutral writer stores bytes 0, 127, 128 and 255 and exposes the guest query
|
||||
SUCCESS through public state inspection. A different process runs a reader with
|
||||
no save or presentation import. It checks each prior byte, traps on a wrong or
|
||||
missing payload and exposes a separate readback result. The entire image remains
|
||||
unchanged by that reader. A further process changes app_version while retaining
|
||||
the same uint32 app_id. Read-only loading into RAM is qualified independently.
|
||||
|
||||
The same process oracle runs through the public dispatcher from another working
|
||||
directory against a real extracted archive produced by the distribution workflow.
|
||||
That establishes something stronger than reopening a native object in one test
|
||||
process or copying target/debug binaries into a directory labeled as an install.
|
||||
Archive, binary, schema and source fingerprints identify the evidence precisely
|
||||
even while the implementation is an uncommitted checkout.
|
||||
|
||||
## Evidence and ownership boundary
|
||||
|
||||
[Qualification evidence](evidence/summary.json) records 1,107 passing workspace
|
||||
tests, 73 passing release tests, strict formatter/clippy checks, and both extracted
|
||||
distribution tests passing. The generic workspace gate has 14 ignored manual or
|
||||
installation tests; the two installation tests were separately run successfully.
|
||||
Execution was qualified on macOS arm64. This is not a physical power-cut,
|
||||
cross-target or storage-latency qualification.
|
||||
|
||||
The runtime delivery prepares a supported contract and its independent evidence.
|
||||
No consumer source, configuration, SDK, workflow or tests were changed or run.
|
||||
Future client/frontend integration uses the published surface and has its own
|
||||
acceptance criteria. Its completion is neither claimed nor required to close
|
||||
this provider work. This boundary prevents a provider plan from absorbing another
|
||||
domain merely because that consumer originally discovered the missing interface.
|
||||
@@ -0,0 +1,6 @@
|
||||
Checking prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
|
||||
Checking prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
|
||||
Checking prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Checking prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
|
||||
Checking prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 5.02s
|
||||
@@ -0,0 +1,44 @@
|
||||
Generated VERSION.txt with version 0.1.0
|
||||
Preparing dist-staging...
|
||||
Preparing dist-staging/stable (existing archives are retained)...
|
||||
building artifacts:
|
||||
prometeu-cli-aarch64-apple-darwin.zip
|
||||
prometeu-cli-aarch64-apple-darwin.zip.sha256
|
||||
prometeu-host-desktop-winit-aarch64-apple-darwin.zip
|
||||
prometeu-host-desktop-winit-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-dummy-boy-aarch64-apple-darwin.zip
|
||||
pbxgen-dummy-boy-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-stress-aarch64-apple-darwin.zip
|
||||
pbxgen-stress-aarch64-apple-darwin.zip.sha256
|
||||
|
||||
building aarch64-apple-darwin target, using cargo profile dist --workspace)
|
||||
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
|
||||
Compiling prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
|
||||
Compiling prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `dist` profile [optimized] target(s) in 39.63s
|
||||
announcing v0.1.0
|
||||
prometeu-cli 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip
|
||||
[bin] prometeu
|
||||
[bin] prometeu-headless
|
||||
[bin] prometeu-runtime
|
||||
[misc] 11a-headless-automation-protocol.md, LICENSE, README.md, headless-protocol
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip.sha256
|
||||
prometeu-host-desktop-winit 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-host-desktop-winit-aarch64-apple-darwin.zip
|
||||
[bin] prometeu-host-desktop-winit
|
||||
[misc] LICENSE, README.md, VERSION.txt
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-host-desktop-winit-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-dummy-boy 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-dummy-boy-aarch64-apple-darwin.zip
|
||||
[bin] pbxgen-dummy-boy
|
||||
[misc] LICENSE, README.md
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-dummy-boy-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-stress 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-stress-aarch64-apple-darwin.zip
|
||||
[bin] pbxgen-stress
|
||||
[misc] LICENSE, README.md
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-stress-aarch64-apple-darwin.zip.sha256
|
||||
Copying target/distrib content to dist-staging/stable...
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# Historical baseline investigation
|
||||
|
||||
These files record the diagnosis at revision `dcf6561ea73446e0a3e1cf1c73eda20923b38df0`, before the public memcard interface and exclusive backend locking were implemented. The probe intentionally tests the old behavior and is not a current conformance runner. Current qualification, commands, artifact fingerprints and limits are recorded in [the provider evidence summary](../summary.json).
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
root = Path.cwd()
|
||||
scratch = Path(tempfile.mkdtemp(prefix="runtime-memcard-review-"))
|
||||
source = scratch / "image_access.rs"
|
||||
source.write_text(r'''
|
||||
use prometeu_drivers::memcard::FileMemcard;
|
||||
use prometeu_hal::memcard::MemcardIoError;
|
||||
use prometeu_system::memcard::{image::IMAGE_BYTES, transaction::Card};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
let path = std::path::Path::new(&args[1]);
|
||||
if args.get(2).is_some() {
|
||||
let second = FileMemcard::open(path, false)
|
||||
.map_err(|e| format!("{e:?}"))
|
||||
.and_then(|io| Card::mount(Box::new(io)).map_err(|e| format!("{e:?}")));
|
||||
match second {
|
||||
Ok(card) => {
|
||||
println!("second_process_rw_mount_accepted");
|
||||
drop(card);
|
||||
}
|
||||
Err(error) => println!("second_process_rw_mount_rejected:{error}"),
|
||||
}
|
||||
return;
|
||||
}
|
||||
let io = FileMemcard::create(path, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
}).expect("create private probe image");
|
||||
let first_card = Card::mount(Box::new(io)).expect("first mount");
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.arg(path).arg("child").output().expect("child process");
|
||||
assert!(output.status.success());
|
||||
print!("{}", String::from_utf8(output.stdout).unwrap());
|
||||
drop(first_card);
|
||||
}
|
||||
''')
|
||||
binary = scratch / "image-access"
|
||||
command = ["rustc", "--edition=2024", str(source), "-o", str(binary),
|
||||
"-L", "dependency=" + str(root / "target/debug/deps")]
|
||||
for crate in ("prometeu_drivers", "prometeu_hal", "prometeu_system"):
|
||||
rlib = max((root / "target/debug/deps").glob("lib" + crate + "-*.rlib"),
|
||||
key=lambda p: p.stat().st_mtime_ns)
|
||||
command += ["--extern", crate + "=" + str(rlib)]
|
||||
subprocess.run(command, check=True, capture_output=True, text=True)
|
||||
access = subprocess.run([str(binary), str(scratch / "probe.pmc")],
|
||||
check=True, capture_output=True, text=True)
|
||||
|
||||
process = subprocess.Popen([str(root / "target/debug/prometeu"), "headless", "--stdio"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
hello = json.loads(process.stdout.readline())
|
||||
def request(identity, command, params):
|
||||
process.stdin.write(json.dumps({"requestId": identity, "command": command, "params": params}) + "\n")
|
||||
process.stdin.flush()
|
||||
return json.loads(process.stdout.readline())
|
||||
required = request("probe-capability", "initialize", {
|
||||
"protocolVersion": {"major": 1, "minor": 0}, "requiredCapabilities": ["memcard"]})
|
||||
initialized = request("init", "initialize", {
|
||||
"protocolVersion": {"major": 1, "minor": 0}, "requiredCapabilities": []})
|
||||
invalid = request("probe-field", "boot", {"path": str(scratch), "memcard": {}})
|
||||
state = request("state", "get_state", {})
|
||||
shutdown = request("stop", "shutdown", {})
|
||||
process.stdin.close()
|
||||
process.wait(timeout=10)
|
||||
assert process.returncode == 0
|
||||
assert required["error"]["code"] == "unsupported_capability"
|
||||
assert invalid["error"]["code"] == "invalid_params"
|
||||
assert shutdown["result"] == {"closed": True}
|
||||
report = {
|
||||
"runtime_revision": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
|
||||
"scope": "read-only diagnosis using checkout debug binaries and isolated disposable image; no installed-process persistence qualification",
|
||||
"scratch_directory": str(scratch),
|
||||
"file_access_probe": {
|
||||
"backend": "FileMemcard + Card::mount on a valid freshly created image",
|
||||
"first_process_holds_rw_card": True,
|
||||
"second_process_result": access.stdout.strip(),
|
||||
"payload_writes": False,
|
||||
},
|
||||
"wire_probe": {
|
||||
"capabilities": hello["capabilities"],
|
||||
"required_capability_memcard": required["error"],
|
||||
"unknown_boot_field_memcard": invalid["error"],
|
||||
"get_state_fields": sorted(state["result"]),
|
||||
"shutdown": shutdown["result"],
|
||||
"note": "The memcard capability/field names are intentionally unsupported test input, not a proposed public contract.",
|
||||
},
|
||||
}
|
||||
report_path = scratch / "summary.json"
|
||||
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report, indent=2))
|
||||
print("report_path=" + str(report_path))
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"runtime_revision": "dcf6561ea73446e0a3e1cf1c73eda20923b38df0",
|
||||
"scope": "read-only diagnosis using checkout debug binaries and isolated disposable image; no installed-process persistence qualification",
|
||||
"scratch_directory": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/runtime-memcard-review-qa13v648",
|
||||
"file_access_probe": {
|
||||
"backend": "FileMemcard + Card::mount on a valid freshly created image",
|
||||
"first_process_holds_rw_card": true,
|
||||
"second_process_result": "second_process_rw_mount_accepted",
|
||||
"payload_writes": false
|
||||
},
|
||||
"wire_probe": {
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"cancel",
|
||||
"shutdown"
|
||||
],
|
||||
"required_capability_memcard": {
|
||||
"code": "unsupported_capability",
|
||||
"details": {},
|
||||
"message": "required capability unavailable"
|
||||
},
|
||||
"unknown_boot_field_memcard": {
|
||||
"code": "invalid_params",
|
||||
"details": {},
|
||||
"message": "unknown field `memcard`, expected `path`"
|
||||
},
|
||||
"get_state_fields": [
|
||||
"appId",
|
||||
"logicalFrameIndex",
|
||||
"pc",
|
||||
"stackTop",
|
||||
"status",
|
||||
"tickIndex"
|
||||
],
|
||||
"shutdown": {
|
||||
"closed": true
|
||||
},
|
||||
"note": "The memcard capability/field names are intentionally unsupported test input, not a proposed public contract."
|
||||
},
|
||||
"date": "2026-10-29",
|
||||
"platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O",
|
||||
"studio_revision": "3a3417eb44c2e99ca183ce6f3fbbfff738b70f87",
|
||||
"reproduction": [
|
||||
"cargo test -p prometeu-cli --test automation_process -- --test-threads=1",
|
||||
"python3 discussion/workflow/agendas/AGD-0071-evidence/review_probe.py"
|
||||
],
|
||||
"automation_process_tests": {
|
||||
"passed": 12,
|
||||
"failed": 0,
|
||||
"ignored": 1,
|
||||
"ignored_test": "packaged_installation_smoke",
|
||||
"ignored_reason": "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive",
|
||||
"covers_memcard": false
|
||||
},
|
||||
"qualification_limits": [
|
||||
"No Studio Gradle/native memcard suite was rerun; its summary was inspected as existing evidence.",
|
||||
"No configured installed-runtime memcard persistence test was performed.",
|
||||
"Two simultaneous valid RW mounts were accepted; no concurrent payload publication was attempted.",
|
||||
"No product code, normative specs or Studio files were modified."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
|
||||
Compiling prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Compiling prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
|
||||
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 6.37s
|
||||
Running tests/automation_process.rs (target/debug/deps/automation_process-018fadef87e61183)
|
||||
|
||||
running 2 tests
|
||||
test memcard_process::packaged_memcard_process_persistence ... ok
|
||||
test packaged_installation_smoke ... ok
|
||||
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 20 filtered out; finished in 1.27s
|
||||
@@ -0,0 +1,140 @@
|
||||
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
|
||||
Compiling prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Compiling prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
|
||||
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `release` profile [optimized] target(s) in 39.83s
|
||||
Running unittests src/lib.rs (target/release/deps/prometeu_cli-a2a569acb4d2123a)
|
||||
|
||||
running 0 tests
|
||||
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
|
||||
Running unittests src/main.rs (target/release/deps/prometeu-233bd0c6f7dfd1c0)
|
||||
|
||||
running 4 tests
|
||||
test tests::child_exit_code_preserves_non_zero_one ... ok
|
||||
test tests::child_exit_code_preserves_non_zero_other ... ok
|
||||
test tests::child_exit_code_preserves_zero ... ok
|
||||
test tests::child_exit_code_rejects_status_without_numeric_code ... ok
|
||||
|
||||
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
|
||||
Running unittests src/bin/prometeu-headless.rs (target/release/deps/prometeu_headless-891734b93133c22e)
|
||||
|
||||
running 0 tests
|
||||
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
|
||||
Running unittests src/bin/prometeu-runtime.rs (target/release/deps/prometeu_runtime-2d42636990523667)
|
||||
|
||||
running 0 tests
|
||||
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
|
||||
Running tests/automation_process.rs (target/release/deps/automation_process-48ae7cde6854c255)
|
||||
|
||||
running 22 tests
|
||||
test malformed_fragmented_and_oversized_commands_do_not_desynchronize ... ok
|
||||
test handshake_versions_capabilities_and_limits_are_explicit ... ok
|
||||
test conflicting_work_is_rejected_and_cancellation_reports_partial_progress ... ok
|
||||
test faults_and_boot_failures_are_structured_not_log_parsing ... ok
|
||||
test lifecycle_and_capture_match_the_in_process_canonical_oracle ... ok
|
||||
test idle_eof_and_truncated_eof_close_the_process ... ok
|
||||
test dispatcher_works_from_a_relocated_installation_and_other_cwd ... ok
|
||||
test memcard_process::packaged_memcard_process_persistence ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive
|
||||
test independent_processes_match_pixels_ids_state_and_fault ... ok
|
||||
test packaged_installation_smoke ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive
|
||||
test memcard_process::desktop_dispatch_forwards_explicit_media_without_interpreting_player_policy ... ok
|
||||
test memcard_process::memcard_creation_race_and_process_death_release_real_ownership ... ok
|
||||
test memcard_process::memcard_access_denial_is_typed_and_does_not_create_or_modify_media ... ok
|
||||
test memcard_process::memcard_media_errors_and_negotiation_never_select_a_fallback ... ok
|
||||
test memcard_process::memcard_dirty_refusal_retains_channel_and_explicit_ram_has_no_save ... ok
|
||||
test schemas_and_distributed_request_fixtures_are_consistent ... ok
|
||||
test memcard_process::memcard_idle_observation_never_advances_guest_counters ... ok
|
||||
test shutdown_and_eof_interrupt_active_work_without_resuming_it ... ok
|
||||
test missing_binary_and_invalid_cli_limits_fail_explicitly ... ok
|
||||
test memcard_process::memcard_process_ownership_covers_aliases_readers_and_release ... ok
|
||||
test partial_guest_fault_and_host_watchdog_are_distinct_outcomes ... ok
|
||||
test memcard_process::memcard_public_distinct_process_save_readback_and_version_identity ... ok
|
||||
|
||||
test result: ok. 20 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.66s
|
||||
|
||||
Running tests/registry_fault_schema.rs (target/release/deps/registry_fault_schema-2274560704287ef1)
|
||||
|
||||
running 2 tests
|
||||
test published_load_schema_requires_tag_context_and_the_matching_init_payload ... ok
|
||||
test published_schema_accepts_structured_resource_fields_and_rejects_unknown_or_negative_values ... ok
|
||||
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
|
||||
|
||||
Running unittests src/lib.rs (target/release/deps/prometeu_host_headless-751195d1585cd278)
|
||||
|
||||
running 13 tests
|
||||
test automation::tests::bounded_lines_accept_fragmentation_and_recover_after_oversize ... ok
|
||||
test automation::tests::response_limit_counts_the_complete_envelope_and_keeps_correlation ... ok
|
||||
test automation::tests::input_snapshot_is_replacement_and_rejects_unknown_fields ... ok
|
||||
test automation::tests::distributed_request_fixtures_are_accepted_by_the_actual_parser ... ok
|
||||
test automation::wire::fault_tests::resource_trap_wire_preserves_native_fields_and_source_span ... ok
|
||||
test automation::tests::capture_preserves_independent_ids_and_excludes_padding_without_channel_loss ... ok
|
||||
test automation::wire::fault_tests::load_failure_wire_uses_shared_structured_serializer_and_no_runtime_pc ... ok
|
||||
test automation::wire::fault_tests::executed_closure_quota_refusal_reaches_wire_with_machine_fields ... ok
|
||||
test automation::wire::fault_tests::active_host_native_type_fault_preserves_wire_machine_fields ... ok
|
||||
test host::tests::termination_during_frame_advance_clears_host_step_control ... ok
|
||||
test host::memcard::tests::explicit_continue_in_ram_preserves_dirty_snapshot_and_uses_no_new_boot ... ok
|
||||
test host::memcard::tests::same_media_recovery_rejects_replacement_and_preserves_ram_continuation ... ok
|
||||
test host::memcard::tests::unceased_io_retains_lock_and_terminal_result_survives_late_return_and_reconcile ... ok
|
||||
|
||||
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.09s
|
||||
|
||||
Running tests/deterministic_control.rs (target/release/deps/deterministic_control-98e9b0ea3dcb6c52)
|
||||
|
||||
running 25 tests
|
||||
test headless_source_has_no_timing_wait_or_interactive_backend_dependency ... ok
|
||||
test lifecycle_state_and_preconditions_are_structural ... ok
|
||||
test instruction_step_fault_remains_structured ... ok
|
||||
test batch_stops_early_on_fault_and_reports_partial_progress ... ok
|
||||
test end_of_rom_completes_a_logical_frame ... ok
|
||||
test advance_after_reset_reports_termination_without_ticking ... ok
|
||||
test audio_play_does_not_need_a_device ... ok
|
||||
test clear_input_drops_right ... ok
|
||||
test injected_civil_clock_remains_the_runtime_source_across_lifecycle ... ok
|
||||
test normalized_touch_edges_and_coordinates_use_the_same_input_surface ... ok
|
||||
test one_frame_returns_and_captures_the_exact_published_frame ... ok
|
||||
test normalized_button_press_hold_release_and_clear_are_observable ... ok
|
||||
test right_hold_then_release_changes_pixels ... ok
|
||||
test step_does_not_complete_a_logical_frame ... ok
|
||||
test controlled_civil_time_is_independent_of_frames_pause_and_reset ... ok
|
||||
test one_logical_frame_may_span_multiple_internal_ticks ... ok
|
||||
test trap_is_structured ... ok
|
||||
test stepping_frame_sync_is_not_a_fault_or_completed_runtime_frame ... ok
|
||||
test vm_init_failure_is_returned_as_structured_boot_failure ... ok
|
||||
test zero_frames_is_an_explicit_noop ... ok
|
||||
test reset_matches_fresh_host ... ok
|
||||
test two_runs_match_oracle ... ok
|
||||
test three_hundred_frames_complete_without_realtime_pacing ... ok
|
||||
test outer_frame_limit_is_a_host_error_and_finishes_paused ... ok
|
||||
test audio_controls_quota_and_multiple_frames_are_device_independent ... ok
|
||||
|
||||
test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.18s
|
||||
|
||||
Running tests/input_queries.rs (target/release/deps/input_queries-2ee1672fd0295c9d)
|
||||
|
||||
running 4 tests
|
||||
test catalogue_has_exact_names_ids_signatures_and_no_endpoint_aliases ... ok
|
||||
test every_known_query_faults_when_unavailable_and_rejects_arguments ... ok
|
||||
test vm_queries_charge_one_cycle_each_and_allocate_no_guest_objects ... ok
|
||||
test every_button_uses_its_own_snapshot_and_queries_do_not_advance_frames ... ok
|
||||
|
||||
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
|
||||
Running tests/typed_runtime.rs (target/release/deps/typed_runtime-e31573f60bd59e2a)
|
||||
|
||||
running 5 tests
|
||||
test typed_native_argument_fault_inside_callback_reaches_active_host ... ok
|
||||
test active_host_preserves_removed_opcode_load_context_and_null_fn_trap ... ok
|
||||
test sync_in_callee_or_closure_resumes_next_pc_with_locals_and_init_once ... ok
|
||||
test budget_exhaustion_inside_fn_keeps_the_same_open_logical_frame ... ok
|
||||
test regenerated_cartridges_run_six_complete_frames_on_production_host ... ok
|
||||
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.07s
|
||||
@@ -0,0 +1,157 @@
|
||||
{
|
||||
"date": "2026-10-30",
|
||||
"scope": "runtime/host provider readiness only; no consumer modifications/builds/tests/configuration updates",
|
||||
"baseline_revision": "dcf6561ea73446e0a3e1cf1c73eda20923b38df0",
|
||||
"working_tree": "uncommitted implementation; identified by per-file SHA256 and combined source fingerprint",
|
||||
"source_files_sha256": {
|
||||
"crates/console/prometeu-drivers/src/memcard.rs": "cc0326c89033cca97d1798e7725f2bf52115c8592a12dab39146c9d3dcb19769",
|
||||
"crates/console/prometeu-firmware/src/firmware/firmware_step_load_cartridge.rs": "3177c16ab016d45424b54e9b3bbf1746f9113db8ec607a2819cabc412202a4fb",
|
||||
"crates/console/prometeu-hal/src/memcard.rs": "263d609d336d6e37b62fa4604d2be5ab98df26c45ec7c611557b0abfb8916bee",
|
||||
"crates/console/prometeu-system/src/os/system_os.rs": "cbca29127df9ca28b6ed84bd5fa3f926b410a34f360c33bfce0456292cf4340b",
|
||||
"crates/console/prometeu-system/src/services/memcard.rs": "a58517232ceef657d005da2f28fbc0cd484398bd407b2340b0d3571d083e53c5",
|
||||
"crates/console/prometeu-system/src/services/memcard/admission.rs": "ecec0b0642da3aba3a38941ce25afdb35dc8d42b15f34d9da6ac9d06f765f741",
|
||||
"crates/console/prometeu-system/src/services/memcard/diagnostics.rs": "99699c14c43090c8eb72624967e96846a99400a5809301a8dcc2564d8164ab61",
|
||||
"crates/console/prometeu-system/src/services/memcard/guest.rs": "507913dc29ed07ab2a4ac6ec93583e935a73e35ec8f16798de0a5b55d392dd98",
|
||||
"crates/console/prometeu-system/src/services/memcard/image.rs": "c4aedb43b050989ef95f8efbd5d0994b23928a16dd49358361ecd96ffed3811d",
|
||||
"crates/console/prometeu-system/src/services/memcard/session.rs": "f6990ddac2f0cd2f2643d4323be6e18eef0e349ea1494c6dfd216cb5e2105d4a",
|
||||
"crates/dev/prometeu-test-support/src/lib.rs": "4cf14e6065e40ec5bc84fdc20f653babee26e1d60c97687b1e68edfda9b1a219",
|
||||
"crates/dev/prometeu-test-support/src/memcard_fixture.rs": "f63fd0c6dff5b862d228709d9160b38ab9edc1a90e62b051eb6540706977bd0f",
|
||||
"crates/dev/prometeu-test-support/src/program.rs": "d6c2f720fb405355ea2d3648a5c08e7fa96f5fc8cfd289be0cfb17f911907696",
|
||||
"crates/host/prometeu-host-headless/src/automation/mod.rs": "7d72c0eddf23b769047812e9a96746380f58dc18d5ef560188999160aee17c68",
|
||||
"crates/host/prometeu-host-headless/src/automation/wire.rs": "0a1e3c786810499857f54d8d1795fded417ed809b17c4a03d1b39941b0d4dd28",
|
||||
"crates/host/prometeu-host-headless/src/host.rs": "fc75f6c9dd842ec241e95f4389935d8edf619ed3c7c5134733d25b6dd58cbb2f",
|
||||
"crates/host/prometeu-host-headless/src/lib.rs": "3b29775d61a26a6098562e2e4e98fba1d43580a36979be43682f44ce5f8655c8",
|
||||
"crates/host/prometeu-host-headless/src/memcard.rs": "a32fcfc9cb30ddf18a2eb848101c34583a215817bf6e185124084a46f22ad329",
|
||||
"crates/host/prometeu-host-headless/src/memcard_tests.rs": "66f566a8291014524a4ef0d5952252adf64d3f8c68b50bd9251f4482664e2f39",
|
||||
"crates/host/prometeu-host-headless/src/resource_qualification_tests.rs": "243f51eadc91c30ef5895d34525574349dbad45ee7b77cb88bee25c7fd2e66a4",
|
||||
"crates/host/prometeu-host-headless/tests/deterministic_control.rs": "5fe3f48575e0fd5f4f2640c76145603baa2571b67ad619de21caadf1ce35aa1b",
|
||||
"crates/tools/prometeu-cli/src/lib.rs": "944840ef6e14400b98cc1dc659c95ba5eb6e7ef8a4cd4d28d37ba70392e7e2d6",
|
||||
"crates/tools/prometeu-cli/src/main.rs": "2c956bc90756e31bc38cd6811933a717b3c49d1f0ab501ed39f5869e6b3d8c92",
|
||||
"crates/tools/prometeu-cli/tests/automation_process.rs": "230dea8a6cabede2e168c35938284903fa41614eaa2619626bb6560a9527640f",
|
||||
"crates/tools/prometeu-cli/tests/support/memcard_process.rs": "0a8581fb129238f39605a6e9485e813e58b639e7a2131e3cf06e9c390cce2bed",
|
||||
"devtools/headless-protocol/invalid-requests.json": "f0f0a9a21735c7f90180e816093a884350c07303ea887ebe89a534fc6c8a7b3a",
|
||||
"devtools/headless-protocol/request.schema.json": "d7e5b39917f0973e0cb697815937e21574bec7f24ebcab8c9a72ca3c05dca553",
|
||||
"devtools/headless-protocol/requests.json": "5821af6fecb51a7b85e502fd27d22e046e140d417982bbb561fd260b9023ddf2",
|
||||
"devtools/headless-protocol/response.schema.json": "0040bb288226eb2f34d4028d8a5f3f8a708d754d51d8f62eaa7e64b0da5c69a8",
|
||||
"docs/specs/runtime/08-save-memory-and-memcard.md": "7ead27a4039a3451909e7319f8624ec37c62602fee4615f6766e4435b0f411d7",
|
||||
"docs/specs/runtime/11a-headless-automation-protocol.md": "526e6aae664ffc5661289150410599fb3494e1a1665ba334fe802b0d69e46313"
|
||||
},
|
||||
"source_fingerprint_sha256": "87474a7172e3e233a9144c97202a40001892ea0e8a6c814b47581b67527c2575",
|
||||
"platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O",
|
||||
"architecture": "arm64",
|
||||
"rustc": "rustc 1.98.1 (48a229cea 2026-09-01)",
|
||||
"cargo": "cargo 1.98.1 (797e8a9bc 2026-08-05)",
|
||||
"cargo_lock_sha256": "cffad9ed62f38a591538abd81dd39270d6022397342c8189f4ac6c7baaa8e795",
|
||||
"protocol": {
|
||||
"major": 1,
|
||||
"minor": 1,
|
||||
"capability": "memcard",
|
||||
"schema_sha256": {
|
||||
"invalid-requests.json": "f0f0a9a21735c7f90180e816093a884350c07303ea887ebe89a534fc6c8a7b3a",
|
||||
"request.schema.json": "d7e5b39917f0973e0cb697815937e21574bec7f24ebcab8c9a72ca3c05dca553",
|
||||
"requests.json": "5821af6fecb51a7b85e502fd27d22e046e140d417982bbb561fd260b9023ddf2",
|
||||
"response.schema.json": "0040bb288226eb2f34d4028d8a5f3f8a708d754d51d8f62eaa7e64b0da5c69a8"
|
||||
}
|
||||
},
|
||||
"checks": {
|
||||
"workspace_all_targets_all_features": {
|
||||
"passed": 1107,
|
||||
"failed": 0,
|
||||
"ignored": 14,
|
||||
"suites": 60
|
||||
},
|
||||
"release_cli_headless": {
|
||||
"passed": 73,
|
||||
"failed": 0,
|
||||
"ignored": 2,
|
||||
"suites": 10
|
||||
},
|
||||
"extracted_distribution": {
|
||||
"passed": 2,
|
||||
"failed": 0,
|
||||
"ignored": 0,
|
||||
"suites": 1
|
||||
},
|
||||
"clippy_all_targets_all_features": "passed; warnings denied",
|
||||
"format": "passed",
|
||||
"git_diff_check": "passed",
|
||||
"docs_workflow_reference_scan": "no matches",
|
||||
"edited_specification_links": "all resolve",
|
||||
"uncertain_installed_media_admission": {
|
||||
"passed": 1,
|
||||
"failed": 0,
|
||||
"ignored": 0,
|
||||
"suites": 1
|
||||
}
|
||||
},
|
||||
"commands": [
|
||||
"cargo test --workspace --all-targets --all-features --no-fail-fast",
|
||||
"cargo test --release -p prometeu-host-headless -p prometeu-cli --lib --tests",
|
||||
"cargo clippy --workspace --all-targets --all-features -- -D warnings",
|
||||
"cargo fmt --all -- --check",
|
||||
"./scripts/local-dist.sh --artifacts local --target aarch64-apple-darwin --allow-dirty",
|
||||
"PROMETEU_PROTOCOL_TEST_INSTALL=<isolated extraction> cargo test -p prometeu-cli --test automation_process packaged_ -- --ignored --test-threads=1"
|
||||
],
|
||||
"distribution": {
|
||||
"builder": "cargo-dist 0.30.3 via existing local-dist workflow",
|
||||
"target": "aarch64-apple-darwin",
|
||||
"profile": "dist (inherits release, LTO)",
|
||||
"archive": "target/distrib/prometeu-cli-aarch64-apple-darwin.zip",
|
||||
"archive_sha256": "a6f66e814e0e9254cc4bba5e4a4307c9ec8a9963f8332f2f64a283a376d93b7c",
|
||||
"extracted_to": "/tmp/pln199-install-0x57zot6",
|
||||
"binary_sha256": {
|
||||
"prometeu": "182e4d9a4d32201c8ad892a11c297de7059dcc0a837660bdd173be44808b9906",
|
||||
"prometeu-headless": "7703190f63844d91fa125ba3a322b5e771db79a282b3cfbb3480eef76422b6ef",
|
||||
"prometeu-runtime": "0e8e692395cedea799b6d555b416e40536dcabf3a98a2061327d2010c478e446"
|
||||
},
|
||||
"included_schemas_and_spec": "byte-identical to current checkout",
|
||||
"qualification_harness_profile": "dev harness invokes only extracted dist executables"
|
||||
},
|
||||
"neutral_fixture": {
|
||||
"producer": "runtime TestProgram / Registry writer / assembler; no frontend input or dependency",
|
||||
"source": "crates/dev/prometeu-test-support/src/memcard_fixture.rs",
|
||||
"source_sha256": "f63fd0c6dff5b862d228709d9160b38ab9edc1a90e62b051eb6540706977bd0f",
|
||||
"save_bytes": [
|
||||
0,
|
||||
127,
|
||||
128,
|
||||
255
|
||||
],
|
||||
"app_id": 4294967295,
|
||||
"versions": [
|
||||
"1",
|
||||
"2"
|
||||
],
|
||||
"oracles": {
|
||||
"101": "guest query SUCCESS",
|
||||
"104": "MEMORY_ONLY, remains dirty",
|
||||
"201": "exact prior readback, reader has no save/presentation import",
|
||||
"301": "dirty RAM, no commit"
|
||||
},
|
||||
"readback_checks": "separate public-dispatcher processes; exact bytes, no retained reader request and unchanged entire image; repeated across app_version and read-only memory-existing"
|
||||
},
|
||||
"additional_qualification": [
|
||||
"minor/capability/schema parsing and 1.0 regression",
|
||||
"dirty shutdown/reset refusal keeps session/channel; explicit discard and memory-only",
|
||||
"missing/corrupt/read-only/access-denied errors, no fallback",
|
||||
"cross-process RW/RO/hardlink/symlink exclusion, non-replacing creation race, actual owner process-death release",
|
||||
"native controlled failures before/inside publication; lock retained with unceased IO; immutable original result and late worker error",
|
||||
"same-card revalidation preserves RAM/continuation/original request; wrong identity rejected; explicit RAM detach",
|
||||
"idle IO observation leaves guest PC/stack/tick/frame unchanged",
|
||||
"desktop dispatcher forwards explicit options without launching a GUI",
|
||||
"uncertain installed media remains write-blocked after session teardown; persistent readmission is refused pending explicit revalidation"
|
||||
],
|
||||
"limits": [
|
||||
"Execution qualified on this macOS arm64 host, not other targets or storage devices.",
|
||||
"No physical power-cut or latency claim.",
|
||||
"14 unrelated/manual tests are ignored by the generic workspace gate; the two packaged tests are separately executed and passed.",
|
||||
"Future frontend/client integration remains external and is not claimed."
|
||||
],
|
||||
"implementation_findings": [
|
||||
"Lifecycle bootstrap can consume a debug step marker before the requested logical frame; headless retains its active advance until frame/stop.",
|
||||
"Host dialogs may reuse FrameId zero; canonical capture excludes their producer.",
|
||||
"Worker return is tracked separately from retained results and presence of a backend after failed reacquisition.",
|
||||
"Ending a session does not clear uncertain publication; installed-media health and admission must preserve the write block."
|
||||
],
|
||||
"historical_investigation": "investigation/summary.json records the earlier baseline diagnosis, not the implemented protocol"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 3.55s
|
||||
Running unittests src/lib.rs (target/debug/deps/prometeu_system-5bd0bf863c9e944e)
|
||||
|
||||
running 1 test
|
||||
test services::memcard::admission::tests::idle_uncertain_media_remains_blocked_before_another_persistent_admission ... ok
|
||||
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 231 filtered out; finished in 0.05s
|
||||
+1492
File diff suppressed because it is too large
Load Diff
+122
@@ -0,0 +1,122 @@
|
||||
---
|
||||
id: LSN-0074
|
||||
ticket: headless-bounded-log-observation
|
||||
title: Native log retention and reader progress
|
||||
created: 2026-11-10
|
||||
tags: [runtime, headless, tooling, logging, retention]
|
||||
---
|
||||
|
||||
## Context and published result
|
||||
|
||||
The runtime exposes native logs through negotiated headless protocol 1.2
|
||||
`log_read` and `get_logs`. This is generic observation over the existing ring and
|
||||
JSONL execution owner. Assertions, test catalogs and verdicts remain consumer
|
||||
semantics. No new guest syscall, execution budget, listener or media policy was
|
||||
introduced, and no Studio files or selected installations were changed.
|
||||
|
||||
Historical source: accepted DEC-0069, executed through PLN-0200 from AGD-0073,
|
||||
after the user's runtime-only authorization. Those workflow files are disposable.
|
||||
The normative contract is [Native log observation](../../../docs/specs/runtime/11a-headless-automation-protocol.md#native-log-observation).
|
||||
This lesson explains the published behavior and its limits.
|
||||
|
||||
## Retention and delivery answer different questions
|
||||
|
||||
A ring must eventually evict old records. That fact alone does not establish
|
||||
that a reader missed any. The protocol therefore exposes two different facts:
|
||||
|
||||
| Observation | Meaning |
|
||||
| --- | --- |
|
||||
| overflow | The process-owned ring has evicted historical records. |
|
||||
| gap | The requested cursor requires history older than the retained oldest record. |
|
||||
|
||||
For retained oldest sequence 100, afterSequence=150 has no gap, and
|
||||
afterSequence=99 can read record 100 without loss. A cursor of 98 or null reports
|
||||
a gap. A reader that consumed records promptly can run beyond the ring's
|
||||
4096-record capacity with overflow=true and gap=false. Rejecting that combination
|
||||
would impose an accidental limit on total run length rather than unread backlog.
|
||||
|
||||
The provider returns every native source in order, without filtering by guest tag.
|
||||
Filtering before cursor validation would hide missing history. Interpretation can
|
||||
select relevant application/tag records after preserving native continuity.
|
||||
|
||||
## An explicit first cursor preserves sequence zero
|
||||
|
||||
An unsigned exclusive cursor cannot express the position before zero. Null is the
|
||||
initial position; zero means zero has already been observed. Both cursor and limit
|
||||
are required parameters. A nonempty page advances to its last returned sequence;
|
||||
an empty page preserves the input cursor. A cursor beyond the stream is rejected
|
||||
instead of silently being treated as caught up.
|
||||
|
||||
Requerying is non-destructive and does not execute the guest. Native uint64
|
||||
identities and elapsed timestamps remain lossless on the wire; elapsed wall time
|
||||
is not a deterministic oracle. The adapter must not route these values through a
|
||||
floating-point number representation.
|
||||
|
||||
## Process identity outlives a VM reset
|
||||
|
||||
Reset preserves SystemOS and its log ring, even though guest frame counters reset.
|
||||
Clearing logs or incrementing an invented reset epoch would contradict the native
|
||||
producer. The stream epoch remains zero and native sequence continues. A new
|
||||
process has a different sessionId and its own sequence zero. Readers bind cursors
|
||||
and deduplication to session/epoch, not frame number or a portable numeric cursor.
|
||||
|
||||
## A complete ring transcript is not a complete producer transcript
|
||||
|
||||
The existing guest logging path stores at most 10 messages per application/frame
|
||||
and at most 256 UTF-8 bytes per message. Excess calls are dropped before obtaining
|
||||
a native sequence; truncation also creates no native gap. Real process qualification
|
||||
demonstrates 12 attempted calls becoming 10 stored messages plus one native warning,
|
||||
while gap and overflow both remain false.
|
||||
|
||||
A structured-event consumer must therefore bound its encoded events and validate
|
||||
its own producer continuity and explicit completion, such as ordinals and final
|
||||
counts. Missing assertions cannot be detected from the native ring sequence alone.
|
||||
Those consumer changes are outside this provider delivery. Increasing guest budgets
|
||||
or adding assertion parsing to the runtime would move the wrong responsibility.
|
||||
|
||||
## Bounded observation requires a page loop
|
||||
|
||||
Negotiate the capability before guest execution. Read after boot, after bounded
|
||||
frame blocks and after completion/failure when available. Consume all pending
|
||||
pages to the observed newest sequence before starting another block, preserving
|
||||
the cursor and original records. Validate session/epoch and gap on every page;
|
||||
deduplicate already observed native sequences. Historical overflow alone is not
|
||||
loss. Never replay advancement automatically after a missing response.
|
||||
|
||||
The advertised frame maximum is an admission ceiling, not a safe polling interval:
|
||||
600 frames at 10 application messages/frame already exceed the ring capacity.
|
||||
System messages also occupy that ring. Polling cannot promise lossless delivery
|
||||
for arbitrary rates or an unbounded block.
|
||||
|
||||
The serialized response limit includes the complete envelope. If a page or one
|
||||
event cannot fit, the provider returns response_too_large without partial records.
|
||||
A smaller page can be retried without draining or executing anything. Shortening
|
||||
an event silently would destroy the consumer's ability to validate its payload.
|
||||
|
||||
## Qualification and boundaries
|
||||
|
||||
The HAL, SystemOS and headless suites passed 380 tests; the CLI process suite
|
||||
passed 25 tests. Three separately selected installation tests passed for native
|
||||
logs, existing production capture and memcard persistence: 408 passing tests in
|
||||
these gates. One existing manual memcard latency qualification remained ignored.
|
||||
The initial process run's three installation skips were subsequently executed.
|
||||
|
||||
Real PBX guest fixtures prove native application records, sequence zero, requery,
|
||||
empty/future cursors, reset continuity, separate processes, byte bounds, unchanged
|
||||
producer limits and more than 4096 cumulative records with timely reads. Process
|
||||
output is checked against the published response schema; typed uint64 maxima and
|
||||
all native source/level variants also have unit coverage.
|
||||
|
||||
The installation checks used an isolated staging directory of debug binaries,
|
||||
invoked through the dispatcher from another working directory. They do not claim
|
||||
a release archive was built or the Studio-selected installation was updated.
|
||||
Consumer helpers, runner, UI, assertions and their end-to-end qualification remain
|
||||
consumer work. See [qualification evidence](evidence/qualification.json), the
|
||||
recorded logs and [wire observations](evidence/wire-observations.json).
|
||||
|
||||
## Implementation references
|
||||
|
||||
- [Native ring](../../../crates/console/prometeu-hal/src/log/log_service.rs).
|
||||
- [Wire serialization and validation](../../../crates/host/prometeu-host-headless/src/automation/wire.rs).
|
||||
- [Negotiation and owner dispatch](../../../crates/host/prometeu-host-headless/src/automation/mod.rs).
|
||||
- [Real process conformance](../../../crates/tools/prometeu-cli/tests/automation_process.rs).
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91s
|
||||
Running tests/automation_process.rs (target/debug/deps/automation_process-018fadef87e61183)
|
||||
|
||||
running 3 tests
|
||||
test packaged_native_log_observation ... ok
|
||||
test packaged_installation_smoke ... ok
|
||||
test memcard_process::packaged_memcard_process_persistence ... ok
|
||||
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 25 filtered out; finished in 1.40s
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 5.59s
|
||||
Running tests/automation_process.rs (target/debug/deps/automation_process-018fadef87e61183)
|
||||
|
||||
running 28 tests
|
||||
test handshake_versions_capabilities_and_limits_are_explicit ... ok
|
||||
test conflicting_work_is_rejected_and_cancellation_reports_partial_progress ... ok
|
||||
test log_observation_preserves_existing_guest_length_and_rate_limits ... ok
|
||||
test faults_and_boot_failures_are_structured_not_log_parsing ... ok
|
||||
test bounded_log_responses_can_be_retried_without_draining ... ok
|
||||
test idle_eof_and_truncated_eof_close_the_process ... ok
|
||||
test malformed_fragmented_and_oversized_commands_do_not_desynchronize ... ok
|
||||
test dispatcher_works_from_a_relocated_installation_and_other_cwd ... ok
|
||||
test log_read_requires_explicit_capability_and_minor_two ... ok
|
||||
test lifecycle_and_capture_match_the_in_process_canonical_oracle ... ok
|
||||
test memcard_process::packaged_memcard_process_persistence ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive
|
||||
test memcard_process::memcard_media_errors_and_negotiation_never_select_a_fallback ... ok
|
||||
test memcard_process::memcard_creation_race_and_process_death_release_real_ownership ... ok
|
||||
test packaged_installation_smoke ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive
|
||||
test packaged_native_log_observation ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an isolated installation
|
||||
test native_log_pages_are_read_only_replayable_and_survive_reset ... ok
|
||||
test independent_processes_match_pixels_ids_state_and_fault ... ok
|
||||
test shutdown_and_eof_interrupt_active_work_without_resuming_it ... ok
|
||||
test schemas_and_distributed_request_fixtures_are_consistent ... ok
|
||||
test memcard_process::memcard_dirty_refusal_retains_channel_and_explicit_ram_has_no_save ... ok
|
||||
test memcard_process::memcard_access_denial_is_typed_and_does_not_create_or_modify_media ... ok
|
||||
test memcard_process::memcard_idle_observation_never_advances_guest_counters ... ok
|
||||
test missing_binary_and_invalid_cli_limits_fail_explicitly ... ok
|
||||
test memcard_process::memcard_process_ownership_covers_aliases_readers_and_release ... ok
|
||||
test timely_readers_outlive_ring_capacity_while_stale_cursors_report_gaps ... ok
|
||||
test memcard_process::memcard_public_distinct_process_save_readback_and_version_identity ... ok
|
||||
test memcard_process::desktop_dispatch_forwards_explicit_media_without_interpreting_player_policy ... ok
|
||||
test partial_guest_fault_and_host_watchdog_are_distinct_outcomes ... ok
|
||||
|
||||
test result: ok. 25 passed; 0 failed; 3 ignored; 0 measured; 0 filtered out; finished in 1.62s
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"scope": "runtime provider only; Studio untouched",
|
||||
"sourceRevision": "09d8778f046a2819c50ac786bfb50e958ef5af61",
|
||||
"gates": [
|
||||
{
|
||||
"command": "cargo test -p prometeu-hal -p prometeu-system -p prometeu-host-headless",
|
||||
"exitCode": 0,
|
||||
"passed": 380,
|
||||
"failed": 0,
|
||||
"ignored": 1,
|
||||
"logSha256": "c959ce94316ca9c953e3f337da1bdb0d02c5308c75dfeec2b2a803b1ee38c282",
|
||||
"rawLogSha256": "e80d2df6721b75a196c90cb0b3d56bf6d8dced951f55d7cf7f41758cc85bb987"
|
||||
},
|
||||
{
|
||||
"command": "cargo test -p prometeu-cli --test automation_process",
|
||||
"exitCode": 0,
|
||||
"passed": 25,
|
||||
"failed": 0,
|
||||
"ignored": 3,
|
||||
"logSha256": "dd69cb68e40660a5a349bc32397fd0c632517a4654a2d20948cad48cbb4d2532",
|
||||
"rawLogSha256": "7cad6b59819348150867f6d8013958ecc189b3d79c6bbdea3970d1ffdb171ad0"
|
||||
},
|
||||
{
|
||||
"command": "PROMETEU_PROTOCOL_TEST_INSTALL=<isolated debug staging> cargo test -p prometeu-cli --test automation_process packaged_ -- --ignored",
|
||||
"exitCode": 0,
|
||||
"passed": 3,
|
||||
"failed": 0,
|
||||
"ignored": 0,
|
||||
"logSha256": "4900e90b07e68268084b674c05b5959a1c8adef86710582c5dd35f86fa3f8175",
|
||||
"rawLogSha256": "9511b19fe51b1776e83990737858e2e5df3971023c514cc89bd5b7056a36b78e"
|
||||
}
|
||||
],
|
||||
"passingTests": 408,
|
||||
"remainingIgnored": "One pre-existing manual memcard file-host latency qualification. The three installation cases skipped in process-tests were run in packaged-tests.",
|
||||
"installation": {
|
||||
"installation": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/prometeu-log-read-58e3d38i",
|
||||
"profile": "debug",
|
||||
"kind": "isolated local staging; no release archive or selected installation update",
|
||||
"sha256": {
|
||||
"prometeu": "f35eeea1a13b48c382b108a7f516bc4205d635f6a1698e98d2b0acb12df49e58",
|
||||
"prometeu-runtime": "75e2a2c56d6a00d94bf265d4d0ed507d869e954ebcb26f9711c332a3a6cb5874",
|
||||
"prometeu-headless": "dce18f2d753c227e291fba41b761df0b6d04155d9fba44f4faed81d308b38212"
|
||||
}
|
||||
},
|
||||
"checks": {
|
||||
"cargoFmt": "passed",
|
||||
"gitDiffCheck": "passed",
|
||||
"discussionValidate": "validation passed after housekeeping",
|
||||
"headlessSpecLinks": "passed",
|
||||
"publishedWorkflowReferences": "none in docs/",
|
||||
"lessonLinks": "passed"
|
||||
},
|
||||
"sourceSha256": {
|
||||
"crates/console/prometeu-hal/src/log/log_service.rs": "80b689cc133da4dd52a34834012f12c9ce15892eb109ea7ddc71392faa6cc8dd",
|
||||
"crates/console/prometeu-system/src/os/system_os.rs": "50d5f71f55b4c40b3ec959aacd91df587f2ffa4cc4f183b1c3343589fabb983a",
|
||||
"crates/host/prometeu-host-headless/src/automation/mod.rs": "e1107aefc12a5fbebd6d59fdae4e642f2844eada4205c9317589a9cbd45fcba6",
|
||||
"crates/host/prometeu-host-headless/src/automation/wire.rs": "b779f4d71a472d6bca6008bb217a568c9a7ac5ee9b2b388ed3c30479c85cdafa",
|
||||
"crates/host/prometeu-host-headless/src/host.rs": "5459b51906cf43342c64ee2ac429d1ccd6274da9418916f5be77a9062c1b0862",
|
||||
"crates/tools/prometeu-cli/tests/automation_process.rs": "454d791c6afa24d117715bdf69f9c8f5c7da89349fd598518721db40fbd65966",
|
||||
"devtools/headless-protocol/invalid-requests.json": "57b409c7db95acd8ee66373806497cc35a68c9141265b6d9781692d0a17aea4b",
|
||||
"devtools/headless-protocol/request.schema.json": "554960a1c6c1304da32753937b899b51ac658cae4b9d96927f5a384325ce2ae2",
|
||||
"devtools/headless-protocol/requests.json": "23307436be7a943e1b3565533d79ac5af8d985f7983690cfcfb5466188d0cb48",
|
||||
"devtools/headless-protocol/response.schema.json": "7a8a0fe70a6864203b771e0564dc4227b768213d2368c5b162c892c55c5e186b",
|
||||
"docs/specs/runtime/11a-headless-automation-protocol.md": "5c9520ba8db26f9c4529a8ad236fb94778b05edd495666ebba8b00fec468110c"
|
||||
},
|
||||
"limits": [
|
||||
"No release archive built or selected installation replaced.",
|
||||
"No Studio helpers, runner, UI or consumer end-to-end qualification performed.",
|
||||
"Guest pre-insertion logging limits remain unchanged; native continuity cannot prove producer completeness."
|
||||
],
|
||||
"commitsCreated": 0,
|
||||
"logNormalization": "Stored logs omit trailing blank lines; rawLogSha256 identifies the original captured output."
|
||||
}
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
Compiling prometeu-hal v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-hal)
|
||||
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 4.80s
|
||||
Running unittests src/lib.rs (target/debug/deps/prometeu_hal-372ad163668682c6)
|
||||
|
||||
running 99 tests
|
||||
test cartridge_loader::tests::load_with_asset_capability_requires_assets_pa ... ok
|
||||
test cartridge_loader::tests::directory_loader_rejects_oversized_pbx_with_default_limit ... ok
|
||||
test cartridge_loader::tests::load_rejects_legacy_raw_codec_string_in_assets_pa_header ... ok
|
||||
test cartridge_loader::tests::load_rejects_invalid_assets_pa_prelude ... ok
|
||||
test cartridge_loader::tests::load_rejects_preload_with_missing_asset_id ... ok
|
||||
test cartridge_loader::tests::load_rejects_invalid_assets_pa_header_json ... ok
|
||||
test cartridge_loader::tests::load_rejects_unknown_codec_string_in_assets_pa_header ... ok
|
||||
test cartridge_loader::tests::load_rejects_preload_slot_clash_per_bank_type ... ok
|
||||
test cartridge_loader::tests::load_with_all_capability_normalizes_to_all_flags ... ok
|
||||
test cartridge_loader::tests::program_admission_accepts_exact_limit_and_rejects_growth_after_metadata ... ok
|
||||
test cartridge_loader::tests::load_reads_asset_table_and_preload_from_assets_pa_header ... ok
|
||||
test cartridge_loader::tests::program_admission_handles_empty_short_and_interrupted_reads ... ok
|
||||
test cartridge_loader::tests::program_admission_rejects_oversized_metadata_before_reading ... ok
|
||||
test debugger_protocol::tests::test_fault_event_serialization ... ok
|
||||
test debugger_protocol::tests::test_get_state_serialization ... ok
|
||||
test debugger_protocol::tests::test_telemetry_event_serialization ... ok
|
||||
test glyph_bank::tests::glyph_bank_can_materialize_v1_max_palette_count ... ok
|
||||
test glyph_bank::tests::invalid_palette_lookup_is_distinct_from_transparent_color ... ok
|
||||
test cartridge_loader::tests::load_with_duplicate_capabilities_fails ... ok
|
||||
test glyph_bank::tests::glyph_bank_rejects_zero_resident_palettes - should panic ... ok
|
||||
test glyph_bank::tests::new_glyph_bank_uses_single_resident_palette ... ok
|
||||
test host_return::tests::full_native_result_buffer_does_not_invoke_string_allocator ... ok
|
||||
test host_return::tests::native_results_cannot_grow_the_reserved_buffer_or_exceed_the_signature ... ok
|
||||
test log::log_service::tests::page_cursors_preserve_large_unsigned_sequences ... ok
|
||||
test cartridge_loader::tests::load_with_unknown_capability_fails ... ok
|
||||
test host_return::tests::measured_native_encoding_matches_utf8_lossy_hex_and_join_semantics ... ok
|
||||
test log::log_service::tests::pages_preserve_zero_requery_and_retained_bounds ... ok
|
||||
test log::log_service::tests::test_get_after ... ok
|
||||
test cartridge_loader::tests::load_with_multiple_capabilities_combines_flags ... ok
|
||||
test log::log_service::tests::test_get_recent ... ok
|
||||
test log::log_service::tests::test_ring_buffer_capacity ... ok
|
||||
test cartridge_loader::tests::load_with_none_capability_keeps_zero_flags ... ok
|
||||
test cartridge_loader::tests::load_with_legacy_input_capability_fails ... ok
|
||||
test owned_frame::tests::checked_constructor_rejects_empty_dimensions ... ok
|
||||
test owned_frame::tests::checked_constructor_rejects_short_pixel_buffer ... ok
|
||||
test cartridge_loader::tests::load_without_capabilities_defaults_to_none ... ok
|
||||
test owned_frame::tests::checked_constructor_rejects_stride_smaller_than_width ... ok
|
||||
test owned_frame::tests::owned_rgba8888_frame_preserves_metadata_and_pixels ... ok
|
||||
test cartridge_loader::tests::load_with_single_capability_normalizes_to_flag ... ok
|
||||
test owned_frame::tests::row_returns_visible_width_without_stride_padding ... ok
|
||||
test platform::tests::core_platform_facades_are_object_safe ... ok
|
||||
test platform::tests::render_submit_error_is_typed_and_debuggable ... ok
|
||||
test render_resources::tests::missing_resources_return_none ... ok
|
||||
test render_resources::tests::reads_resident_resources_by_id ... ok
|
||||
test render_submission::tests::closed_submission_owns_command_payload ... ok
|
||||
test cartridge_loader::tests::load_without_asset_capability_accepts_missing_assets_pa ... ok
|
||||
test render_submission::tests::coherence_check_rejects_mismatched_envelope ... ok
|
||||
test render_submission::tests::constructors_pin_app_mode_to_packet_kind ... ok
|
||||
test render_submission::tests::frame_id_advances_monotonically_with_wrapping_arithmetic ... ok
|
||||
test render_submission::tests::ownership_can_be_stamped_by_runtime ... ok
|
||||
test render_worker::tests::render_worker_error_is_copy_equatable_and_debuggable ... ok
|
||||
test render_worker::tests::render_worker_telemetry_defaults_to_zero ... ok
|
||||
test render_worker::tests::render_worker_telemetry_records_counters_and_frame_ids ... ok
|
||||
test scene_bank::tests::scene_bank_owns_exactly_four_layers ... ok
|
||||
test scene_layer::tests::scene_layer_preserves_parallax_factor_and_tilemap_ownership ... ok
|
||||
test scene_viewport_cache::tests::cache_entry_fields_are_derived_from_scene_tiles ... ok
|
||||
test scene_viewport_cache::tests::column_refresh_only_updates_the_requested_column ... ok
|
||||
test scene_viewport_cache::tests::corner_style_region_update_does_not_touch_outside_tiles ... ok
|
||||
test scene_viewport_cache::tests::layer_cache_wraps_ring_origin_for_negative_and_large_movements ... ok
|
||||
test scene_viewport_cache::tests::layer_cache_wraps_ring_origin_under_window_movement ... ok
|
||||
test scene_viewport_cache::tests::line_refresh_only_updates_the_requested_line ... ok
|
||||
test scene_viewport_cache::tests::materialization_populates_all_four_layers ... ok
|
||||
test scene_viewport_cache::tests::move_window_to_matches_incremental_ring_movement ... ok
|
||||
test scene_viewport_cache::tests::out_of_bounds_logical_origins_materialize_default_entries_after_wrap ... ok
|
||||
test scene_viewport_cache::tests::partial_refresh_uses_wrapped_physical_slots_after_window_move ... ok
|
||||
test scene_viewport_cache::tests::refresh_after_wrapped_window_move_materializes_new_logical_tiles ... ok
|
||||
test scene_viewport_cache::tests::region_refresh_only_updates_the_requested_area ... ok
|
||||
test scene_viewport_cache::tests::ringbuffer_preserves_logical_tile_mapping_across_long_mixed_movements ... ok
|
||||
test scene_viewport_cache::tests::scene_swap_invalidation_clears_all_layers ... ok
|
||||
test scene_viewport_resolver::tests::anchors_clamp_near_scene_edges ... ok
|
||||
test scene_viewport_resolver::tests::corner_trigger_converts_to_non_overlapping_region_requests ... ok
|
||||
test scene_viewport_resolver::tests::first_update_initializes_master_and_layer_anchors ... ok
|
||||
test scene_viewport_resolver::tests::reset_scene_requests_full_invalidation_for_all_layers ... ok
|
||||
test scene_viewport_resolver::tests::hysteresis_prevents_small_back_and_forth_refresh_churn ... ok
|
||||
test scene_viewport_resolver::tests::per_layer_copy_requests_follow_parallax_factor ... ok
|
||||
test syscalls::tests::declared_resolver_accepts_mixed_status_first_surface_as_a_single_module ... ok
|
||||
test syscalls::tests::audio_control_abi_and_capability_are_stable ... ok
|
||||
test syscalls::tests::declared_resolver_rejects_abi_mismatch ... ok
|
||||
test syscalls::tests::declared_resolver_rejects_missing_capability ... ok
|
||||
test syscalls::tests::declared_resolver_rejects_unknown_identity ... ok
|
||||
test syscalls::tests::declared_resolver_rejects_legacy_status_first_signatures ... ok
|
||||
test syscalls::tests::declared_resolver_returns_expected_id_for_known_identity ... ok
|
||||
test scene_viewport_resolver::tests::repeated_high_speed_movement_advances_in_tile_steps ... ok
|
||||
test syscalls::tests::resolver_enforces_capabilities ... ok
|
||||
test syscalls::tests::resolver_exposes_split_render_capabilities ... ok
|
||||
test syscalls::tests::resolver_rejects_removed_bank_slot_info_identity ... ok
|
||||
test syscalls::tests::resolver_rejects_removed_legacy_gfx_set_sprite_identity ... ok
|
||||
test syscalls::tests::resolver_rejects_unknown_identity ... ok
|
||||
test syscalls::tests::resolver_rejects_userland_system_run_cart_identity ... ok
|
||||
test syscalls::tests::resolver_returns_expected_id_for_known_identity ... ok
|
||||
test syscalls::tests::memcard_syscall_signatures_are_pinned ... ok
|
||||
test telemetry::tests::snapshot_includes_internal_allocation_evidence ... ok
|
||||
test telemetry::tests::snapshot_maps_render_worker_telemetry ... ok
|
||||
test telemetry::tests::snapshot_uses_persisted_last_frame_logs ... ok
|
||||
test syscalls::tests::status_first_syscall_signatures_are_pinned ... ok
|
||||
test telemetry::tests::test_certifier_violations ... ok
|
||||
test tilemap::tests::tilemap_tile_write_and_read_remain_canonical ... ok
|
||||
test value_snapshot::tests::serialization_contains_values_and_never_exports_native_domain_metadata ... ok
|
||||
test syscalls::tests::every_syscall_has_metadata ... ok
|
||||
|
||||
test result: ok. 99 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
|
||||
Running unittests src/lib.rs (target/debug/deps/prometeu_host_headless-34e7d78b76b56071)
|
||||
|
||||
running 16 tests
|
||||
test automation::tests::bounded_lines_accept_fragmentation_and_recover_after_oversize ... ok
|
||||
test automation::wire::fault_tests::resource_trap_wire_preserves_native_fields_and_source_span ... ok
|
||||
test automation::tests::input_snapshot_is_replacement_and_rejects_unknown_fields ... ok
|
||||
test automation::wire::fault_tests::load_failure_wire_uses_shared_structured_serializer_and_no_runtime_pc ... ok
|
||||
test automation::tests::distributed_request_fixtures_are_accepted_by_the_actual_parser ... ok
|
||||
test automation::wire::log_tests::required_nullable_cursor_and_limit_reject_malformed_values ... ok
|
||||
test automation::wire::log_tests::oversized_native_event_is_an_error_without_partial_result ... ok
|
||||
test automation::tests::response_limit_counts_the_complete_envelope_and_keeps_correlation ... ok
|
||||
test automation::wire::log_tests::native_records_preserve_unsigned_maxima_and_typed_sources ... ok
|
||||
test automation::tests::capture_preserves_independent_ids_and_excludes_padding_without_channel_loss ... ok
|
||||
test automation::wire::fault_tests::executed_closure_quota_refusal_reaches_wire_with_machine_fields ... ok
|
||||
test automation::wire::fault_tests::active_host_native_type_fault_preserves_wire_machine_fields ... ok
|
||||
test host::tests::termination_during_frame_advance_clears_host_step_control ... ok
|
||||
test host::memcard::tests::explicit_continue_in_ram_preserves_dirty_snapshot_and_uses_no_new_boot ... ok
|
||||
test host::memcard::tests::same_media_recovery_rejects_replacement_and_preserves_ram_continuation ... ok
|
||||
test host::memcard::tests::unceased_io_retains_lock_and_terminal_result_survives_late_return_and_reconcile ... ok
|
||||
|
||||
test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.20s
|
||||
|
||||
Running tests/deterministic_control.rs (target/debug/deps/deterministic_control-bf4ec7093c206e5c)
|
||||
|
||||
running 25 tests
|
||||
test headless_source_has_no_timing_wait_or_interactive_backend_dependency ... ok
|
||||
test instruction_step_fault_remains_structured ... ok
|
||||
test lifecycle_state_and_preconditions_are_structural ... ok
|
||||
test audio_play_does_not_need_a_device ... ok
|
||||
test batch_stops_early_on_fault_and_reports_partial_progress ... ok
|
||||
test injected_civil_clock_remains_the_runtime_source_across_lifecycle ... ok
|
||||
test end_of_rom_completes_a_logical_frame ... ok
|
||||
test advance_after_reset_reports_termination_without_ticking ... ok
|
||||
test clear_input_drops_right ... ok
|
||||
test one_frame_returns_and_captures_the_exact_published_frame ... ok
|
||||
test step_does_not_complete_a_logical_frame ... ok
|
||||
test normalized_button_press_hold_release_and_clear_are_observable ... ok
|
||||
test normalized_touch_edges_and_coordinates_use_the_same_input_surface ... ok
|
||||
test stepping_frame_sync_is_not_a_fault_or_completed_runtime_frame ... ok
|
||||
test controlled_civil_time_is_independent_of_frames_pause_and_reset ... ok
|
||||
test trap_is_structured ... ok
|
||||
test zero_frames_is_an_explicit_noop ... ok
|
||||
test vm_init_failure_is_returned_as_structured_boot_failure ... ok
|
||||
test right_hold_then_release_changes_pixels ... ok
|
||||
test two_runs_match_oracle ... ok
|
||||
test one_logical_frame_may_span_multiple_internal_ticks ... ok
|
||||
test reset_matches_fresh_host ... ok
|
||||
test three_hundred_frames_complete_without_realtime_pacing ... ok
|
||||
test outer_frame_limit_is_a_host_error_and_finishes_paused ... ok
|
||||
test audio_controls_quota_and_multiple_frames_are_device_independent ... ok
|
||||
|
||||
test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.30s
|
||||
|
||||
Running tests/input_queries.rs (target/debug/deps/input_queries-95d1e124c4662847)
|
||||
|
||||
running 4 tests
|
||||
test catalogue_has_exact_names_ids_signatures_and_no_endpoint_aliases ... ok
|
||||
test vm_queries_charge_one_cycle_each_and_allocate_no_guest_objects ... ok
|
||||
test every_button_uses_its_own_snapshot_and_queries_do_not_advance_frames ... ok
|
||||
test every_known_query_faults_when_unavailable_and_rejects_arguments ... ok
|
||||
|
||||
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
|
||||
Running tests/typed_runtime.rs (target/debug/deps/typed_runtime-e8b3a2e2b04729f7)
|
||||
|
||||
running 5 tests
|
||||
test typed_native_argument_fault_inside_callback_reaches_active_host ... ok
|
||||
test active_host_preserves_removed_opcode_load_context_and_null_fn_trap ... ok
|
||||
test sync_in_callee_or_closure_resumes_next_pc_with_locals_and_init_once ... ok
|
||||
test regenerated_cartridges_run_six_complete_frames_on_production_host ... ok
|
||||
test budget_exhaustion_inside_fn_keeps_the_same_open_logical_frame ... ok
|
||||
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.65s
|
||||
|
||||
Running unittests src/lib.rs (target/debug/deps/prometeu_system-5bd0bf863c9e944e)
|
||||
|
||||
running 232 tests
|
||||
test crash_report::init_diagnostic::tests::all_load_codes_serialize_to_the_normative_tags ... ok
|
||||
test os::system_os::tests::foreground_stack_starts_at_hub ... ok
|
||||
test crash_report::init_diagnostic::tests::native_abi_and_resource_context_are_machine_fields ... ok
|
||||
test os::system_os::tests::close_task_marks_task_closed_and_process_stopped_without_removing_entities ... ok
|
||||
test os::system_os::tests::game_session_registers_single_resident_game ... ok
|
||||
test crash_report::init_diagnostic::tests::load_tag_and_reference_context_survive_without_fabricating_runtime_pc ... ok
|
||||
test os::system_os::tests::closing_foreground_shell_returns_to_hub ... ok
|
||||
test os::system_os::tests::lifecycle_exposes_process_kind_for_shell_tasks ... ok
|
||||
test os::system_os::tests::crash_task_marks_task_and_process_crashed ... ok
|
||||
test os::system_os::tests::lifecycle_operation_missing_process_returns_typed_error ... ok
|
||||
test os::system_os::tests::lifecycle_operation_missing_task_returns_typed_error ... ok
|
||||
test os::system_os::tests::home_request_notifies_game_before_budget_suspends_it ... ok
|
||||
test os::system_os::tests::native_shell_task_does_not_create_vm_session ... ok
|
||||
test os::system_os::tests::native_shell_foreground_suspends_foreground_resident_game ... ok
|
||||
test os::system_os::tests::resume_task_from_non_suspended_state_returns_invalid_transition ... ok
|
||||
test os::system_os::tests::resume_task_marks_suspended_task_foreground_and_process_running ... ok
|
||||
test os::system_os::tests::same_resident_game_app_reuses_existing_vm_session ... ok
|
||||
test os::system_os::tests::second_foreground_shell_is_rejected ... ok
|
||||
test os::system_os::tests::second_resident_game_is_rejected ... ok
|
||||
test os::system_os::tests::session_cartridge_initialization_returns_typed_error_for_missing_session ... ok
|
||||
test os::system_os::tests::set_foreground_task_marks_task_and_process_running ... ok
|
||||
test os::system_os::tests::shell_foreground_keeps_game_resident_and_marks_it_suspended ... ok
|
||||
test os::system_os::tests::suspend_task_marks_task_and_process_suspended ... ok
|
||||
test os::system_os::tests::terminate_resident_game_closes_task_and_removes_vm_session ... ok
|
||||
test os::system_os::tests::terminate_resident_game_preserves_foreground_shell ... ok
|
||||
test os::system_os::tests::vm_debug_operations_target_foreground_shell_before_resident_game ... ok
|
||||
test os::system_os::tests::vm_game_task_creates_vm_session ... ok
|
||||
test os::system_os::tests::vm_session_creation_returns_typed_error_for_missing_process ... ok
|
||||
test os::system_os::tests::vm_session_creation_returns_typed_error_for_missing_task ... ok
|
||||
test os::system_os::tests::vm_sessions_hold_independent_runtime_state ... ok
|
||||
test os::system_os::tests::vm_shell_foreground_suspends_foreground_resident_game ... ok
|
||||
test os::system_os::tests::vm_shell_load_returns_typed_error_when_foreground_shell_exists ... ok
|
||||
test os::system_os::tests::vm_shell_task_creates_vm_session ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::button_hit_test_excludes_right_and_bottom_edges ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::close_button_click_emits_close_only_in_shell ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::game_row_click_emits_launch_game_action ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::held_pointer_does_not_emit_click_action ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::home_layout_exposes_exactly_two_manual_shell_buttons ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::home_render_omits_suspended_game_kill_control_without_resident_game ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::home_render_produces_shell_ui_packet_commands ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::home_render_shows_suspended_game_kill_control_when_game_is_resident ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::hub_starts_with_home_input_disarmed ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::shell_a_button_click_emits_launch_action ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::resident_game_indicator_uses_only_resident_game_sessions ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::shell_close_button_sits_inside_shell_frame ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::shell_b_button_click_emits_launch_action ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::suspended_game_kill_control_click_emits_kill_action ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::suspended_game_kill_control_truncates_long_titles ... ok
|
||||
test services::async_work::tests::async_work_lane_rejects_submit_after_shutdown ... ok
|
||||
test services::async_work::tests::async_work_lane_shutdown_discards_pending_jobs ... ok
|
||||
test services::foreground::tests::foreground_stack_starts_at_hub ... ok
|
||||
test services::foreground::tests::home_request_moves_resident_game_to_pause_requested ... ok
|
||||
test services::foreground::tests::pause_budget_decrements_before_expiry ... ok
|
||||
test services::async_work::tests::async_work_lane_runs_higher_priority_io_before_assets ... ok
|
||||
test services::async_work::tests::async_work_lane_runs_jobs_in_submission_order ... ok
|
||||
test services::foreground::tests::pause_budget_expiry_suspends_game_and_returns_to_hub ... ok
|
||||
test services::async_work::tests::async_work_lane_has_one_active_job ... ok
|
||||
test services::foreground::tests::resume_request_precedes_game_foreground_restore ... ok
|
||||
test services::foreground::tests::second_resident_game_is_rejected ... ok
|
||||
test services::foreground::tests::setting_game_foreground_registers_resident_game ... ok
|
||||
test services::foreground::tests::shell_foreground_keeps_resident_game ... ok
|
||||
test services::fs::virtual_fs::tests::fs_async_lane_operations_classify_priority_without_public_api_changes ... ok
|
||||
test services::fs::virtual_fs::tests::test_delete_root_is_rejected_before_backend ... ok
|
||||
test services::fs::virtual_fs::tests::test_invalid_paths_never_reach_backend ... ok
|
||||
test services::fs::virtual_fs::tests::test_normalize_path_rejects_parent_traversal ... ok
|
||||
test services::fs::virtual_fs::tests::test_virtual_fs_health ... ok
|
||||
test services::fs::virtual_fs::tests::test_virtual_fs_operations ... ok
|
||||
test services::game_library::tests::switch_target_preserves_resolved_identity ... ok
|
||||
test services::game_library::tests::missing_root_returns_diagnostic_and_no_entries ... ok
|
||||
test services::memcard::image::tests::closed_catalog_rejects_duplicates_and_deep_input ... ok
|
||||
test services::game_library::tests::repository_test_cartridges_include_stress_and_dummy_boy ... ok
|
||||
test services::memcard::image::tests::crc_vectors_and_identity_golden ... ok
|
||||
test services::async_work::tests::async_work_lane_supports_cooperative_cancellation ... ok
|
||||
test services::memcard::image::tests::descriptor_roundtrip_rejects_reserved_and_alias ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::native_shell_profile_close_button_does_not_tick_vm ... ok
|
||||
test services::async_work::step_tests::yielded_asset_resumes_same_job_after_priority_save ... ok
|
||||
test programs::prometeu_hub::prometeu_hub::tests::native_shell_profile_start_close_does_not_tick_vm ... ok
|
||||
test services::memcard::session::tests::clear_and_sparse_writes_do_not_expose_previous_bytes ... ok
|
||||
test services::memcard::session::tests::memory_snapshot_limits_isolation_and_no_fake_durability ... ok
|
||||
test services::memcard::image::tests::maximum_catalog_and_icons_fit_and_preserve_uint64 ... ok
|
||||
test services::memcard::transaction::tests::cancellation_prevents_publication_and_generations_do_not_wrap ... ok
|
||||
test services::memcard::transaction::tests::corrupted_new_payload_recovers_old_map_with_diagnostic ... ok
|
||||
test services::memcard::transaction::tests::async_commit_protects_only_source_and_retains_result_without_occupying_lane ... ok
|
||||
test services::memcard::transaction::tests::deferred_boot_memcard_deadline_stays_timeout ... ok
|
||||
test services::memcard::transaction::tests::boot_commit_waits_for_ready_and_publishes_registration_before_payload ... ok
|
||||
test services::game_library::tests::discovery_samples_once_per_scan_and_preserves_adjustments_and_full_range ... ok
|
||||
test services::memcard::transaction::tests::ending_a_session_releases_a_completed_unconsumed_request ... ok
|
||||
test services::memcard::transaction::tests::full_card_admission_preserves_card_and_memory_only_can_extend_existing_data ... ok
|
||||
test services::memcard::transaction::tests::grow_shrink_removal_and_clean_reassignment ... ok
|
||||
test services::memcard::admission::tests::idle_uncertain_media_remains_blocked_before_another_persistent_admission ... ok
|
||||
test services::memcard::transaction::tests::qualify_file_commits_with_production_asset_decoder ... ignored, manual file-host latency qualification; prints measurements for this host
|
||||
test services::memcard::transaction::tests::quarantine_survives_remount_and_is_never_selected ... ok
|
||||
test services::memcard::transaction::tests::lifecycle_cancellation_is_not_a_watchdog_timeout ... ok
|
||||
test services::memcard::transaction::tests::catalog_cuts_never_publish_partial_registration ... ok
|
||||
test services::game_library::tests::discovery_returns_only_immediate_valid_game_directories ... ok
|
||||
test services::memcard::transaction::tests::reinsertion_retains_ram_and_different_card_requires_explicit_load ... ok
|
||||
test services::process::process_manager::tests::mark_stopped_updates_process_state ... ok
|
||||
test services::process::process_manager::tests::mark_suspended_updates_process_state ... ok
|
||||
test services::process::process_manager::tests::remove_stopped_keeps_running_processes ... ok
|
||||
test services::process::process_manager::tests::spawn_native_shell_creates_running_process ... ok
|
||||
test services::process::process_manager::tests::spawn_vm_game_creates_running_process ... ok
|
||||
test services::process::process_manager::tests::spawn_vm_shell_creates_running_process ... ok
|
||||
test services::process::process_manager::tests::unknown_process_transition_returns_false ... ok
|
||||
test services::task::task_manager::tests::close_foreground_task_clears_foreground ... ok
|
||||
test services::task::task_manager::tests::crashed_foreground_task_clears_foreground ... ok
|
||||
test services::task::task_manager::tests::create_game_task_registers_task ... ok
|
||||
test services::task::task_manager::tests::set_foreground_marks_task_as_foreground ... ok
|
||||
test services::task::task_manager::tests::set_foreground_moves_previous_task_to_background ... ok
|
||||
test services::task::task_manager::tests::set_foreground_unknown_task_returns_false ... ok
|
||||
test services::task::task_manager::tests::suspend_foreground_task_clears_foreground ... ok
|
||||
test services::vm_runtime::async_render_contract_tests::async_render_contract_matrix_rows_have_validation ... ok
|
||||
test services::memcard::transaction::tests::queued_memcard_watchdog_preserves_timeout_and_guest_reason ... ok
|
||||
test services::vm_runtime::async_render_contract_tests::matrix_epoch_stale_discard_and_telemetry_sync_remain_consistent ... ok
|
||||
test services::vm_runtime::async_render_contract_tests::matrix_packet_policy_and_pacing_are_mode_specific ... ok
|
||||
test services::vm_runtime::async_render_contract_tests::matrix_shutdown_failure_and_repeat_are_observable ... ok
|
||||
test services::vm_runtime::async_render_contract_tests::matrix_sync_and_worker_paths_share_latest_wins_handoff_contract ... ok
|
||||
test services::vm_runtime::frame_scheduler::tests::authorizes_one_game_frame_until_completion ... ok
|
||||
test services::vm_runtime::frame_scheduler::tests::completion_is_sequential_without_catch_up_frames ... ok
|
||||
test services::vm_runtime::frame_scheduler::tests::records_logical_frame_overrun_without_advancing_frame_id ... ok
|
||||
test services::vm_runtime::lifecycle::tests::vm_runtime_records_and_drains_delivered_game_lifecycle_events ... ok
|
||||
test services::vm_runtime::render_manager::tests::app_mode_switch_records_noop_transition_placeholder ... ok
|
||||
test services::vm_runtime::render_manager::tests::active_render_policy_follows_app_mode_transition ... ok
|
||||
test services::vm_runtime::render_manager::tests::close_frame_stamps_submission_with_active_ownership ... ok
|
||||
test services::vm_runtime::render_manager::tests::frame_closure_assigns_monotonic_frame_ids ... ok
|
||||
test services::memcard::transaction::tests::blocked_host_memcard_watchdog_preserves_outcome_and_escalation ... ok
|
||||
test services::vm_runtime::render_manager::tests::latest_complete_submission_wins_without_queue_growth ... ok
|
||||
test services::vm_runtime::render_manager::tests::local_render_worker_consumes_latest_game_submission ... ok
|
||||
test services::vm_runtime::render_manager::tests::publish_latest_consumes_pending_but_keeps_observable_last_submission ... ok
|
||||
test services::vm_runtime::render_manager::tests::present_panic_is_reported_without_unwinding_to_vm ... ok
|
||||
test services::vm_runtime::render_manager::tests::publish_latest_discards_stale_epoch_before_present ... ok
|
||||
test services::vm_runtime::render_manager::tests::publish_latest_hands_submission_to_surface ... ok
|
||||
test services::vm_runtime::render_manager::tests::rejects_packet_that_does_not_match_active_app_mode ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_handoff_counts_replacement_before_consume ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_handoff_discards_pending_submission ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_handoff_takes_owned_latest_submission ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_policy_keeps_shell_local_even_when_worker_capability_is_enabled ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_policy_maps_game_to_frame_scheduled_worker_capable ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_policy_maps_shell_to_lifecycle_driven_local_sync ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_policy_resolves_game_worker_only_when_capability_is_enabled ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_telemetry_counts_produced_replaced_consumed_and_presented ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_telemetry_counts_stale_repeat_and_error_hooks ... ok
|
||||
test services::vm_runtime::render_manager::tests::render_telemetry_syncs_to_atomic_telemetry ... ok
|
||||
test services::vm_runtime::render_manager::tests::request_shutdown_discards_pending_submission_without_presenting ... ok
|
||||
test services::vm_runtime::render_manager::tests::stopped_consumer_discards_new_pending_submission_before_present ... ok
|
||||
test services::vm_runtime::render_manager::tests::resume_consumer_allows_presentation_after_shutdown ... ok
|
||||
test services::vm_runtime::render_worker::tests::latest_render_frame_store_is_sink_and_observable_publication_source ... ok
|
||||
test services::vm_runtime::render_manager::tests::transition_render_owner_increments_epoch_for_same_mode_app_swap ... ok
|
||||
test services::vm_runtime::render_worker::tests::render_worker_controller_renders_and_publishes_submission ... ok
|
||||
test services::vm_runtime::render_worker::tests::render_worker_controller_repeats_latest_published_frame_without_rendering ... ok
|
||||
test services::vm_runtime::render_worker::tests::render_worker_controller_discards_stale_frame_before_publish ... ok
|
||||
test services::vm_runtime::render_worker::tests::render_worker_controller_captures_backend_panic_as_typed_failure ... ok
|
||||
test services::vm_runtime::render_worker::tests::render_worker_controller_starts_and_stops_waiting_worker ... ok
|
||||
test services::vm_runtime::render_worker_handoff::tests::render_worker_handoff_is_latest_wins_and_counts_replacements ... ok
|
||||
test services::vm_runtime::render_worker_handoff::tests::render_worker_handoff_takes_owned_submission ... ok
|
||||
test services::vm_runtime::render_worker::tests::runtime_publishes_game_submissions_to_worker_without_waiting_for_render ... ok
|
||||
test services::vm_runtime::render_worker_handoff::tests::render_worker_handoff_wait_take_returns_pending_without_blocking ... ok
|
||||
test services::vm_runtime::render_worker_handoff::tests::render_worker_handoff_wait_returns_shutdown_signal ... ok
|
||||
test services::vm_runtime::render_worker_test_harness::tests::render_worker_harness_builds_game_and_shell_submissions ... ok
|
||||
test services::vm_runtime::render_worker_handoff::tests::render_worker_handoff_waits_for_publish_without_timing_delay ... ok
|
||||
test services::vm_runtime::render_worker_test_harness::tests::render_worker_harness_blocks_and_releases_render_without_timing_delay ... ok
|
||||
test services::vm_runtime::render_worker_test_harness::tests::render_worker_harness_injects_backend_errors ... ok
|
||||
test services::vm_runtime::render_worker_test_harness::tests::render_worker_harness_records_published_owned_frames ... ok
|
||||
test services::vm_runtime::tests::asset_bank::initialize_vm_rejects_removed_bank_slot_info_syscall_identity ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_backlog_promote_unknown_handle_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_cancel_unknown_handle_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::render_worker::tests::render_worker_controller_reports_shutdown_timeout ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_commit_operational_error_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_commit_invalid_transition_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_load_invalid_slot_returns_status_and_zero_handle ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_load_missing_asset_returns_status_and_zero_handle ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_status_unknown_handle_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_target_status_empty_slot_returns_status_first_payload ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_status_first_surface_smoke_across_composer_audio_and_asset ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_bank_info_returns_slot_summary_not_json ... ok
|
||||
test services::memcard::transaction::tests::explicit_revalidation_preserves_exclusions_until_separate_reintegration ... ok
|
||||
test services::vm_runtime::tests::audio_controls::frame_publication_backpressure_abort_and_debug_steps ... ok
|
||||
test services::memcard::transaction::tests::persistent_save_preempts_real_multichunk_asset_decoders ... ok
|
||||
test services::vm_runtime::tests::audio_controls::normal_entry_return_is_a_successful_implicit_audio_frame ... ok
|
||||
test services::vm_runtime::tests::initialize_vm_applies_cartridge_capabilities_before_loader_resolution ... ok
|
||||
test services::vm_runtime::tests::fs_memcard::tick_memcard_boot_is_denied_for_non_game_profile ... ok
|
||||
test services::vm_runtime::tests::initialize_vm_failure_clears_previous_identity_and_handles ... ok
|
||||
test services::vm_runtime::tests::initialize_vm_succeeds_when_cartridge_capabilities_cover_hostcalls ... ok
|
||||
test services::vm_runtime::tests::fs_memcard::tick_memcard_boot_receives_admitted_context_and_precedes_first_frame ... ok
|
||||
test services::vm_runtime::tests::initialize_vm_success_clears_previous_crash_report ... ok
|
||||
test services::vm_runtime::tests::reset_clears_cartridge_scoped_runtime_state ... ok
|
||||
test services::vm_runtime::tests::audio_controls::guest_audio_status_matrix_and_type_traps ... ok
|
||||
test services::vm_runtime::tests::tick_audio_play_missing_asset_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_already_materialized_string_path_records_zero_internal_allocations ... ok
|
||||
test services::vm_runtime::tests::tick_audio_play_sample_operational_error_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_audio_play_type_mismatch_surfaces_trap_not_panic ... ok
|
||||
test services::vm_runtime::tests::tick_audio_play_voice_invalid_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_composer_bind_scene_operational_error_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_composer_emit_sprite_invalid_layer_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_composer_emit_sprite_invalid_palette_returns_bank_invalid ... ok
|
||||
test services::vm_runtime::tests::tick_composer_emit_sprite_invalid_range_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_composer_emit_sprite_type_mismatch_surfaces_trap_not_panic ... ok
|
||||
test services::vm_runtime::tests::tick_composer_emit_sprite_operational_error_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_draw_text_survives_no_scene_frame_path ... ok
|
||||
test services::vm_runtime::tests::audio_controls::guest_play_validates_raw_bank_loop_and_preserves_both_play_forms ... ok
|
||||
test services::vm_runtime::tests::tick_game_profile_rejects_gfxui_shell_surface ... ok
|
||||
test services::vm_runtime::tests::tick_game_submissions_are_immutable_and_latest_complete_wins ... ok
|
||||
test services::vm_runtime::tests::tick_numeric_happy_path_records_zero_internal_allocations ... ok
|
||||
test services::vm_runtime::tests::tick_returns_error_when_vm_ends_slice_with_trap ... ok
|
||||
test services::vm_runtime::tests::tick_shell_profile_closes_gfxui_commands_into_shell_packet ... ok
|
||||
test services::vm_runtime::tests::tick_system_profile_can_use_shared_log_transport ... ok
|
||||
test services::vm_runtime::tests::tick_renders_scene_through_public_composer_syscalls ... ok
|
||||
test services::vm_runtime::tests::tick_renders_bound_eight_pixel_scene_through_frame_composer_path ... ok
|
||||
test services::vm_runtime::tests::tick_system_profile_rejects_bank_game_surface ... ok
|
||||
test services::vm_runtime::tests::tick_system_profile_rejects_composer_game_surface ... ok
|
||||
test services::vm_runtime::tests::asset_bank::tick_asset_cancel_invalid_transition_returns_status_not_crash ... ok
|
||||
test services::vm_runtime::tests::tick_system_profile_rejects_gfx_game_surface ... ok
|
||||
test services::vm_session::tests::creates_vm_shell_session_for_vm_shell_task ... ok
|
||||
test services::vm_runtime::tests::unpatched_hostcall_is_rejected_before_tick ... ok
|
||||
test services::vm_session::tests::creates_vm_game_session_for_vm_game_task ... ok
|
||||
test services::vm_session::tests::finds_resident_game_by_app_id ... ok
|
||||
test services::vm_session::tests::rejects_native_shell_process ... ok
|
||||
test services::vm_session::tests::remove_for_task_removes_only_matching_session ... ok
|
||||
test services::vm_session::tests::session_runtime_state_is_independent_per_session ... ok
|
||||
test services::windows::window_manager::tests::focused_window_belongs_to_task_matches_focused_task_owner ... ok
|
||||
test services::windows::window_manager::tests::focused_window_belongs_to_task_rejects_hub_owner ... ok
|
||||
test services::windows::window_manager::tests::focused_window_belongs_to_task_rejects_other_task_owner ... ok
|
||||
test services::windows::window_manager::tests::focused_window_belongs_to_task_rejects_stale_focus ... ok
|
||||
test services::windows::window_manager::tests::focused_window_belongs_to_task_rejects_overlay_owner ... ok
|
||||
test services::windows::window_manager::tests::focused_window_belongs_to_task_returns_false_without_focus ... ok
|
||||
test services::windows::window_manager::tests::test_window_manager_focus ... ok
|
||||
test services::windows::window_manager::tests::test_window_manager_remove_window ... ok
|
||||
test services::memcard::transaction::tests::cut_every_commit_step_including_sync_that_persists_then_errors ... ok
|
||||
test services::memcard::transaction::tests::file_backend_allocates_full_image_and_reopens_verified_save_without_replacing_files ... ok
|
||||
test services::memcard::transaction::tests::full_pool_rotates_and_empty_keeps_ownership ... ok
|
||||
test services::vm_runtime::tests::audio_controls::guest_quota_is_deterministic_and_resets_on_next_frame ... ok
|
||||
test services::vm_runtime::tests::tick_gfx2d_draw_text_buffers_without_immediate_pixel_mutation_before_frame_close ... ok
|
||||
test services::vm_runtime::tests::tick_gfx2d_clear_buffers_without_immediate_pixel_mutation_before_frame_close ... ok
|
||||
|
||||
test result: ok. 231 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.28s
|
||||
|
||||
Doc-tests prometeu_hal
|
||||
|
||||
running 0 tests
|
||||
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
|
||||
Doc-tests prometeu_host_headless
|
||||
|
||||
running 0 tests
|
||||
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
|
||||
Doc-tests prometeu_system
|
||||
|
||||
running 0 tests
|
||||
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
{
|
||||
"installation": {
|
||||
"installation": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/prometeu-log-read-58e3d38i",
|
||||
"profile": "debug",
|
||||
"kind": "isolated local staging; no release archive or selected installation update",
|
||||
"sha256": {
|
||||
"prometeu": "f35eeea1a13b48c382b108a7f516bc4205d635f6a1698e98d2b0acb12df49e58",
|
||||
"prometeu-runtime": "75e2a2c56d6a00d94bf265d4d0ed507d869e954ebcb26f9711c332a3a6cb5874",
|
||||
"prometeu-headless": "dce18f2d753c227e291fba41b761df0b6d04155d9fba44f4faed81d308b38212"
|
||||
}
|
||||
},
|
||||
"records": [
|
||||
{
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory"
|
||||
],
|
||||
"limits": {
|
||||
"callTimeoutMs": 60000,
|
||||
"handshakeTimeoutMs": 5000,
|
||||
"maxCommandBytes": 65536,
|
||||
"maxFrames": 600,
|
||||
"maxResponseBytes": 33554432,
|
||||
"shutdownTimeoutMs": 5000
|
||||
},
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"runtimeVersion": "0.1.0",
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "hello"
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "init",
|
||||
"command": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"requiredCapabilities": [
|
||||
"log_read"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "init",
|
||||
"result": {
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory"
|
||||
],
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
}
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "before",
|
||||
"command": "get_state",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "before",
|
||||
"result": {
|
||||
"appId": 0,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 0,
|
||||
"stackTop": [],
|
||||
"status": "terminated",
|
||||
"tickIndex": 0
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "logs",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 1
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "logs",
|
||||
"result": {
|
||||
"events": [
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "PrometeuOS starting...",
|
||||
"sequence": 0,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 0
|
||||
}
|
||||
],
|
||||
"gap": false,
|
||||
"logEpoch": 0,
|
||||
"newestSequence": 0,
|
||||
"nextAfterSequence": 0,
|
||||
"oldestSequence": 0,
|
||||
"overflow": false,
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8"
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "after",
|
||||
"command": "get_state",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "after",
|
||||
"result": {
|
||||
"appId": 0,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 0,
|
||||
"stackTop": [],
|
||||
"status": "terminated",
|
||||
"tickIndex": 0
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "reset",
|
||||
"command": "reset",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "reset",
|
||||
"result": {
|
||||
"appId": 0,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 0,
|
||||
"stackTop": [],
|
||||
"status": "terminated",
|
||||
"tickIndex": 0
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "continued",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": 0,
|
||||
"limit": 128
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "continued",
|
||||
"result": {
|
||||
"events": [
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Firmware Reset",
|
||||
"sequence": 1,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 1
|
||||
}
|
||||
],
|
||||
"gap": false,
|
||||
"logEpoch": 0,
|
||||
"newestSequence": 1,
|
||||
"nextAfterSequence": 1,
|
||||
"oldestSequence": 0,
|
||||
"overflow": false,
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8"
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "shutdown",
|
||||
"command": "shutdown",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "shutdown",
|
||||
"result": {
|
||||
"closed": true
|
||||
},
|
||||
"sessionId": "fc44b1adef1a5044fccf5d801fa5f2c8",
|
||||
"type": "response"
|
||||
}
|
||||
}
|
||||
],
|
||||
"readPreservedState": true
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
---
|
||||
id: LSN-0075
|
||||
ticket: rust-toolchain-pin
|
||||
title: One source for the Rust compiler version
|
||||
created: 2026-11-10
|
||||
tags: [tooling, ci]
|
||||
---
|
||||
|
||||
## Published configuration
|
||||
|
||||
Historical source: accepted DEC-0070, implemented through PLN-0201 from AGD-0074.
|
||||
The selected compiler is Rust 1.98.1 in
|
||||
[rust-toolchain.toml](../../../rust-toolchain.toml), with installation instructions
|
||||
in the [README](../../../README.md#requirements). No runtime spec changed.
|
||||
|
||||
## A moving channel does not preserve a tested environment
|
||||
|
||||
`stable` can resolve to different compilers across machines and installation
|
||||
dates. An exact version preserves the compiler used in existing qualifications.
|
||||
Cargo's `rust-version` expresses a minimum and does not replace that selection.
|
||||
|
||||
The [CI workflow](../../../.github/workflows/ci.yml) reads the channel from the
|
||||
toolchain file and passes it explicitly to `rustup toolchain install`, avoiding
|
||||
another version literal to update. Implicit installation encountered cache rename
|
||||
errors during verification; explicit installation recognized the existing compiler
|
||||
and components. The shared provisioner installs formatting, Clippy and coverage
|
||||
components before the quality gate.
|
||||
|
||||
## Evidence and limits
|
||||
|
||||
On macOS aarch64, the numbered toolchain selected rustc/cargo 1.98.1. Workspace
|
||||
formatting and `cargo check --workspace --all-targets --all-features --locked`
|
||||
passed. Explicit installation and CI version extraction also passed. This controls
|
||||
compiler drift; it does not establish the cause or resolution of the original
|
||||
Linux compatibility failure.
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
---
|
||||
id: LSN-0076
|
||||
ticket: headless-memcard-reopen-io-progress
|
||||
title: Native IO progress is not machine progress
|
||||
created: 2026-11-10
|
||||
tags: [headless, memcard, testing, ownership]
|
||||
---
|
||||
|
||||
## Context and published result
|
||||
|
||||
The headless owner now waits for native progress when a successful memcard
|
||||
bootstrap hook is still blocked on its queued or running publication. The wait
|
||||
stays outside machine ticks and inside the original frame advance. Ordinary
|
||||
asynchronous gameplay commits continue independently of this coordination.
|
||||
|
||||
Historical source: accepted DEC-0071, implemented through PLN-0202 from AGD-0075.
|
||||
The canonical contracts are [Save Memory and MEMCARD](../../../docs/specs/runtime/08-save-memory-and-memcard.md),
|
||||
[Headless Control](../../../docs/specs/runtime/11-portability-and-cross-platform-execution.md#131-control-contract)
|
||||
and [Memcard Controls](../../../docs/specs/runtime/11a-headless-automation-protocol.md#memcard-controls).
|
||||
This lesson explains the published result rather than defining a new policy.
|
||||
|
||||
## A tick watchdog can measure attempts without measuring useful work
|
||||
|
||||
An owner can repeatedly call firmware while an execution gate returns before
|
||||
the VM advances. In the original incident, 100,000 firmware attempts left the
|
||||
guest at logical frame zero and VM tick two, with native presentation IO pending.
|
||||
The host watchdog correctly reported exhausted attempts; that observation did
|
||||
not establish excessive guest instructions or a guest fault.
|
||||
|
||||
Increasing a guest budget would have changed the wrong quantity. The useful
|
||||
question is which dependency prevents progress, which owner can observe it,
|
||||
and which deadline governs it. Here the synchronous host owns the frame request,
|
||||
while an asynchronous storage worker owns the publication and its resources.
|
||||
|
||||
## Wait on the execution dependency, not every active worker
|
||||
|
||||
The query follows the active GameRunning task's session: its bootstrap hook
|
||||
completed successfully, the memcard session still blocks execution, and native IO
|
||||
remains owned. That excludes an ordinary gameplay save whose caller can continue
|
||||
executing while storage works in parallel.
|
||||
|
||||
This distinction is operationally observable. A channel-controlled gameplay
|
||||
commit remains active while the guest completes its next frame. A bootstrap
|
||||
publication under the same kind of hold prevents the first frame until the
|
||||
worker returns or native supervision requests external action.
|
||||
|
||||
## Notification ordering and clocks solve different problems
|
||||
|
||||
The owner reads a fresh lane progress stamp before every dependency observation
|
||||
and native poll. It then waits for actual progress, in requested intervals of at
|
||||
most 5 ms. Reusing a stamp indefinitely after another job finishes would turn
|
||||
later waits into immediate returns even while the relevant publication remains
|
||||
pending. A wake only permits another observation; it is not proof of success.
|
||||
|
||||
The request keeps its native deadlines from admission: cancellation at 500 ms
|
||||
and stop/escalation at 1 s. A separate owner guard expires 2 s after the first wait
|
||||
admission within that advance and never resets on wakes or reentry. Native
|
||||
action-required boundaries take precedence over that guard. Explicit-instant
|
||||
tests qualify the guard; actual blocked storage reaches native supervision first.
|
||||
|
||||
Machine execution keeps its 100,000 firmware-tick watchdog. Polling and waiting
|
||||
do not add simulated ticks, frames, input or instruction work. The frame request
|
||||
is neither replayed nor moved into boot.
|
||||
|
||||
## Native supervision should return before another guest tick
|
||||
|
||||
While the bootstrap dependency remains held, the owner polls native work without
|
||||
executing another firmware tick. This lets it observe an unavailable card or
|
||||
restart requirement before allowing guest execution to proceed. The controlled
|
||||
failure case asserts zero completed frames, a paused guest and no fabricated
|
||||
VM fault.
|
||||
|
||||
Timeout and cessation remain separate. A blocked native operation can require
|
||||
external action while its worker still owns the file lock. Returning from an
|
||||
advance does not free that lock or its buffers. The integration test verifies
|
||||
ownership while the operation is held, then explicitly permits safe worker
|
||||
return before cleanup.
|
||||
|
||||
## A reader can publish metadata without saving its own answer
|
||||
|
||||
The previous neutral reader intentionally imported no presentation or commit
|
||||
operation. That is a strong readback oracle: correct payload plus an unchanged
|
||||
whole image. It also leaves presentation during reopened bootstrap untested.
|
||||
|
||||
An additional neutral reader supplies presentation in its hook and verifies the
|
||||
existing bytes 0, 127, 128 and 255 without a slot write or payload commit. Its
|
||||
metadata publication is intentional. A distinct-process test sends exactly one
|
||||
first advance, checks its frame/tick state and captures the canonical game frame.
|
||||
The original no-presentation reader separately retains the whole-image oracle.
|
||||
|
||||
## Optimized and debug execution expose different scheduling windows
|
||||
|
||||
The original installed probe failed intermittently in two of nineteen fresh
|
||||
processes. The controlled storage test establishes entry into the relevant write
|
||||
using a channel, holds it while observing the owner, and then permits completion.
|
||||
The old optimized host expired its tick watchdog while that write was held.
|
||||
The slower debug host could already let it finish before exhausting attempts.
|
||||
|
||||
The [pre-fix release failure](evidence/qualification/red-controlled-release.log)
|
||||
and corrected [release qualification](evidence/qualification/release.log) preserve
|
||||
that distinction. A green debug test alone would not have established the fix.
|
||||
Control of the IO phase and optimized execution complement each other.
|
||||
|
||||
## Evidence and ownership boundary
|
||||
|
||||
The [qualification summary](evidence/summary.json) records 1,125 passing workspace
|
||||
tests, 89 passing release tests, formatter and strict workspace clippy success,
|
||||
and all four packaged automation cases passing against the exact extracted
|
||||
macOS arm64 distribution. The generic workspace run has 16 ignored tests; the
|
||||
four packaged cases were separately executed successfully. Other manual/device
|
||||
and resource qualification cases remain ignored.
|
||||
|
||||
The [baseline](evidence/baseline/review-summary.json) preserves the nineteen
|
||||
installed native probes and two original failure transcripts. Source deltas,
|
||||
source/binary/archive/schema hashes, native logs and the selected stable install's
|
||||
unchanged fingerprints remain in the qualification evidence. The archive is also
|
||||
retained alongside its isolated installation.
|
||||
|
||||
The [runtime handoff](runtime-handoff.md) identifies the qualified executable for
|
||||
the Studio owner. This delivery executes only provider tests with runtime-owned
|
||||
PBX/ABI fixtures. Studio/game builds and the consumer's Zelda/UI/MCP acceptance
|
||||
remain with that owner. Qualification is macOS arm64, not a cross-platform,
|
||||
physical power-cut or device-latency certification.
|
||||
+485
@@ -0,0 +1,485 @@
|
||||
{
|
||||
"hello": {
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory"
|
||||
],
|
||||
"limits": {
|
||||
"callTimeoutMs": 60000,
|
||||
"handshakeTimeoutMs": 5000,
|
||||
"maxCommandBytes": 65536,
|
||||
"maxFrames": 600,
|
||||
"maxResponseBytes": 33554432,
|
||||
"shutdownTimeoutMs": 5000
|
||||
},
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"runtimeVersion": "0.1.0",
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "hello"
|
||||
},
|
||||
"observations": [
|
||||
{
|
||||
"request": {
|
||||
"requestId": "1",
|
||||
"command": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"requiredCapabilities": [
|
||||
"memcard",
|
||||
"log_read"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "1",
|
||||
"result": {
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory"
|
||||
],
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
}
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "2",
|
||||
"command": "memcard_mount",
|
||||
"params": {
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-8ipr560i/owned-copy.pmc",
|
||||
"action": "open",
|
||||
"access": "read_write"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "2",
|
||||
"result": {
|
||||
"dirty": false,
|
||||
"dirtySlots": [],
|
||||
"io": {
|
||||
"active": false,
|
||||
"deferred": false,
|
||||
"phase": "idle"
|
||||
},
|
||||
"media": {
|
||||
"access": "read_write",
|
||||
"cardId": "c0e20cf55f4661f7298054098c710b2d",
|
||||
"degraded": false,
|
||||
"error": null,
|
||||
"mountEpoch": "0",
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-8ipr560i/owned-copy.pmc",
|
||||
"preparation": "ready",
|
||||
"recovered": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"recovery": {
|
||||
"reconciliationRequired": false,
|
||||
"removalPending": false,
|
||||
"restartRequired": false
|
||||
},
|
||||
"request": null,
|
||||
"session": {
|
||||
"actionRequired": false,
|
||||
"appId": null,
|
||||
"bootAttempted": false,
|
||||
"bootPhase": "idle",
|
||||
"choice": null,
|
||||
"mode": null,
|
||||
"resident": false
|
||||
}
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "3",
|
||||
"command": "boot",
|
||||
"params": {
|
||||
"path": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/discussion/workflow/plans/evidence/PLN-0172/native-reopen-watchdog/reader-cartridge",
|
||||
"memcardChoice": "persistent"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "3",
|
||||
"result": {
|
||||
"appId": 2137977836,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 0,
|
||||
"stackTop": [],
|
||||
"status": "running",
|
||||
"tickIndex": 0
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "4",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 128
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "4",
|
||||
"result": {
|
||||
"events": [
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "PrometeuOS starting...",
|
||||
"sequence": 0,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 0
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Firmware Reset",
|
||||
"sequence": 1,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 2
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Launching Hub",
|
||||
"sequence": 2,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 2
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Loading cartridge: zelda1",
|
||||
"sequence": 3,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 6
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Entering GameRunning",
|
||||
"sequence": 4,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 30
|
||||
}
|
||||
],
|
||||
"gap": false,
|
||||
"logEpoch": 0,
|
||||
"newestSequence": 4,
|
||||
"nextAfterSequence": 4,
|
||||
"oldestSequence": 0,
|
||||
"overflow": false,
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b"
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "5",
|
||||
"command": "advance",
|
||||
"params": {
|
||||
"frames": 1
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "5",
|
||||
"result": {
|
||||
"completed": 0,
|
||||
"error": {
|
||||
"code": "watchdog_expired",
|
||||
"details": {
|
||||
"hostTickLimit": 100000
|
||||
},
|
||||
"message": "headless host frame-advance watchdog expired after 100000 firmware ticks"
|
||||
},
|
||||
"requested": 1,
|
||||
"stop": "host_error"
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "6",
|
||||
"command": "get_state",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "6",
|
||||
"result": {
|
||||
"appId": 2137977836,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 233,
|
||||
"stackTop": [
|
||||
{
|
||||
"kind": "int32",
|
||||
"value": 0
|
||||
}
|
||||
],
|
||||
"status": "paused",
|
||||
"tickIndex": 2
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "7",
|
||||
"command": "get_fault",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "7",
|
||||
"result": null,
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "8",
|
||||
"command": "get_memcard_state",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "8",
|
||||
"result": {
|
||||
"dirty": false,
|
||||
"dirtySlots": [],
|
||||
"io": {
|
||||
"active": true,
|
||||
"deferred": false,
|
||||
"phase": "running"
|
||||
},
|
||||
"media": {
|
||||
"access": "read_write",
|
||||
"cardId": "c0e20cf55f4661f7298054098c710b2d",
|
||||
"degraded": false,
|
||||
"error": null,
|
||||
"mountEpoch": "1",
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-8ipr560i/owned-copy.pmc",
|
||||
"preparation": "ready",
|
||||
"recovered": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"recovery": {
|
||||
"reconciliationRequired": false,
|
||||
"removalPending": false,
|
||||
"restartRequired": false
|
||||
},
|
||||
"request": {
|
||||
"id": "1",
|
||||
"operation": "presentation",
|
||||
"reason": "none",
|
||||
"retained": false,
|
||||
"slot": null,
|
||||
"state": "pending",
|
||||
"storageError": null
|
||||
},
|
||||
"session": {
|
||||
"actionRequired": false,
|
||||
"appId": 2137977836,
|
||||
"bootAttempted": true,
|
||||
"bootPhase": "running",
|
||||
"choice": "persistent",
|
||||
"mode": "persistent",
|
||||
"resident": true
|
||||
}
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "9",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 128
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "9",
|
||||
"result": {
|
||||
"events": [
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "PrometeuOS starting...",
|
||||
"sequence": 0,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 0
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Firmware Reset",
|
||||
"sequence": 1,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 2
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Launching Hub",
|
||||
"sequence": 2,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 2
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Loading cartridge: zelda1",
|
||||
"sequence": 3,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 6
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Entering GameRunning",
|
||||
"sequence": 4,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 30
|
||||
}
|
||||
],
|
||||
"gap": false,
|
||||
"logEpoch": 0,
|
||||
"newestSequence": 4,
|
||||
"nextAfterSequence": 4,
|
||||
"oldestSequence": 0,
|
||||
"overflow": false,
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b"
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "10",
|
||||
"command": "shutdown",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "10",
|
||||
"result": {
|
||||
"closed": true,
|
||||
"memcard": {
|
||||
"dirty": false,
|
||||
"dirtySlots": [],
|
||||
"io": {
|
||||
"active": false,
|
||||
"deferred": false,
|
||||
"phase": "idle"
|
||||
},
|
||||
"media": {
|
||||
"access": "read_write",
|
||||
"cardId": "c0e20cf55f4661f7298054098c710b2d",
|
||||
"degraded": false,
|
||||
"error": null,
|
||||
"mountEpoch": "1",
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-8ipr560i/owned-copy.pmc",
|
||||
"preparation": "ready",
|
||||
"recovered": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"recovery": {
|
||||
"reconciliationRequired": false,
|
||||
"removalPending": false,
|
||||
"restartRequired": false
|
||||
},
|
||||
"request": null,
|
||||
"session": {
|
||||
"actionRequired": false,
|
||||
"appId": 2137977836,
|
||||
"bootAttempted": true,
|
||||
"bootPhase": "running",
|
||||
"choice": "persistent",
|
||||
"mode": "persistent",
|
||||
"resident": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"sessionId": "51e29382483fa5aea3c9318bb6f4a33b",
|
||||
"type": "response"
|
||||
}
|
||||
}
|
||||
],
|
||||
"exitCode": 0,
|
||||
"headlessSha256": "e5e9571e7ab42724af37294c79b19478a1e1b5a71df177eee7141d42e042f6f4",
|
||||
"advanceCommands": 1,
|
||||
"scope": "Native-only probe; temporary copy of fixture card; no Studio consumer and no advance retry."
|
||||
}
|
||||
+485
@@ -0,0 +1,485 @@
|
||||
{
|
||||
"hello": {
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory"
|
||||
],
|
||||
"limits": {
|
||||
"callTimeoutMs": 60000,
|
||||
"handshakeTimeoutMs": 5000,
|
||||
"maxCommandBytes": 65536,
|
||||
"maxFrames": 600,
|
||||
"maxResponseBytes": 33554432,
|
||||
"shutdownTimeoutMs": 5000
|
||||
},
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"runtimeVersion": "0.1.0",
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "hello"
|
||||
},
|
||||
"observations": [
|
||||
{
|
||||
"request": {
|
||||
"requestId": "1",
|
||||
"command": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
},
|
||||
"requiredCapabilities": [
|
||||
"memcard",
|
||||
"log_read"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "1",
|
||||
"result": {
|
||||
"capabilities": [
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"log_read",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
"memcard",
|
||||
"memcard_mount",
|
||||
"memcard_unmount",
|
||||
"get_memcard_state",
|
||||
"memcard_reconcile",
|
||||
"memcard_continue_in_memory"
|
||||
],
|
||||
"protocolVersion": {
|
||||
"major": 1,
|
||||
"minor": 2
|
||||
}
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "2",
|
||||
"command": "memcard_mount",
|
||||
"params": {
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-hyqvb7jv/owned-copy.pmc",
|
||||
"action": "open",
|
||||
"access": "read_write"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "2",
|
||||
"result": {
|
||||
"dirty": false,
|
||||
"dirtySlots": [],
|
||||
"io": {
|
||||
"active": false,
|
||||
"deferred": false,
|
||||
"phase": "idle"
|
||||
},
|
||||
"media": {
|
||||
"access": "read_write",
|
||||
"cardId": "c0e20cf55f4661f7298054098c710b2d",
|
||||
"degraded": false,
|
||||
"error": null,
|
||||
"mountEpoch": "0",
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-hyqvb7jv/owned-copy.pmc",
|
||||
"preparation": "ready",
|
||||
"recovered": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"recovery": {
|
||||
"reconciliationRequired": false,
|
||||
"removalPending": false,
|
||||
"restartRequired": false
|
||||
},
|
||||
"request": null,
|
||||
"session": {
|
||||
"actionRequired": false,
|
||||
"appId": null,
|
||||
"bootAttempted": false,
|
||||
"bootPhase": "idle",
|
||||
"choice": null,
|
||||
"mode": null,
|
||||
"resident": false
|
||||
}
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "3",
|
||||
"command": "boot",
|
||||
"params": {
|
||||
"path": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/discussion/workflow/plans/evidence/PLN-0172/native-reopen-watchdog/reader-cartridge",
|
||||
"memcardChoice": "persistent"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "3",
|
||||
"result": {
|
||||
"appId": 2137977836,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 0,
|
||||
"stackTop": [],
|
||||
"status": "running",
|
||||
"tickIndex": 0
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "4",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 128
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "4",
|
||||
"result": {
|
||||
"events": [
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "PrometeuOS starting...",
|
||||
"sequence": 0,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 0
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Firmware Reset",
|
||||
"sequence": 1,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 1
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Launching Hub",
|
||||
"sequence": 2,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 1
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Loading cartridge: zelda1",
|
||||
"sequence": 3,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 4
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Entering GameRunning",
|
||||
"sequence": 4,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 29
|
||||
}
|
||||
],
|
||||
"gap": false,
|
||||
"logEpoch": 0,
|
||||
"newestSequence": 4,
|
||||
"nextAfterSequence": 4,
|
||||
"oldestSequence": 0,
|
||||
"overflow": false,
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf"
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "5",
|
||||
"command": "advance",
|
||||
"params": {
|
||||
"frames": 1
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "5",
|
||||
"result": {
|
||||
"completed": 0,
|
||||
"error": {
|
||||
"code": "watchdog_expired",
|
||||
"details": {
|
||||
"hostTickLimit": 100000
|
||||
},
|
||||
"message": "headless host frame-advance watchdog expired after 100000 firmware ticks"
|
||||
},
|
||||
"requested": 1,
|
||||
"stop": "host_error"
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "6",
|
||||
"command": "get_state",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "6",
|
||||
"result": {
|
||||
"appId": 2137977836,
|
||||
"logicalFrameIndex": 0,
|
||||
"pc": 233,
|
||||
"stackTop": [
|
||||
{
|
||||
"kind": "int32",
|
||||
"value": 0
|
||||
}
|
||||
],
|
||||
"status": "paused",
|
||||
"tickIndex": 2
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "7",
|
||||
"command": "get_fault",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "7",
|
||||
"result": null,
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "8",
|
||||
"command": "get_memcard_state",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "8",
|
||||
"result": {
|
||||
"dirty": false,
|
||||
"dirtySlots": [],
|
||||
"io": {
|
||||
"active": true,
|
||||
"deferred": false,
|
||||
"phase": "running"
|
||||
},
|
||||
"media": {
|
||||
"access": "read_write",
|
||||
"cardId": "c0e20cf55f4661f7298054098c710b2d",
|
||||
"degraded": false,
|
||||
"error": null,
|
||||
"mountEpoch": "1",
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-hyqvb7jv/owned-copy.pmc",
|
||||
"preparation": "ready",
|
||||
"recovered": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"recovery": {
|
||||
"reconciliationRequired": false,
|
||||
"removalPending": false,
|
||||
"restartRequired": false
|
||||
},
|
||||
"request": {
|
||||
"id": "1",
|
||||
"operation": "presentation",
|
||||
"reason": "none",
|
||||
"retained": false,
|
||||
"slot": null,
|
||||
"state": "pending",
|
||||
"storageError": null
|
||||
},
|
||||
"session": {
|
||||
"actionRequired": false,
|
||||
"appId": 2137977836,
|
||||
"bootAttempted": true,
|
||||
"bootPhase": "running",
|
||||
"choice": "persistent",
|
||||
"mode": "persistent",
|
||||
"resident": true
|
||||
}
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "9",
|
||||
"command": "get_logs",
|
||||
"params": {
|
||||
"afterSequence": null,
|
||||
"limit": 128
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "9",
|
||||
"result": {
|
||||
"events": [
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "PrometeuOS starting...",
|
||||
"sequence": 0,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 0
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Firmware Reset",
|
||||
"sequence": 1,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 1
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Launching Hub",
|
||||
"sequence": 2,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 1
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Loading cartridge: zelda1",
|
||||
"sequence": 3,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 4
|
||||
},
|
||||
{
|
||||
"appId": null,
|
||||
"frame": 0,
|
||||
"level": "info",
|
||||
"message": "Entering GameRunning",
|
||||
"sequence": 4,
|
||||
"source": "pos",
|
||||
"tag": 0,
|
||||
"timestampMs": 29
|
||||
}
|
||||
],
|
||||
"gap": false,
|
||||
"logEpoch": 0,
|
||||
"newestSequence": 4,
|
||||
"nextAfterSequence": 4,
|
||||
"oldestSequence": 0,
|
||||
"overflow": false,
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf"
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"requestId": "10",
|
||||
"command": "shutdown",
|
||||
"params": {}
|
||||
},
|
||||
"response": {
|
||||
"requestId": "10",
|
||||
"result": {
|
||||
"closed": true,
|
||||
"memcard": {
|
||||
"dirty": false,
|
||||
"dirtySlots": [],
|
||||
"io": {
|
||||
"active": false,
|
||||
"deferred": false,
|
||||
"phase": "idle"
|
||||
},
|
||||
"media": {
|
||||
"access": "read_write",
|
||||
"cardId": "c0e20cf55f4661f7298054098c710b2d",
|
||||
"degraded": false,
|
||||
"error": null,
|
||||
"mountEpoch": "1",
|
||||
"path": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/pln172-native-reopen-hyqvb7jv/owned-copy.pmc",
|
||||
"preparation": "ready",
|
||||
"recovered": false,
|
||||
"writeBlocked": false
|
||||
},
|
||||
"recovery": {
|
||||
"reconciliationRequired": false,
|
||||
"removalPending": false,
|
||||
"restartRequired": false
|
||||
},
|
||||
"request": null,
|
||||
"session": {
|
||||
"actionRequired": false,
|
||||
"appId": 2137977836,
|
||||
"bootAttempted": true,
|
||||
"bootPhase": "running",
|
||||
"choice": "persistent",
|
||||
"mode": "persistent",
|
||||
"resident": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"sessionId": "9b96872c8a5c0a2d66543d4f7ff90acf",
|
||||
"type": "response"
|
||||
}
|
||||
}
|
||||
],
|
||||
"exitCode": 0,
|
||||
"headlessSha256": "e5e9571e7ab42724af37294c79b19478a1e1b5a71df177eee7141d42e042f6f4",
|
||||
"advanceCommands": 1,
|
||||
"scope": "Native-only probe; temporary copy of fixture card; no Studio consumer and no advance retry."
|
||||
}
|
||||
+1116
File diff suppressed because it is too large
Load Diff
+8
@@ -0,0 +1,8 @@
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 2.30s
|
||||
Running unittests src/lib.rs (target/debug/deps/prometeu_host_headless-34e7d78b76b56071)
|
||||
|
||||
running 1 test
|
||||
test host::memcard::tests::first_reopen_frame_waits_for_controlled_presentation_without_replaying ... ok
|
||||
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 18 filtered out; finished in 0.38s
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
Checking prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Checking prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.58s
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
building artifacts:
|
||||
prometeu-cli-aarch64-apple-darwin.zip
|
||||
prometeu-cli-aarch64-apple-darwin.zip.sha256
|
||||
prometeu-host-desktop-winit-aarch64-apple-darwin.zip
|
||||
prometeu-host-desktop-winit-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-dummy-boy-aarch64-apple-darwin.zip
|
||||
pbxgen-dummy-boy-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-stress-aarch64-apple-darwin.zip
|
||||
pbxgen-stress-aarch64-apple-darwin.zip.sha256
|
||||
|
||||
building aarch64-apple-darwin target, using cargo profile dist --workspace)
|
||||
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
|
||||
Compiling prometeu-test-support v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/dev/prometeu-test-support)
|
||||
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
|
||||
Finished `dist` profile [optimized] target(s) in 42.70s
|
||||
announcing v0.1.0
|
||||
prometeu-cli 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip
|
||||
[bin] prometeu
|
||||
[bin] prometeu-headless
|
||||
[bin] prometeu-runtime
|
||||
[misc] 11a-headless-automation-protocol.md, LICENSE, README.md, headless-protocol
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip.sha256
|
||||
prometeu-host-desktop-winit 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-host-desktop-winit-aarch64-apple-darwin.zip
|
||||
[bin] prometeu-host-desktop-winit
|
||||
[misc] LICENSE, README.md, VERSION.txt
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-host-desktop-winit-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-dummy-boy 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-dummy-boy-aarch64-apple-darwin.zip
|
||||
[bin] pbxgen-dummy-boy
|
||||
[misc] LICENSE, README.md
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-dummy-boy-aarch64-apple-darwin.zip.sha256
|
||||
pbxgen-stress 0.1.0
|
||||
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-stress-aarch64-apple-darwin.zip
|
||||
[bin] pbxgen-stress
|
||||
[misc] LICENSE, README.md
|
||||
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-stress-aarch64-apple-darwin.zip.sha256
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"builder": "cargo-dist 0.30.3",
|
||||
"target": "aarch64-apple-darwin",
|
||||
"profile": "dist",
|
||||
"archive": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip",
|
||||
"archiveSha256": "05b0e38f797bc6d24cd69aeb7f6cad9ae224cb2308390a084634dfebe5e8f2f7",
|
||||
"installation": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/dist-staging/qualification/PLN-0202",
|
||||
"installedSha256": {
|
||||
"prometeu": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"prometeu-runtime": "ee00a587eb48030d1455d3c9bedd784ab620309a09877b50fe3641ae502635df",
|
||||
"prometeu-headless": "18423f798ab28bbd38c12a7ee46459f3ef3d08876cc64327952f57be041fc5df",
|
||||
"headless-protocol/request.schema.json": "554960a1c6c1304da32753937b899b51ac658cae4b9d96927f5a384325ce2ae2",
|
||||
"headless-protocol/response.schema.json": "7a8a0fe70a6864203b771e0564dc4227b768213d2368c5b162c892c55c5e186b",
|
||||
"11a-headless-automation-protocol.md": "2c5391fdbeb35964717f2af1f994b5c81b1b4278641fece17ccdc3fb6b766a6e"
|
||||
},
|
||||
"retainedArchive": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/dist-staging/qualification/PLN-0202/prometeu-cli-aarch64-apple-darwin.zip"
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"workflowMentions": [],
|
||||
"brokenLessonLinks": []
|
||||
}
|
||||
+673
@@ -0,0 +1,673 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_drivers::{ControlledWallClock, MemoryBanks};
|
||||
use prometeu_firmware::firmware_state::{AppCrashesStep, ResetStep};
|
||||
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
|
||||
use prometeu_hal::{
|
||||
AssetBridge, AudioBridge, FrameId, Game2DFrameComposer, InputPlatform, InputSignals,
|
||||
OwnedRgba8888Frame, RenderBackend, RenderSubmission, RenderSubmissionSink, RenderSubmitError,
|
||||
RuntimePlatform, TelemetryPlatform, WallClock,
|
||||
};
|
||||
use prometeu_system::{CrashReport, LatestRenderFrameStore};
|
||||
#[path = "memcard.rs"]
|
||||
mod memcard;
|
||||
pub use memcard::{
|
||||
MediaAccess, MediaAction, MemcardChoice, MemcardFailure, MemcardMount, MemcardState,
|
||||
PendingWrites, TeardownPolicy,
|
||||
};
|
||||
|
||||
const BOOT_TICK_LIMIT: usize = 5000;
|
||||
const HOST_FRAME_ADVANCE_TICK_LIMIT: usize = 100_000;
|
||||
|
||||
/// One published logical frame plus the automation counter.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CapturedFrame {
|
||||
pub logical_frame_index: u64,
|
||||
pub frame: OwnedRgba8888Frame,
|
||||
}
|
||||
|
||||
/// Debugger-shaped execution snapshot.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostState {
|
||||
pub pc: usize,
|
||||
pub stack_top: prometeu_hal::ValueSnapshot,
|
||||
pub frame_index: u64,
|
||||
pub tick_index: u64,
|
||||
pub app_id: u32,
|
||||
pub status: HostExecutionStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostExecutionStatus {
|
||||
Running,
|
||||
Paused,
|
||||
Terminated,
|
||||
Faulted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AdvanceFrameOutcome {
|
||||
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
ActionRequired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AdvanceFramesStop {
|
||||
Completed,
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
ActionRequired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdvanceFramesOutcome {
|
||||
pub requested: u64,
|
||||
pub completed: u64,
|
||||
pub stop: AdvanceFramesStop,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HostError {
|
||||
Memcard(Box<MemcardFailure>),
|
||||
AlreadyBooted,
|
||||
BootFailed { reason: String, report: Option<Box<CrashReport>> },
|
||||
InvalidState { operation: &'static str, status: HostExecutionStatus },
|
||||
FrameAdvanceWatchdogExpired { host_tick_limit: usize },
|
||||
FrameNotPublished { previous: Option<FrameId> },
|
||||
NoFrameAvailable,
|
||||
}
|
||||
|
||||
impl fmt::Display for HostError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Memcard(error) => write!(f, "{}: {}", error.operation, error.reason),
|
||||
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
|
||||
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
|
||||
Self::InvalidState { operation, status } => {
|
||||
write!(f, "{operation} is invalid while execution is {status:?}")
|
||||
}
|
||||
Self::FrameAdvanceWatchdogExpired { host_tick_limit } => {
|
||||
write!(
|
||||
f,
|
||||
"headless host frame-advance watchdog expired after {host_tick_limit} firmware ticks"
|
||||
)
|
||||
}
|
||||
Self::FrameNotPublished { .. } => {
|
||||
write!(f, "logical frame closed without its canonical published frame")
|
||||
}
|
||||
Self::NoFrameAvailable => write!(f, "no completed frame is available for capture"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for HostError {}
|
||||
|
||||
/// In-process host. The desktop winit runner is a separate crate and is not linked here.
|
||||
pub struct HeadlessHost {
|
||||
firmware: Firmware,
|
||||
platform: HeadlessPlatform,
|
||||
signals: InputSignals,
|
||||
boot_attempted: bool,
|
||||
last_completed_frame: Option<CompletedFrame>,
|
||||
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
|
||||
media: memcard::MediaSelection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct CompletedFrame {
|
||||
logical_frame_index: u64,
|
||||
frame_id: FrameId,
|
||||
}
|
||||
|
||||
struct HeadlessPlatform {
|
||||
hardware: Hardware,
|
||||
store: LatestRenderFrameStore,
|
||||
}
|
||||
|
||||
impl HeadlessHost {
|
||||
/// Install storage through the shared worker. Progress is driven by ordinary host ticks.
|
||||
pub fn install_memcard(
|
||||
&mut self,
|
||||
storage: Box<dyn prometeu_hal::memcard::MemcardStorage>,
|
||||
) -> prometeu_system::memcard::image::Result<()> {
|
||||
self.firmware.os.memcard().mount_card(storage)
|
||||
}
|
||||
pub fn memcard_preparation(&mut self) -> prometeu_system::memcard::admission::PreparationState {
|
||||
self.firmware.os.memcard().admission.state
|
||||
}
|
||||
|
||||
pub fn new() -> Self {
|
||||
let clock = Arc::new(ControlledWallClock::default());
|
||||
Self::with_clock(clock.clone(), Some(clock))
|
||||
}
|
||||
|
||||
/// Supply a host-owned civil clock. The caller retains control of this provider.
|
||||
pub fn new_with_wall_clock(clock: Arc<dyn WallClock>) -> Self {
|
||||
Self::with_clock(clock, None)
|
||||
}
|
||||
|
||||
fn with_clock(
|
||||
clock: Arc<dyn WallClock>,
|
||||
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
|
||||
) -> Self {
|
||||
let memory_banks = Arc::new(MemoryBanks::new());
|
||||
let hardware = Hardware::new_with_memory_banks(Arc::clone(&memory_banks), clock);
|
||||
let store = LatestRenderFrameStore::default();
|
||||
Self {
|
||||
firmware: Firmware::new(None),
|
||||
platform: HeadlessPlatform { hardware, store },
|
||||
signals: InputSignals::default(),
|
||||
boot_attempted: false,
|
||||
last_completed_frame: None,
|
||||
controlled_wall_clock,
|
||||
media: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the same clock supplied to the runtime platform.
|
||||
pub fn wall_clock(&self) -> &dyn WallClock {
|
||||
self.platform.wall_clock()
|
||||
}
|
||||
|
||||
/// Native controls for the default clock; custom providers are controlled by their owner.
|
||||
pub fn controlled_wall_clock(&self) -> Option<&ControlledWallClock> {
|
||||
self.controlled_wall_clock.as_deref()
|
||||
}
|
||||
|
||||
/// Observe native log history without advancing, draining or changing lifecycle.
|
||||
pub fn log_snapshot(
|
||||
&self,
|
||||
after: Option<u64>,
|
||||
limit: usize,
|
||||
) -> (Vec<prometeu_hal::log::LogEvent>, Option<u64>, Option<u64>) {
|
||||
self.firmware.os.log_snapshot(after, limit)
|
||||
}
|
||||
|
||||
/// Load `path` and tick until the firmware is in `GameRunning`.
|
||||
///
|
||||
/// The transition into `GameRunning` is the last tick. The first game
|
||||
/// logical frame stays available for [`Self::advance_frame`].
|
||||
pub fn boot(&mut self, path: impl Into<String>) -> Result<(), HostError> {
|
||||
self.boot_with_choice(path, None)
|
||||
}
|
||||
pub fn boot_with_memcard_choice(
|
||||
&mut self,
|
||||
path: impl Into<String>,
|
||||
choice: prometeu_system::memcard::admission::Choice,
|
||||
) -> Result<(), HostError> {
|
||||
self.boot_with_choice(path, Some(choice))
|
||||
}
|
||||
fn boot_with_choice(
|
||||
&mut self,
|
||||
path: impl Into<String>,
|
||||
choice: Option<prometeu_system::memcard::admission::Choice>,
|
||||
) -> Result<(), HostError> {
|
||||
if self.boot_attempted {
|
||||
return Err(HostError::AlreadyBooted);
|
||||
}
|
||||
self.boot_attempted = true;
|
||||
self.media.choice = choice;
|
||||
self.media.boot_phase = "loading";
|
||||
let path = path.into();
|
||||
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
||||
|
||||
let boot_deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
let mut choice_submitted = false;
|
||||
for _ in 0..BOOT_TICK_LIMIT {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
self.media.boot_phase = "running";
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
self.media.boot_phase = "failed";
|
||||
let report = self.get_fault();
|
||||
let reason = report
|
||||
.as_ref()
|
||||
.map(CrashReport::summary)
|
||||
.unwrap_or_else(|| "cartridge crashed during boot".to_string());
|
||||
return Err(HostError::BootFailed { reason, report: report.map(Box::new) });
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(HostError::BootFailed {
|
||||
reason: "cartridge did not load".to_string(),
|
||||
report: None,
|
||||
});
|
||||
}
|
||||
let progress = self.firmware.os.memcard().lane.progress_stamp();
|
||||
if let FirmwareState::LoadCartridge(step) = &self.firmware.state
|
||||
&& step.cartridge.memcard_slots.is_none()
|
||||
&& choice.is_some()
|
||||
{
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", "invalid_state"));
|
||||
}
|
||||
if choice_submitted
|
||||
&& let prometeu_system::memcard::admission::PreparationState::Failed(error) =
|
||||
self.firmware.os.memcard().admission.state
|
||||
{
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", memcard::error_name(error)));
|
||||
}
|
||||
let waiting = matches!(&self.firmware.state,FirmwareState::LoadCartridge(step) if step.needs_memcard_choice());
|
||||
if waiting {
|
||||
let Some(choice) = choice else {
|
||||
self.media.boot_phase = "choice_required";
|
||||
return Err(self.memcard_error("boot", "choice_required"));
|
||||
};
|
||||
if self.firmware.os.memcard().preparation_active() {
|
||||
self.poll_memcard();
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.lane
|
||||
.wait_for_progress(progress, std::time::Duration::from_millis(5));
|
||||
continue;
|
||||
}
|
||||
let created_at = self.platform.wall_clock().utc_unix_seconds();
|
||||
let result = match &mut self.firmware.state {
|
||||
FirmwareState::LoadCartridge(step) => {
|
||||
step.choose_memcard(&mut self.firmware.os, choice, created_at)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", memcard::error_name(error)));
|
||||
}
|
||||
choice_submitted = true;
|
||||
self.media.boot_phase = "preparing";
|
||||
}
|
||||
self.tick_once();
|
||||
self.signals = InputSignals::default();
|
||||
if matches!(self.firmware.state, FirmwareState::LoadCartridge(_)) {
|
||||
if std::time::Instant::now() >= boot_deadline {
|
||||
break;
|
||||
}
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.lane
|
||||
.wait_for_progress(progress, std::time::Duration::from_millis(16));
|
||||
}
|
||||
}
|
||||
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
Ok(())
|
||||
} else {
|
||||
self.media.boot_phase = "failed";
|
||||
Err(HostError::BootFailed {
|
||||
reason: "boot did not reach the game".to_string(),
|
||||
report: self.get_fault().map(Box::new),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) -> Result<(), HostError> {
|
||||
self.reset_with_policy(TeardownPolicy::default()).map(|_| ())
|
||||
}
|
||||
fn reset_inner(&mut self) {
|
||||
self.signals = InputSignals::default();
|
||||
self.firmware.change_state(
|
||||
FirmwareState::Reset(ResetStep),
|
||||
&self.signals,
|
||||
&mut self.platform,
|
||||
);
|
||||
self.platform.store = LatestRenderFrameStore::default();
|
||||
self.boot_attempted = false;
|
||||
self.last_completed_frame = None;
|
||||
}
|
||||
|
||||
pub fn pause(&mut self) -> Result<(), HostError> {
|
||||
self.require_active("pause")?;
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn resume(&mut self) -> Result<(), HostError> {
|
||||
self.require_active("resume")?;
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute one VM instruction. This does not close a logical frame.
|
||||
pub fn step(&mut self) -> Result<Option<CrashReport>, HostError> {
|
||||
self.require_active("step")?;
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
let report = self.firmware.os.vm().debug_step_active_session(&mut self.platform);
|
||||
self.platform.hardware.audio.transport().consume_silently();
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub fn advance_frame(&mut self) -> Result<AdvanceFrameOutcome, HostError> {
|
||||
if let Some(report) = self.get_fault() {
|
||||
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(if self.host_action_required() {
|
||||
AdvanceFrameOutcome::ActionRequired
|
||||
} else {
|
||||
AdvanceFrameOutcome::Terminated
|
||||
});
|
||||
}
|
||||
|
||||
let start = self.firmware.os.vm().logical_frame_index();
|
||||
let previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
|
||||
for _ in 0..HOST_FRAME_ADVANCE_TICK_LIMIT {
|
||||
// A controlled lifecycle slice can consume the runtime step marker
|
||||
// without closing a logical frame. This operation still owns the
|
||||
// request until its first frame or an explicit stop boundary.
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
self.tick_once();
|
||||
if let Some(report) = self.get_fault() {
|
||||
self.finish_frame_advance();
|
||||
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
self.finish_frame_advance();
|
||||
return Ok(if self.host_action_required() {
|
||||
AdvanceFrameOutcome::ActionRequired
|
||||
} else {
|
||||
AdvanceFrameOutcome::Terminated
|
||||
});
|
||||
}
|
||||
|
||||
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
|
||||
if logical_frame_index > start {
|
||||
self.finish_frame_advance();
|
||||
let frame = self
|
||||
.platform
|
||||
.store
|
||||
.latest_frame()
|
||||
.ok_or(HostError::FrameNotPublished { previous: previous_frame_id })?;
|
||||
if Some(frame.frame_id) == previous_frame_id {
|
||||
return Err(HostError::FrameNotPublished { previous: previous_frame_id });
|
||||
}
|
||||
self.last_completed_frame =
|
||||
Some(CompletedFrame { logical_frame_index, frame_id: frame.frame_id });
|
||||
return Ok(AdvanceFrameOutcome::FrameCompleted {
|
||||
logical_frame_index,
|
||||
frame_id: frame.frame_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
self.finish_frame_advance();
|
||||
Err(HostError::FrameAdvanceWatchdogExpired {
|
||||
host_tick_limit: HOST_FRAME_ADVANCE_TICK_LIMIT,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn advance_frames(&mut self, count: u64) -> Result<AdvanceFramesOutcome, HostError> {
|
||||
let mut completed = 0;
|
||||
for _ in 0..count {
|
||||
match self.advance_frame()? {
|
||||
AdvanceFrameOutcome::FrameCompleted { .. } => completed += 1,
|
||||
AdvanceFrameOutcome::Faulted(report) => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::Faulted(report),
|
||||
});
|
||||
}
|
||||
AdvanceFrameOutcome::Terminated => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::Terminated,
|
||||
});
|
||||
}
|
||||
AdvanceFrameOutcome::ActionRequired => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::ActionRequired,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
|
||||
}
|
||||
|
||||
pub fn set_input(&mut self, signals: InputSignals) {
|
||||
self.signals = signals;
|
||||
}
|
||||
|
||||
pub fn clear_input(&mut self) {
|
||||
self.signals = InputSignals::default();
|
||||
}
|
||||
|
||||
pub fn set_right(&mut self, down: bool) {
|
||||
self.signals.right_signal = down;
|
||||
}
|
||||
|
||||
pub fn capture_frame(&self) -> Result<CapturedFrame, HostError> {
|
||||
let completed = self.last_completed_frame.ok_or(HostError::NoFrameAvailable)?;
|
||||
let frame = self.platform.store.latest_frame().ok_or(HostError::NoFrameAvailable)?;
|
||||
if frame.frame_id != completed.frame_id {
|
||||
return Err(HostError::FrameNotPublished { previous: Some(completed.frame_id) });
|
||||
}
|
||||
Ok(CapturedFrame { logical_frame_index: completed.logical_frame_index, frame })
|
||||
}
|
||||
|
||||
pub fn get_state(&mut self) -> HostState {
|
||||
let status = self.execution_status();
|
||||
HostState {
|
||||
pc: self.firmware.os.vm().active_pc().unwrap_or(0),
|
||||
stack_top: self.firmware.os.vm().active_operand_stack_top(10),
|
||||
frame_index: self.firmware.os.vm().logical_frame_index(),
|
||||
tick_index: self.firmware.os.vm().tick_index(),
|
||||
app_id: self.firmware.os.vm().current_app_id(),
|
||||
status,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_fault(&mut self) -> Option<CrashReport> {
|
||||
if let Some(report) = self.firmware.os.vm().last_crash_report() {
|
||||
return Some(report.clone());
|
||||
}
|
||||
match &self.firmware.state {
|
||||
FirmwareState::AppCrashes(AppCrashesStep { report }) => Some(report.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tick_once(&mut self) {
|
||||
self.firmware.tick(&self.signals, &mut self.platform);
|
||||
self.platform.hardware.audio.transport().consume_silently();
|
||||
}
|
||||
|
||||
fn execution_status(&mut self) -> HostExecutionStatus {
|
||||
if self.fault_is_visible() {
|
||||
HostExecutionStatus::Faulted
|
||||
} else if self.host_action_required() {
|
||||
HostExecutionStatus::Paused
|
||||
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
HostExecutionStatus::Terminated
|
||||
} else if self.firmware.os.vm().paused() {
|
||||
HostExecutionStatus::Paused
|
||||
} else {
|
||||
HostExecutionStatus::Running
|
||||
}
|
||||
}
|
||||
|
||||
fn fault_is_visible(&mut self) -> bool {
|
||||
self.firmware.os.vm().last_crash_report().is_some()
|
||||
|| matches!(self.firmware.state, FirmwareState::AppCrashes(_))
|
||||
}
|
||||
|
||||
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||
let status = self.execution_status();
|
||||
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused)
|
||||
&& !self.host_action_required()
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(HostError::InvalidState { operation, status })
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_frame_advance(&mut self) {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
self.firmware.os.vm().clear_debug_step_request();
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for HeadlessHost {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "resource-diagnostics"))]
|
||||
#[path = "resource_qualification_tests.rs"]
|
||||
mod resource_qualification_tests;
|
||||
|
||||
impl RenderSubmissionSink for HeadlessPlatform {
|
||||
fn submit_render_submission(
|
||||
&mut self,
|
||||
submission: RenderSubmission,
|
||||
) -> Result<(), RenderSubmitError> {
|
||||
let frame_id = submission.frame_id;
|
||||
let ownership = submission.ownership;
|
||||
self.hardware.submit_render_submission(submission)?;
|
||||
// Host dialogs use their own producer and may reuse FrameId::ZERO.
|
||||
// Capture/advance observe only canonical game publications.
|
||||
if ownership.app_mode != prometeu_hal::app_mode::AppMode::Game {
|
||||
return Ok(());
|
||||
}
|
||||
let (width, height) = self.hardware.gfx.size();
|
||||
let pixels = self.hardware.gfx.front_buffer().to_vec();
|
||||
let frame = OwnedRgba8888Frame::packed(frame_id, ownership, width, height, pixels)
|
||||
.map_err(|_| RenderSubmitError::SubmissionRejected)?;
|
||||
self.store.publish_frame(frame);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimePlatform for HeadlessPlatform {
|
||||
fn wall_clock(&self) -> &dyn WallClock {
|
||||
self.hardware.wall_clock()
|
||||
}
|
||||
|
||||
fn display_size(&self) -> (usize, usize) {
|
||||
(Hardware::W, Hardware::H)
|
||||
}
|
||||
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||
self
|
||||
}
|
||||
|
||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||
&mut self.hardware
|
||||
}
|
||||
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||
&mut self.hardware
|
||||
}
|
||||
|
||||
fn audio(&self) -> &dyn AudioBridge {
|
||||
self.hardware.audio()
|
||||
}
|
||||
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||
self.hardware.audio_mut()
|
||||
}
|
||||
|
||||
fn input(&self) -> &dyn InputPlatform {
|
||||
self.hardware.input()
|
||||
}
|
||||
|
||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||
self.hardware.input_mut()
|
||||
}
|
||||
|
||||
fn assets(&self) -> &dyn AssetBridge {
|
||||
self.hardware.assets()
|
||||
}
|
||||
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||
self.hardware.assets_mut()
|
||||
}
|
||||
|
||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||
self.hardware.telemetry()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use prometeu_bytecode::registry::FunctionDecl;
|
||||
use prometeu_test_support::program::{TestProgram, int64_signature};
|
||||
use std::fs;
|
||||
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::Export;
|
||||
|
||||
use super::{AdvanceFrameOutcome, HeadlessHost};
|
||||
|
||||
#[test]
|
||||
fn termination_during_frame_advance_clears_host_step_control() {
|
||||
let cartridge = non_closing_cartridge();
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(cartridge.to_string_lossy()).expect("boot non-closing cartridge");
|
||||
host.firmware.request_home_from_host();
|
||||
|
||||
assert_eq!(
|
||||
host.advance_frame().expect("lifecycle termination"),
|
||||
AdvanceFrameOutcome::Terminated
|
||||
);
|
||||
assert!(host.firmware.os.vm().paused());
|
||||
assert!(!host.firmware.os.vm().debug_step_requested());
|
||||
|
||||
fs::remove_dir_all(cartridge).expect("remove test cartridge");
|
||||
}
|
||||
|
||||
fn non_closing_cartridge() -> std::path::PathBuf {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"prometeu-headless-termination-cleanup-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("system clock")
|
||||
.as_nanos()
|
||||
));
|
||||
fs::create_dir_all(&directory).expect("create test cartridge");
|
||||
|
||||
let code = assemble("JMP 0\n").expect("assemble non-closing program");
|
||||
let module = TestProgram {
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
local_slots: 0,
|
||||
max_stack_slots: 1,
|
||||
signature: int64_signature(0, 0),
|
||||
captures: vec![],
|
||||
name: None,
|
||||
}],
|
||||
code,
|
||||
debug_info: None,
|
||||
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
|
||||
syscalls: vec![],
|
||||
}
|
||||
.serialize();
|
||||
fs::write(directory.join("program.pbx"), module).expect("write test program");
|
||||
fs::write(
|
||||
directory.join("manifest.json"),
|
||||
"{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": 91,\n \"title\": \"Termination Cleanup\",\n \"app_version\": \"0.1.0\",\n \"app_mode\": \"Game\",\n \"capabilities\": []\n}\n",
|
||||
)
|
||||
.expect("write test manifest");
|
||||
|
||||
directory
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user