feat(runtime): add host wall clock and administrative UTC timestamps
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

This commit is contained in:
2026-10-13 09:16:15 +01:00
parent 3e39a90083
commit 23dc6fc66d
21 changed files with 603 additions and 51 deletions
+27 -17
View File
@@ -12,7 +12,7 @@ use prometeu_hal::cartridge::AssetsPayloadSource;
use prometeu_hal::sprite::Sprite;
use prometeu_hal::{
AssetBridge, AudioBridge, InputPlatform, NoopTelemetryPlatform, PadBridge, RenderBackend,
RuntimePlatform, TelemetryPlatform, TouchBridge,
RuntimePlatform, TelemetryPlatform, TouchBridge, WallClock,
};
use prometeu_hal::{
Game2DFrameComposer, Game2DFramePacket, RenderSubmission, RenderSubmissionPacket,
@@ -33,6 +33,7 @@ use std::sync::Arc;
/// - **Audio**: Stereo, Command-based mixing.
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
pub struct Hardware {
wall_clock: Arc<dyn WallClock>,
/// Shared physical memory bank ownership used by peripherals and worker backends.
pub memory_banks: Arc<MemoryBanks>,
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
@@ -49,12 +50,6 @@ pub struct Hardware {
pub assets: AssetManager,
}
impl Default for Hardware {
fn default() -> Self {
Self::new()
}
}
impl Hardware {
fn consume_render_submission(&mut self, submission: &RenderSubmission) {
match &submission.packet {
@@ -159,6 +154,10 @@ impl InputPlatform for Hardware {
static NOOP_TELEMETRY: NoopTelemetryPlatform = NoopTelemetryPlatform;
impl RuntimePlatform for Hardware {
fn wall_clock(&self) -> &dyn WallClock {
self.wall_clock.as_ref()
}
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
self
}
@@ -207,12 +206,15 @@ impl Hardware {
pub const H: usize = 270;
/// Creates a fresh hardware instance with default settings.
pub fn new() -> Self {
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()))
pub fn new(wall_clock: Arc<dyn WallClock>) -> Self {
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()), wall_clock)
}
/// Creates hardware with explicit shared bank ownership.
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
pub fn new_with_memory_banks(
memory_banks: Arc<MemoryBanks>,
wall_clock: Arc<dyn WallClock>,
) -> Self {
let assets = AssetManager::new(
vec![],
AssetsPayloadSource::empty(),
@@ -222,6 +224,7 @@ impl Hardware {
);
let glyph_slot_index = assets.glyph_asset_slot_index();
Self {
wall_clock,
memory_banks: Arc::clone(&memory_banks),
gfx: Gfx::new(
Self::W,
@@ -304,7 +307,10 @@ mod tests {
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
let mut hardware = Hardware::new_with_memory_banks(
Arc::clone(&banks),
Arc::new(crate::ControlledWallClock::default()),
);
let scene = banks.scene_bank_slot(0).expect("scene bank slot 0 should be resident");
let mut cache = SceneViewportCache::new(&scene, 4, 4);
cache.materialize_all_layers(&scene);
@@ -323,7 +329,8 @@ mod tests {
let banks = Arc::new(MemoryBanks::new());
banks.install_scene_bank(2, Arc::new(make_scene()));
let hardware = Hardware::new_with_memory_banks(banks);
let hardware =
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
let scene = hardware
.frame_composer
.scene_bank_slot(2)
@@ -340,7 +347,8 @@ mod tests {
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
let mut hardware = Hardware::new_with_memory_banks(banks);
let mut hardware =
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
let mut glyph_slots = [None; 16];
glyph_slots[0] = Some(0);
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
@@ -370,7 +378,8 @@ mod tests {
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
let mut hardware = Hardware::new_with_memory_banks(banks);
let mut hardware =
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
let mut glyph_slots = [None; 16];
glyph_slots[0] = Some(0);
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
@@ -411,7 +420,7 @@ mod tests {
#[test]
fn render_submission_sink_accepts_owned_game2d_submission() {
let mut hardware = Hardware::new();
let mut hardware = Hardware::new(Arc::new(crate::ControlledWallClock::default()));
let packet = Game2DFramePacket::new(
ComposerFramePacket::default(),
vec![Gfx2dCommand::Clear { color: Color::BLUE }],
@@ -426,7 +435,7 @@ mod tests {
#[test]
fn render_submission_sink_accepts_owned_shell_ui_submission() {
let mut hardware = Hardware::new();
let mut hardware = Hardware::new(Arc::new(crate::ControlledWallClock::default()));
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
let submission = RenderSubmission::shell_ui(FrameId::ZERO, packet);
@@ -440,7 +449,8 @@ mod tests {
fn emit_sprite_rejects_palette_id_outside_loaded_glyph_bank() {
let banks = Arc::new(MemoryBanks::new());
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
let mut hardware = Hardware::new_with_memory_banks(banks);
let mut hardware =
Hardware::new_with_memory_banks(banks, Arc::new(crate::ControlledWallClock::default()));
let status = Game2DFrameComposer::emit_sprite(
&mut hardware,
@@ -8,6 +8,7 @@ mod memory_banks;
mod pad;
mod test_platform;
mod touch;
mod wall_clock;
pub use crate::asset::AssetManager;
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
@@ -20,3 +21,4 @@ pub use crate::memory_banks::{
};
pub use crate::pad::Pad;
pub use crate::test_platform::TestPlatform;
pub use crate::wall_clock::ControlledWallClock;
@@ -1,13 +1,15 @@
use crate::ControlledWallClock;
use crate::hardware::Hardware;
use crate::memory_banks::MemoryBanks;
use prometeu_hal::{
AssetBridge, AudioBridge, Game2DFrameComposer, InputPlatform, RenderBackend,
RenderSubmissionSink, RuntimePlatform, TelemetryPlatform,
RenderSubmissionSink, RuntimePlatform, TelemetryPlatform, WallClock,
};
use std::sync::Arc;
pub struct TestPlatform {
hardware: Hardware,
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
}
impl Default for TestPlatform {
@@ -18,11 +20,24 @@ impl Default for TestPlatform {
impl TestPlatform {
pub fn new() -> Self {
Self { hardware: Hardware::new() }
Self::new_with_memory_banks(Arc::new(MemoryBanks::new()))
}
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
Self { hardware: Hardware::new_with_memory_banks(memory_banks) }
let clock = Arc::new(ControlledWallClock::default());
Self {
hardware: Hardware::new_with_memory_banks(memory_banks, clock.clone()),
controlled_wall_clock: Some(clock),
}
}
pub fn new_with_wall_clock(clock: Arc<dyn WallClock>) -> Self {
Self { hardware: Hardware::new(clock), controlled_wall_clock: None }
}
/// Native controls for the default clock. Injected providers are controlled by their owner.
pub fn controlled_wall_clock(&self) -> Option<&ControlledWallClock> {
self.controlled_wall_clock.as_deref()
}
pub fn local_hardware(&self) -> &Hardware {
@@ -35,6 +50,10 @@ impl TestPlatform {
}
impl RuntimePlatform for TestPlatform {
fn wall_clock(&self) -> &dyn WallClock {
self.hardware.wall_clock()
}
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
self.hardware.render_submission_sink()
}
@@ -97,4 +116,22 @@ mod tests {
assert!(!platform.input().pad().any());
assert!(platform.telemetry().telemetry_snapshot().is_none());
}
#[test]
fn selected_clock_is_shared_with_hardware_and_can_be_injected() {
let platform = TestPlatform::new();
assert_eq!(platform.wall_clock().utc_unix_seconds(), 0);
let clock = platform.controlled_wall_clock().expect("default controls");
clock.set(42);
assert_eq!(platform.local_hardware().wall_clock().utc_unix_seconds(), 42);
clock.advance(3);
assert_eq!(platform.wall_clock().utc_unix_seconds(), 45);
let custom = Arc::new(ControlledWallClock::new(900));
let platform = TestPlatform::new_with_wall_clock(custom.clone());
assert!(platform.controlled_wall_clock().is_none());
assert_eq!(platform.wall_clock().utc_unix_seconds(), 900);
custom.set(7);
assert_eq!(platform.local_hardware().wall_clock().utc_unix_seconds(), 7);
}
}
@@ -0,0 +1,57 @@
use prometeu_hal::WallClock;
use std::sync::atomic::{AtomicU64, Ordering};
/// A native harness-controlled civil clock. Reads and runtime ticks never advance it.
#[derive(Debug, Default)]
pub struct ControlledWallClock {
seconds: AtomicU64,
}
impl ControlledWallClock {
pub fn new(seconds: u64) -> Self {
Self { seconds: AtomicU64::new(seconds) }
}
/// Set civil time explicitly, including backwards adjustments.
pub fn set(&self, seconds: u64) {
self.seconds.store(seconds, Ordering::Relaxed);
}
/// Advance civil time explicitly, saturating at the largest timestamp.
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| {
Some(current.saturating_add(seconds))
});
}
}
impl WallClock for ControlledWallClock {
fn utc_unix_seconds(&self) -> u64 {
self.seconds.load(Ordering::Relaxed)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn explicit_changes_allow_regression_and_saturate_without_advancing_on_read() {
let clock = ControlledWallClock::default();
assert_eq!(clock.utc_unix_seconds(), 0);
clock.set(100);
for _ in 0..10 {
assert_eq!(clock.utc_unix_seconds(), 100);
}
clock.advance(9);
assert_eq!(clock.utc_unix_seconds(), 109);
clock.set(3);
assert_eq!(clock.utc_unix_seconds(), 3);
clock.advance(u64::MAX);
clock.advance(1);
assert_eq!(clock.utc_unix_seconds(), u64::MAX);
clock.set(0);
assert_eq!(clock.utc_unix_seconds(), 0);
}
}
@@ -693,7 +693,10 @@ mod tests {
root.add_game("stress", true);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(discover_games_root(&root.path));
firmware.hub.set_game_library(discover_games_root(
&root.path,
&prometeu_drivers::ControlledWallClock::default(),
));
firmware.tick(&InputSignals::default(), &mut platform);
let signals = InputSignals { f_signal: true, x_pos: 72, y_pos: 90, ..Default::default() };
@@ -714,7 +717,10 @@ mod tests {
root.add_game("stress", true);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(discover_games_root(&root.path));
firmware.hub.set_game_library(discover_games_root(
&root.path,
&prometeu_drivers::ControlledWallClock::default(),
));
firmware.tick(&InputSignals::default(), &mut platform);
let signals = InputSignals { f_signal: true, x_pos: 72, y_pos: 90, ..Default::default() };
@@ -732,7 +738,10 @@ mod tests {
root.add_game("stress", true);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(discover_games_root(&root.path));
firmware.hub.set_game_library(discover_games_root(
&root.path,
&prometeu_drivers::ControlledWallClock::default(),
));
firmware.tick(&InputSignals::default(), &mut platform);
let launch_click =
@@ -787,7 +796,10 @@ mod tests {
root.add_game_with_identity("zzz-dummy", 43, "Zzz Dummy", "1.0.0", true);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(discover_games_root(&root.path));
firmware.hub.set_game_library(discover_games_root(
&root.path,
&prometeu_drivers::ControlledWallClock::default(),
));
firmware.tick(&InputSignals::default(), &mut platform);
let stress_click =
@@ -848,7 +860,10 @@ mod tests {
#[test]
fn repository_stress_to_dummy_boy_switch_is_end_to_end() {
let library = discover_games_root(repository_test_cartridges_root());
let library = discover_games_root(
repository_test_cartridges_root(),
&prometeu_drivers::ControlledWallClock::default(),
);
assert!(
library
.entries()
@@ -1036,7 +1051,10 @@ mod tests {
#[test]
fn resident_game_termination_closes_session_and_cleans_runtime_state() {
let library = discover_games_root(repository_test_cartridges_root());
let library = discover_games_root(
repository_test_cartridges_root(),
&prometeu_drivers::ControlledWallClock::default(),
);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(library);
firmware.tick(&InputSignals::default(), &mut platform);
@@ -1121,7 +1139,10 @@ mod tests {
#[test]
fn hub_kill_control_click_terminates_resident_game_and_stays_home() {
let library = discover_games_root(repository_test_cartridges_root());
let library = discover_games_root(
repository_test_cartridges_root(),
&prometeu_drivers::ControlledWallClock::default(),
);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(library);
firmware.tick(&InputSignals::default(), &mut platform);
@@ -1213,7 +1234,10 @@ mod tests {
root.add_game_with_program("zzz-broken", 43, "Zzz Broken", "1.0.0", Some(vec![0, 0, 0, 0]));
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(discover_games_root(&root.path));
firmware.hub.set_game_library(discover_games_root(
&root.path,
&prometeu_drivers::ControlledWallClock::default(),
));
firmware.tick(&InputSignals::default(), &mut platform);
let stress_click =
@@ -1279,7 +1303,8 @@ mod tests {
root.add_game("broken", false);
let (mut firmware, mut platform) = hub_home_firmware();
let library = discover_games_root(&root.path);
let library =
discover_games_root(&root.path, &prometeu_drivers::ControlledWallClock::default());
assert!(library.is_empty());
assert!(!library.diagnostics().is_empty());
firmware.hub.set_game_library(library);
@@ -1319,7 +1344,10 @@ mod tests {
let cart = root.add_game("stress", true);
let (mut firmware, mut platform) = hub_home_firmware();
firmware.hub.set_game_library(discover_games_root(&root.path));
firmware.hub.set_game_library(discover_games_root(
&root.path,
&prometeu_drivers::ControlledWallClock::default(),
));
fs::remove_file(cart.join("program.pbx")).expect("program should be removable");
firmware.tick(&InputSignals::default(), &mut platform);
+2
View File
@@ -38,6 +38,7 @@ pub mod tilemap;
pub mod touch_bridge;
pub mod value_snapshot;
pub mod vm_fault;
pub mod wall_clock;
pub use asset_bridge::AssetBridge;
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
@@ -66,3 +67,4 @@ pub use render_worker::{
};
pub use touch_bridge::TouchBridge;
pub use value_snapshot::ValueSnapshot;
pub use wall_clock::WallClock;
@@ -6,6 +6,7 @@ use crate::render_submission::{Game2DFramePacket, RenderSubmission};
use crate::sprite::Sprite;
use crate::telemetry::TelemetryFrame;
use crate::touch_bridge::TouchBridge;
use crate::wall_clock::WallClock;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderSubmitError {
@@ -60,6 +61,8 @@ pub struct NoopTelemetryPlatform;
impl TelemetryPlatform for NoopTelemetryPlatform {}
pub trait RuntimePlatform {
fn wall_clock(&self) -> &dyn WallClock;
fn display_size(&self) -> (usize, usize) {
(480, 270)
}
@@ -0,0 +1,11 @@
/// Host civil time for administrative timestamps, independent of gameplay and deadlines.
///
/// Reads must be local and bounded, without waiting for IO or clock synchronization.
/// The host always supplies a value, even when its civil clock is incorrect.
pub trait WallClock {
/// Whole UTC seconds since the Unix epoch, with fractions discarded.
///
/// Values outside the unsigned range saturate to zero or `u64::MAX`.
/// Successive reads may go backwards when the host adjusts its clock.
fn utc_unix_seconds(&self) -> u64;
}
@@ -619,7 +619,7 @@ mod tests {
app_id: 42,
app_version: "1.0.0".to_string(),
path: PathBuf::from("test-cartridges/stress-console"),
discovered_at: std::time::SystemTime::UNIX_EPOCH,
discovered_at: 0,
};
let action = action_for_click(
@@ -1,8 +1,8 @@
use prometeu_hal::WallClock;
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::cartridge::CartridgeManifest;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
#[derive(Debug, Clone)]
pub struct GameLibraryEntry {
@@ -11,11 +11,12 @@ pub struct GameLibraryEntry {
pub app_id: u32,
pub app_version: String,
pub path: PathBuf,
pub discovered_at: SystemTime,
/// UTC seconds sampled once for the discovery scan, from the selected host clock.
pub discovered_at: u64,
}
impl GameLibraryEntry {
fn new(path: PathBuf, manifest: CartridgeManifest, discovered_at: SystemTime) -> Self {
fn new(path: PathBuf, manifest: CartridgeManifest, discovered_at: u64) -> Self {
Self {
title: manifest.title.clone(),
app_id: manifest.app_id,
@@ -91,9 +92,9 @@ impl GameLibrary {
}
}
pub fn discover_games_root(root: impl AsRef<Path>) -> GameLibrary {
pub fn discover_games_root(root: impl AsRef<Path>, wall_clock: &dyn WallClock) -> GameLibrary {
let root = root.as_ref();
let discovered_at = SystemTime::now();
let discovered_at = wall_clock.utc_unix_seconds();
if !root.is_dir() {
return GameLibrary {
@@ -153,7 +154,7 @@ pub fn discover_games_root(root: impl AsRef<Path>) -> GameLibrary {
fn discover_candidate(
path: &Path,
discovered_at: SystemTime,
discovered_at: u64,
) -> Result<GameLibraryEntry, GameLibraryDiagnosticReason> {
let manifest_path = path.join("manifest.json");
if !manifest_path.exists() {
@@ -185,8 +186,26 @@ fn discover_candidate(
mod tests {
use super::*;
use serde_json::json;
use std::cell::Cell;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::UNIX_EPOCH;
struct CountingClock {
seconds: Cell<u64>,
calls: Cell<usize>,
}
impl CountingClock {
fn new(seconds: u64) -> Self {
Self { seconds: Cell::new(seconds), calls: Cell::new(0) }
}
}
impl WallClock for CountingClock {
fn utc_unix_seconds(&self) -> u64 {
self.calls.set(self.calls.get() + 1);
self.seconds.get()
}
}
static TEST_DIR_COUNTER: AtomicU64 = AtomicU64::new(0);
@@ -254,7 +273,7 @@ mod tests {
fs::write(nested_parent.join("nested-game").join("program.pbx"), [0_u8])
.expect("nested program should be written");
let library = discover_games_root(&root.path);
let library = discover_games_root(&root.path, &CountingClock::new(123));
assert_eq!(library.entries().len(), 2);
assert_eq!(library.entries()[0].title, "Alpha");
@@ -262,7 +281,7 @@ mod tests {
assert_eq!(library.entries()[0].app_version, "1.0.0");
assert_eq!(library.entries()[0].manifest.app_mode, AppMode::Game);
assert!(library.entries()[0].path.ends_with("alpha"));
assert!(library.entries()[0].discovered_at >= UNIX_EPOCH);
assert_eq!(library.entries()[0].discovered_at, 123);
assert_eq!(library.entries()[1].title, "Zeta");
assert!(library.diagnostics().iter().any(|diagnostic| {
@@ -293,7 +312,7 @@ mod tests {
app_mode: AppMode::Game,
capabilities: vec![],
},
UNIX_EPOCH,
0,
);
let target = entry.switch_target();
@@ -309,7 +328,7 @@ mod tests {
let root = TestRoot::new();
let missing = root.path.join("missing");
let library = discover_games_root(&missing);
let library = discover_games_root(&missing, &CountingClock::new(0));
assert!(library.is_empty());
assert_eq!(library.diagnostics().len(), 1);
@@ -321,7 +340,7 @@ mod tests {
let games_root =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..").join("test-cartridges");
let library = discover_games_root(games_root);
let library = discover_games_root(games_root, &CountingClock::new(0));
let entries = library.entries();
assert!(entries.iter().any(|entry| {
@@ -333,4 +352,24 @@ mod tests {
entry.app_id == 2 && entry.title == "Dummy Boy" && entry.path.ends_with("dummy-boy")
}));
}
#[test]
fn discovery_samples_once_per_scan_and_preserves_adjustments_and_full_range() {
let root = TestRoot::new();
root.add_candidate("zeta", manifest("Zeta", 2, "Game"), true);
root.add_candidate("alpha", manifest("Alpha", 1, "Game"), true);
let clock = CountingClock::new(u64::MAX);
let first = discover_games_root(&root.path, &clock);
assert_eq!(clock.calls.get(), 1);
assert_eq!(first.entries().len(), 2);
assert!(first.entries().iter().all(|entry| entry.discovered_at == u64::MAX));
clock.seconds.set(7);
let second = discover_games_root(&root.path, &clock);
assert_eq!(clock.calls.get(), 2);
assert!(second.entries().iter().all(|entry| entry.discovered_at == 7));
assert_eq!(second.entries()[0].app_id, 1);
assert_eq!(second.entries()[1].app_id, 2);
assert!(first.entries().iter().all(|entry| entry.discovered_at == u64::MAX));
}
}