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
@@ -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");