commit 1a8bc7d1b9ae247e958408e478b306d86e1d1003
parent ee0915aef8fa778ebb3e527397a2b3fa14d17840
Author: triesap <tyson@radroots.org>
Date: Mon, 21 Sep 2026 13:03:06 +0000
runtime: add deterministic wall and monotonic clock ports
Diffstat:
2 files changed, 68 insertions(+), 0 deletions(-)
diff --git a/src/hyf_runtime/clock.mojo b/src/hyf_runtime/clock.mojo
@@ -0,0 +1,46 @@
+from std.ffi import c_long, external_call
+from std.time import perf_counter_ns
+
+
+@fieldwise_init
+struct Clock(Copyable, Movable):
+ var wall_epoch_seconds: Int
+ var monotonic_ns: Int
+
+
+def fixed_clock(wall_epoch_seconds: Int, monotonic_ns: Int) -> Clock:
+ return Clock(wall_epoch_seconds=wall_epoch_seconds, monotonic_ns=monotonic_ns)
+
+
+def advance(clock: Clock, monotonic_delta_ns: Int) -> Clock:
+ return Clock(
+ wall_epoch_seconds=clock.wall_epoch_seconds,
+ monotonic_ns=clock.monotonic_ns + monotonic_delta_ns,
+ )
+
+
+def clock_wall_epoch_seconds(clock: Clock) -> Int:
+ return clock.wall_epoch_seconds
+
+
+def clock_monotonic_ns(clock: Clock) -> Int:
+ return clock.monotonic_ns
+
+
+def monotonic_elapsed_ns(start: Clock, end: Clock) -> Int:
+ return end.monotonic_ns - start.monotonic_ns
+
+
+def system_wall_epoch_seconds() -> Int:
+ return Int(external_call["time", c_long](0))
+
+
+def system_monotonic_ns() -> Int:
+ return Int(perf_counter_ns())
+
+
+def system_clock() -> Clock:
+ return Clock(
+ wall_epoch_seconds=system_wall_epoch_seconds(),
+ monotonic_ns=system_monotonic_ns(),
+ )
diff --git a/tests/test_assist.mojo b/tests/test_assist.mojo
@@ -44,3 +44,25 @@ def test_typed_answers_and_score_normalization() raises:
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
+
+
+from hyf_runtime.clock import (
+ Clock,
+ advance,
+ clock_monotonic_ns,
+ clock_wall_epoch_seconds,
+ fixed_clock,
+ monotonic_elapsed_ns,
+ system_monotonic_ns,
+ system_wall_epoch_seconds,
+)
+
+
+def test_clock_ports_are_injectable_and_monotonic() raises:
+ var start = fixed_clock(1789000000, 1000)
+ assert_equal(clock_wall_epoch_seconds(start), 1789000000)
+ var end = advance(start, 5000)
+ assert_equal(clock_monotonic_ns(end), 6000)
+ assert_equal(monotonic_elapsed_ns(start, end), 5000)
+ assert_true(system_wall_epoch_seconds() > 1600000000)
+ assert_true(system_monotonic_ns() > 0)