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));
}
}
@@ -24,3 +24,7 @@ cpal = "0.15.3"
ringbuf = "0.4.7"
serde_json = "1.0.149"
clap = { version = "4.5", features = ["derive"] }
[[bench]]
name = "wall_clock"
harness = false
@@ -0,0 +1,37 @@
use prometeu_drivers::ControlledWallClock;
use prometeu_hal::WallClock;
use prometeu_host_desktop_winit::wall_clock::SystemWallClock;
use std::hint::black_box;
use std::time::Instant;
fn measure(name: &str, clock: &dyn WallClock) {
const BATCHES: usize = 101;
const READS: usize = 10_000;
for _ in 0..READS {
black_box(black_box(clock).utc_unix_seconds());
}
let mut samples = Vec::with_capacity(BATCHES);
for _ in 0..BATCHES {
let start = Instant::now();
for _ in 0..READS {
black_box(black_box(clock).utc_unix_seconds());
}
samples.push(start.elapsed().as_nanos() as f64 / READS as f64);
}
samples.sort_by(f64::total_cmp);
println!(
"{name}: batches={BATCHES} reads_per_batch={READS} ns/read batch_mean p50={:.2} p95={:.2} max={:.2}",
samples[50], samples[95], samples[100]
);
}
fn main() {
println!(
"target={}-{} debug_assertions={}; batch means include dynamic dispatch and loop overhead",
std::env::consts::ARCH,
std::env::consts::OS,
cfg!(debug_assertions)
);
measure("system", &SystemWallClock);
measure("controlled", &ControlledWallClock::new(1_000));
}
@@ -7,6 +7,7 @@ pub mod log_sink;
pub mod runner;
pub mod stats;
pub mod utilities;
pub mod wall_clock;
use cap::load_cap_config;
use clap::Parser;
@@ -163,7 +163,7 @@ impl HostRunner {
}
pub(crate) fn set_games_root(&mut self, games_root: String) {
let library = discover_games_root(&games_root);
let library = discover_games_root(&games_root, self.hardware.wall_clock());
for diagnostic in library.diagnostics() {
eprintln!(
"games-root: omitted candidate {}: {:?}",
@@ -185,7 +185,10 @@ impl HostRunner {
}
let memory_banks = Arc::new(MemoryBanks::new());
let hardware = Hardware::new_with_memory_banks(Arc::clone(&memory_banks));
let hardware = Hardware::new_with_memory_banks(
Arc::clone(&memory_banks),
Arc::new(crate::wall_clock::SystemWallClock),
);
let display_size = hardware.display_size();
let worker_backend = LocalFramebufferRenderBackend::new_with_memory_banks(
display_size.0,
@@ -0,0 +1,52 @@
use prometeu_hal::WallClock;
use std::time::{SystemTime, UNIX_EPOCH};
/// Desktop civil time. Synchronization and clock adjustments belong to the OS.
#[derive(Debug, Default)]
pub struct SystemWallClock;
impl WallClock for SystemWallClock {
fn utc_unix_seconds(&self) -> u64 {
seconds_from_system_time(SystemTime::now())
}
}
fn seconds_from_system_time(time: SystemTime) -> u64 {
match time.duration_since(UNIX_EPOCH) {
Ok(duration) => seconds_from_unix_nanos(duration.as_nanos()),
Err(_) => 0,
}
}
fn seconds_from_unix_nanos(nanos: u128) -> u64 {
u64::try_from(nanos / 1_000_000_000).unwrap_or(u64::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn conversion_truncates_fractions_and_saturates_at_both_limits() {
assert_eq!(seconds_from_system_time(UNIX_EPOCH), 0);
assert_eq!(seconds_from_system_time(UNIX_EPOCH - Duration::from_nanos(1)), 0);
assert_eq!(seconds_from_system_time(UNIX_EPOCH - Duration::from_secs(1)), 0);
assert_eq!(seconds_from_system_time(UNIX_EPOCH + Duration::from_millis(999)), 0);
assert_eq!(seconds_from_system_time(UNIX_EPOCH + Duration::from_millis(1_900)), 1);
let limit = u128::from(u64::MAX) * 1_000_000_000;
assert_eq!(seconds_from_unix_nanos(limit - 1), u64::MAX - 1);
assert_eq!(seconds_from_unix_nanos(limit), u64::MAX);
assert_eq!(seconds_from_unix_nanos(limit + 1_000_000_000), u64::MAX);
assert_eq!(seconds_from_unix_nanos(u128::MAX), u64::MAX);
}
#[test]
fn system_provider_reads_current_local_time() {
let before = seconds_from_system_time(SystemTime::now());
let actual = SystemWallClock.utc_unix_seconds();
let after = seconds_from_system_time(SystemTime::now());
// A wall-clock adjustment may reverse the bounding samples.
assert!((before.min(after)..=before.max(after)).contains(&actual));
}
}
+32 -3
View File
@@ -1,14 +1,14 @@
use std::fmt;
use std::sync::Arc;
use prometeu_drivers::MemoryBanks;
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,
RuntimePlatform, TelemetryPlatform, WallClock,
};
use prometeu_system::{CrashReport, LatestRenderFrameStore};
@@ -103,6 +103,7 @@ pub struct HeadlessHost {
signals: InputSignals,
boot_attempted: bool,
last_completed_frame: Option<CompletedFrame>,
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
}
#[derive(Debug, Clone, Copy)]
@@ -118,8 +119,21 @@ struct HeadlessPlatform {
impl HeadlessHost {
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));
let hardware = Hardware::new_with_memory_banks(Arc::clone(&memory_banks), clock);
let store = LatestRenderFrameStore::default();
Self {
firmware: Firmware::new(None),
@@ -127,9 +141,20 @@ impl HeadlessHost {
signals: InputSignals::default(),
boot_attempted: false,
last_completed_frame: None,
controlled_wall_clock,
}
}
/// 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()
}
/// Load `path` and tick until the firmware is in `GameRunning`.
///
/// The transition into `GameRunning` is the last tick. The first game
@@ -384,6 +409,10 @@ impl RenderSubmissionSink for HeadlessPlatform {
}
impl RuntimePlatform for HeadlessPlatform {
fn wall_clock(&self) -> &dyn WallClock {
self.hardware.wall_clock()
}
fn display_size(&self) -> (usize, usize) {
(Hardware::W, Hardware::H)
}
@@ -20,6 +20,48 @@ const BLUE: u32 = Color::BLUE.raw();
const GREEN: u32 = Color::GREEN.raw();
const BLACK: u32 = Color::BLACK.raw();
#[test]
fn controlled_civil_time_is_independent_of_frames_pause_and_reset() {
let cartridge = color_cartridge();
for _ in 0..2 {
let mut host = HeadlessHost::new();
assert_eq!(host.wall_clock().utc_unix_seconds(), 0);
host.controlled_wall_clock().unwrap().set(1_000);
host.boot(&cartridge).expect("boot");
host.advance_frames(3).expect("frames");
assert_eq!(host.wall_clock().utc_unix_seconds(), 1_000);
host.pause().expect("pause");
host.controlled_wall_clock().unwrap().advance(60);
host.resume().expect("resume");
assert_eq!(host.wall_clock().utc_unix_seconds(), 1_060);
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();
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
host.boot(&cartridge).expect("reboot");
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
}
}
#[test]
fn injected_civil_clock_remains_the_runtime_source_across_lifecycle() {
use prometeu_drivers::ControlledWallClock;
use std::sync::Arc;
let clock = Arc::new(ControlledWallClock::new(u64::MAX));
let mut host = HeadlessHost::new_with_wall_clock(clock.clone());
assert!(host.controlled_wall_clock().is_none());
host.boot(color_cartridge()).expect("boot");
host.advance_frame().expect("frame");
assert_eq!(host.wall_clock().utc_unix_seconds(), u64::MAX);
clock.set(42);
assert_eq!(host.wall_clock().utc_unix_seconds(), 42);
host.reset();
clock.advance(3);
assert_eq!(host.wall_clock().utc_unix_seconds(), 45);
}
#[test]
fn headless_source_has_no_timing_wait_or_interactive_backend_dependency() {
let source = include_str!("../src/host.rs");
@@ -0,0 +1,129 @@
---
id: LSN-0065
ticket: host-clock-interface-for-runtime-utc-timestamps
title: Civil Time Is Not Ordering or Elapsed Time
created: 2026-10-13
tags: [clock, host, runtime]
---
## Context
The published runtime now obtains administrative civil time from a host-selected
`WallClock` through `RuntimePlatform`. Desktop uses its OS clock; headless and
test platforms default to an explicitly controlled source. Game-library discovery
uses this interface for its `discovered_at` values.
Source record: the accepted DEC-0053 contract was executed by PLN-0184, originating
in AGD-0066 / DSC-0063. The workflow artifacts were completed and pruned after
publication. The normative reference is the
[administrative host wall-clock contract](../../../docs/specs/runtime/11-portability-and-cross-platform-execution.md#41-administrative-host-wall-clock).
This lesson explains that implemented boundary; it does not replace the spec.
## Three Clocks Answer Three Different Questions
Civil time answers what date the host reports. Monotonic elapsed time answers
how long an operation has been running. Logical runtime time answers how many
machine frames or cycles have executed. These meanings remain separate even
when one OS supplies their underlying mechanisms.
Moving a civil clock backwards is a normal administrative adjustment. Keeping
the maximum of previous readings would hide that adjustment and produce an
invented date. Conversely, using that civil clock for a timeout could extend or
shorten the operation's allowance. Sequences, rather than timestamps, identify
publication order; monotonic elapsed time drives host deadlines; logical cycles
preserve gameplay behavior.
A clock that is always present need not be accurate. The implemented interface
returns a number even when the system date is wrong. Range handling saturates
pre-epoch values to zero and overflow to u64::MAX. These endpoints are dates in
the chosen representation, not errors or unavailable-source indicators. None of
these properties makes timestamps unique IDs.
## Provider Ownership Is Part of the Boundary
The [HAL trait](../../../crates/console/prometeu-hal/src/wall_clock.rs) is deliberately
small. [Hardware](../../../crates/console/prometeu-drivers/src/hardware.rs) requires
an explicitly supplied provider and delegates reads to it. This keeps the
runtime from silently selecting an OS clock while a wrapper advertises a fake.
The [desktop provider](../../../crates/host/prometeu-host-desktop-winit/src/wall_clock.rs)
reads local SystemTime and converts at the boundary. Its read does not enqueue
work or depend on an IO worker. The
[controlled provider](../../../crates/console/prometeu-drivers/src/wall_clock.rs)
uses one atomic load per read; native set and saturating advance are explicit.
Clock synchronization is not part of the read path.
The headless API retains the selected source across runtime lifecycle changes.
`controlled_wall_clock()` exposes controls for the default fake; it returns
None for a caller-injected provider because the caller owns those controls.
That optional control handle is not an optional timestamp: the selected source
always returns u64.
## Deterministic Tests Control Civil Time Independently
A fake that advances on every read makes behavior depend on how often code
inspects time. A fake tied to frames cannot independently simulate a paused game
whose system clock continues, or a user correcting the date backwards. The
implemented fake therefore changes only through native set/advance controls.
For example, a harness can set the clock to 1,000, advance several game frames
and still read 1,000. It can pause the game, advance civil time by 60 seconds,
and observe 1,060 after resume. Setting the source back to 10 leaves publication
ordering and logical execution untouched. Resetting the runtime does not
replace the host-owned source.
The [headless integration tests](../../../crates/host/prometeu-host-headless/tests/deterministic_control.rs)
exercise this timeline twice and also verify injected-source ownership across
lifecycle operations.
## Sample Once for One Administrative Event
[Game discovery](../../../crates/console/prometeu-system/src/services/game_library.rs)
reads the selected clock once per scan and assigns the resulting u64 to every
entry. A scan is one administrative event; sampling separately for each entry
would make timestamp differences depend on enumeration and disk timing.
A counting provider verifies the single sample, and a later scan after a
backwards adjustment records the new date. The maximum u64 value passes through
without reconstruction as an OS time type. Existing sorting, diagnostics and
launch behavior remain covered by the runtime/firmware tests.
## Validation and Performance Evidence
Executed on macOS/aarch64 (`aarch64-apple-darwin`), rustc 1.98.1, on 2026-10-13:
- `cargo fmt -- --check`: passed.
- `cargo clippy --workspace --all-features`: passed without warnings.
- `cargo test --workspace --all-targets --all-features --no-fail-fast`: 946 passed,
zero failed, nine existing ignored tests across 53 reported test suites.
- `cargo bench -p prometeu-host-desktop-winit --bench wall_clock`: optimized local
dynamic-dispatch benchmark, 101 batches of 10,000 reads after warm-up.
- Documentation workflow-reference scan, lesson-link checks, `git diff --check`
and discussion validation passed.
| Provider | Median batch mean, ns/read | p95 batch mean | Maximum batch mean |
| --- | ---: | ---: | ---: |
| OS civil clock | 30.83 | 57.14 | 138.00 |
| Controlled clock | 0.93 | 3.30 | 4.52 |
These measurements include loop/dynamic-dispatch overhead. They are observed
batch averages under local validation load, not per-call tail guarantees,
worst-case latency bounds, or qualification of a handheld/other OS. The
[benchmark source](../../../crates/host/prometeu-host-desktop-winit/benches/wall_clock.rs)
allows the same experiment on another host. Inspection of the provider paths
establishes the absence of disk/network/async-work waits; fast timings alone
would not establish that property.
## Consumer Boundaries
The generic clock and library consumer are delivered. Memory-card timestamp
publication, slot aggregation under clock regressions, identity generation and
legacy-format transition remain work of the memory-card discussion. The old
save UUID path uses nanoseconds; mechanically replacing it with whole seconds
would not establish a sound identity policy. Temporary-path naming in test and
benchmark infrastructure and monotonic host clocks were outside this migration.
The useful pattern is to publish the small provider contract, demonstrate a real
consumer and deterministic tests, and leave each further consumer responsible
for when it captures and persists the reading. Completion of a source service
is not completion of all its consumers.
@@ -19,6 +19,11 @@ It covers:
## 2 System Base Clock
Administrative UTC timestamps use the separate
[host wall clock](11-portability-and-cross-platform-execution.md#41-administrative-host-wall-clock).
Civil clock adjustments do not change logical time or cycle accounting. Host
timeouts use monotonic elapsed time, independent of that adjustable civil clock.
PROMETEU operates with a fixed **60 Hz** logical clock.
This means:
@@ -51,6 +51,7 @@ The contract is about logical behavior, not identical physical latency or throug
- audio output
- physical input collection
- access to the sandbox file system
- a local civil clock for administrative UTC timestamps
- technical inspection and debugger integrations that do not modify presented
Game or Shell pixels
@@ -68,14 +69,71 @@ PROMETEU guarantees determinism through:
## 4 Independence from Real Hardware
PROMETEU **does not use**:
Deterministic gameplay and cycle accounting **do not depend on**:
- operating system timers
- high-resolution clocks
- CPU-specific instructions
- uncontrolled graphics acceleration
All performance is measured in **PROMETEU cycles**, not in milliseconds.
Guest execution cost is measured in **PROMETEU cycles**. Native host cost
measurements do not redefine those weights.
Host administration can read civil time through the interface below. Host
deadlines and diagnostics can measure monotonic elapsed time; neither source
changes guest cycle weights or logical frame advancement.
### 4.1 Administrative host wall clock
Didactic companion: [Civil time, ordering and elapsed time](../../../discussion/lessons/DSC-0063-host-clock-interface-for-runtime-utc-timestamps/LSN-0065-civil-time-is-not-ordering-or-elapsed-time.md).
The HAL defines `WallClock::utc_unix_seconds(&self) -> u64`.
`RuntimePlatform::wall_clock(&self) -> &dyn WallClock` MUST return the
host-selected provider. The host MUST keep that provider alive while the
platform uses it. A missing provider MUST NOT be hidden behind a default zero
timestamp. Hardware aggregates and platform wrappers delegate to the selected
source; they do not select an OS clock on the runtime's behalf.
The result is whole UTC seconds since `1970-01-01T00:00:00Z`, with fractional
seconds discarded. Hosts MUST saturate pre-epoch dates to `0` and values above
the unsigned range to `u64::MAX`, without wrapping or panicking. Both endpoints
are timestamps, not error sentinels. A provider always returns a value: an
incorrect system date does not become an absent clock. This interface does not
certify synchronization, authenticity, accuracy, uniqueness, or commit order.
A read MUST be synchronous, local and bounded. It MUST NOT wait for disk,
network, `async_work`, external time synchronization, a worker, or an unbounded
lock. Hosts may maintain local clock state, but MUST reflect civil adjustments,
including backward changes. Repeated reads within a second can be equal.
Real civil time continues during game pause; resume observes current host time.
Host deadlines MUST use their monotonic source rather than this adjustable
clock. No guest time syscall is introduced.
The desktop provider reads the OS clock locally. The headless host and
`TestPlatform` default to a controlled clock at epoch zero. Its native `set`
operation allows backward changes; `advance` adds seconds with saturation.
Reads, ticks, frames, pause/resume and runtime reset MUST NOT implicitly advance
or replace that controlled source. A harness can explicitly advance it while
the game is paused. These native controls do not extend remote automation or
guest capabilities.
Headless supports an explicitly injected `WallClock`, including a real source,
without depending on the desktop host crate. `controlled_wall_clock()` exposes
the default provider's controls; for an injected provider it returns `None`
because the caller owns its controls. The clock reading itself is always a
`u64`. `new_with_wall_clock(...)` preserves the injected source across lifecycle
operations. Future handheld hosts MUST supply their own conforming provider;
desktop/headless support does not qualify an unimplemented hardware backend.
Game-library discovery captures one reading per scan and stores it as the
`u64` `discovered_at` of each entry. This field is not converted back into an
OS-specific time type. Memory-card timestamp integration is a separate pending
consumer; the existing save-identity path is not migrated by the clock service.
Provider qualification MUST check numerical limits, adjustment behavior,
local access without IO waits, deterministic controls and native read cost on
the executed host/profile. Batch timing observations are not universal latency
or individual-read worst-case guarantees.
## 5 Floating Point Precision
@@ -99,7 +99,10 @@ The Hub does not execute bytecode directly. It always delegates execution setup
For v1, the local games library is Game-only. Hub/Home must not expose Shell or
System cartridges from the games root. The internal library entry must retain
the loaded manifest data, `title`, `app_id`, `app_version`, the cartridge path,
and discovery metadata such as a timestamp or equivalent discovery marker.
and `discovered_at` as unsigned 64-bit UTC seconds from the selected
[host wall clock](11-portability-and-cross-platform-execution.md#41-administrative-host-wall-clock).
Discovery captures one reading per scan and assigns it to every entry in that
scan. A later scan samples the clock again, including any backward adjustment.
The Home UI may display only `title`, `app_id`, and `app_version`. Path and
operational metadata may remain internal.