From 91629e8548064011430373692cd5d4aef8d3fb61 Mon Sep 17 00:00:00 2001 From: Abhinav Sharma Date: Wed, 4 Mar 2026 00:00:58 +0530 Subject: [PATCH 1/5] fix: Make StdClock monotonic using std::time::Instant --- core/engine/src/builtins/date/mod.rs | 6 +- .../src/builtins/intl/date_time_format/mod.rs | 2 +- core/engine/src/builtins/temporal/now.rs | 7 +- core/engine/src/context/mod.rs | 2 +- core/engine/src/context/time.rs | 134 +++++++++++++++--- 5 files changed, 123 insertions(+), 28 deletions(-) diff --git a/core/engine/src/builtins/date/mod.rs b/core/engine/src/builtins/date/mod.rs index f730ba82724..cb6b81944d4 100644 --- a/core/engine/src/builtins/date/mod.rs +++ b/core/engine/src/builtins/date/mod.rs @@ -50,7 +50,7 @@ impl Date { /// Creates a new `Date` from the current UTC time of the host. pub(crate) fn utc_now(context: &mut Context) -> Self { - Self(context.clock().now().millis_since_epoch() as f64) + Self(context.clock().system_time_millis() as f64) } } @@ -210,7 +210,7 @@ impl BuiltInConstructor for Date { // 1. If NewTarget is undefined, then if new_target.is_undefined() { // a. Let now be the time value (UTC) identifying the current time. - let now = context.clock().now().millis_since_epoch(); + let now = context.clock().system_time_millis(); // b. Return ToDateString(now). return Ok(JsValue::from(to_date_string_t( @@ -328,7 +328,7 @@ impl Date { /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now #[allow(clippy::unnecessary_wraps)] pub(crate) fn now(_: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult { - Ok(JsValue::new(context.clock().now().millis_since_epoch())) + Ok(JsValue::new(context.clock().system_time_millis())) } /// `Date.parse()` diff --git a/core/engine/src/builtins/intl/date_time_format/mod.rs b/core/engine/src/builtins/intl/date_time_format/mod.rs index 4e1460aa4ff..9a42c3701ee 100644 --- a/core/engine/src/builtins/intl/date_time_format/mod.rs +++ b/core/engine/src/builtins/intl/date_time_format/mod.rs @@ -257,7 +257,7 @@ impl DateTimeFormat { // NOTE (nekevss) i64 should be sufficient for a millisecond // representation. // a. Let x be ! Call(%Date.now%, undefined). - context.clock().now().millis_since_epoch() as f64 + context.clock().system_time_millis() as f64 // 4. Else, } else { // NOTE (nekevss) The i64 covers all MAX_SAFE_INTEGER values. diff --git a/core/engine/src/builtins/temporal/now.rs b/core/engine/src/builtins/temporal/now.rs index f4d42a5721c..0b075097d11 100644 --- a/core/engine/src/builtins/temporal/now.rs +++ b/core/engine/src/builtins/temporal/now.rs @@ -213,9 +213,10 @@ impl HostHooks for &Context {} impl HostClock for &Context { fn get_host_epoch_nanoseconds(&self) -> TemporalResult { - Ok(EpochNanoseconds::from( - self.clock().now().nanos_since_epoch() as i128, - )) + // Temporal needs actual Unix epoch time, not monotonic time + let millis = self.clock().system_time_millis(); + let nanos = millis as i128 * 1_000_000; + Ok(EpochNanoseconds::from(nanos)) } } diff --git a/core/engine/src/context/mod.rs b/core/engine/src/context/mod.rs index e1e426ec6bb..b9791334283 100644 --- a/core/engine/src/context/mod.rs +++ b/core/engine/src/context/mod.rs @@ -1201,7 +1201,7 @@ impl ContextBuilder { let root_shape = RootShape::default(); let host_hooks = self.host_hooks.unwrap_or(Rc::new(DefaultHooks)); - let clock = self.clock.unwrap_or_else(|| Rc::new(StdClock)); + let clock = self.clock.unwrap_or_else(|| Rc::new(StdClock::new())); let realm = Realm::create(host_hooks.as_ref(), &root_shape)?; let vm = Vm::new(realm); diff --git a/core/engine/src/context/time.rs b/core/engine/src/context/time.rs index b7f04969282..4da59fe701b 100644 --- a/core/engine/src/context/time.rs +++ b/core/engine/src/context/time.rs @@ -4,14 +4,18 @@ /// /// This type is guaranteed to be monotonic, i.e. if two instants /// are compared, the later one will always be greater than the -/// earlier one. It is also always guaranteed to be greater than -/// or equal to the Unix epoch. +/// earlier one. +/// +/// This mirrors the behavior of [`std::time::Instant`] and represents +/// a measurement of elapsed time relative to an arbitrary starting point. +/// It is NOT tied to wall-clock time or the Unix epoch, and system clock +/// adjustments will not affect it. /// /// This should not be used to keep dates or times, but only to -/// measure the current time in the engine. +/// measure monotonic time progression in the engine. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct JsInstant { - /// The duration of time since the Unix epoch. + /// The duration of time since an arbitrary starting point. inner: std::time::Duration, } @@ -29,13 +33,21 @@ impl JsInstant { Self { inner } } - /// Returns the number of milliseconds since the Unix epoch. + /// Returns the number of milliseconds since the clock's starting point. + /// + /// Note: This is NOT a Unix timestamp. It represents elapsed time + /// since an arbitrary starting point and is only meaningful for + /// measuring durations and comparing instants. #[must_use] pub fn millis_since_epoch(&self) -> u64 { self.inner.as_millis() as u64 } - /// Returns the number of nanoseconds since the Unix epoch. + /// Returns the number of nanoseconds since the clock's starting point. + /// + /// Note: This is NOT a Unix timestamp. It represents elapsed time + /// since an arbitrary starting point and is only meaningful for + /// measuring durations and comparing instants. #[must_use] pub fn nanos_since_epoch(&self) -> u128 { self.inner.as_nanos() @@ -131,22 +143,61 @@ impl std::ops::Sub for JsInstant { /// Implement a clock that can be used to measure time. pub trait Clock { - /// Returns the current time. + /// Returns the current monotonic time. + /// + /// This is guaranteed to be monotonic and should be used for measuring + /// durations and scheduling timeouts. fn now(&self) -> JsInstant; + + /// Returns the current wall-clock time in milliseconds since the Unix epoch. + /// + /// This is NOT monotonic and can go backward if the system clock is adjusted. + /// It should only be used for `Date` objects and other wall-clock time needs. + fn system_time_millis(&self) -> i64; } -/// A clock that uses the standard system clock. -#[derive(Debug, Clone, Copy, Default)] -pub struct StdClock; +/// A clock that uses the standard monotonic clock. +/// +/// This clock is based on [`std::time::Instant`] and is guaranteed to be +/// monotonic. Time measurements are relative to an arbitrary starting point +/// (the first call to `now()`) and are not affected by system clock adjustments. +/// +/// This ensures that time never goes backward, which is critical for +/// maintaining the invariants of [`JsInstant`]. +#[derive(Debug, Clone, Copy)] +pub struct StdClock { + /// The base instant from which all measurements are relative. + base: std::time::Instant, +} + +impl Default for StdClock { + fn default() -> Self { + Self::new() + } +} + +impl StdClock { + /// Creates a new `StdClock` with the current instant as the base. + #[must_use] + pub fn new() -> Self { + Self { + base: std::time::Instant::now(), + } + } +} impl Clock for StdClock { fn now(&self) -> JsInstant { + let elapsed = self.base.elapsed(); + JsInstant::new_unchecked(elapsed) + } + + fn system_time_millis(&self) -> i64 { let now = std::time::SystemTime::now(); let duration = now .duration_since(std::time::UNIX_EPOCH) .expect("System clock is before Unix epoch"); - - JsInstant::new_unchecked(duration) + duration.as_millis() as i64 } } @@ -178,28 +229,36 @@ impl Clock for FixedClock { ((millis % 1000) * 1_000_000) as u32, )) } + + fn system_time_millis(&self) -> i64 { + *self.0.borrow() as i64 + } } #[test] fn basic() { - let now = StdClock.now(); - assert!(now.millis_since_epoch() > 0); - assert!(now.nanos_since_epoch() > 0); + let clock = StdClock::new(); + let now = clock.now(); + // Since we're using a relative clock, values are always >= 0 by type + let _millis = now.millis_since_epoch(); + let _nanos = now.nanos_since_epoch(); let duration = JsDuration::from_millis(1000); let later = now + duration; assert!(later > now); - let earlier = now - duration; - assert!(earlier < now); + // Only subtract if we have enough time elapsed + let duration_small = JsDuration::from_millis(100); + let later_small = now + duration_small; + let earlier = later_small - duration_small; + assert_eq!(earlier, now); - let diff = later - earlier; - assert_eq!(diff.as_millis(), 2000); + let diff = later - now; + assert_eq!(diff.as_millis(), 1000); let fixed = FixedClock::from_millis(0); let now2 = fixed.now(); assert_eq!(now2.millis_since_epoch(), 0); - assert!(now2 < now); fixed.forward(1000); let now3 = fixed.now(); @@ -212,3 +271,38 @@ fn basic() { assert_eq!(now4.millis_since_epoch(), u64::MAX); assert!(now4 > now3); } + +#[test] +fn monotonic_behavior() { + let clock = StdClock::new(); + + // Verify that time always moves forward + let t1 = clock.now(); + std::thread::sleep(std::time::Duration::from_millis(1)); + let t2 = clock.now(); + std::thread::sleep(std::time::Duration::from_millis(1)); + let t3 = clock.now(); + + // Time must always increase + assert!(t2 > t1, "Time must move forward"); + assert!(t3 > t2, "Time must continue moving forward"); + assert!(t3 > t1, "Time must be transitive"); + + // Verify that elapsed time is reasonable + let elapsed = t3 - t1; + assert!(elapsed.as_millis() >= 2, "At least 2ms should have elapsed"); +} + +#[test] +fn clock_independence() { + // Each clock instance has its own base instant + let clock1 = StdClock::new(); + std::thread::sleep(std::time::Duration::from_millis(10)); + let clock2 = StdClock::new(); + + let t1 = clock1.now(); + let t2 = clock2.now(); + + // clock1 started earlier, so it should show more elapsed time + assert!(t1.millis_since_epoch() >= t2.millis_since_epoch()); +} From 064ce6cc0fa7758e72144c8195ff46064e320ffc Mon Sep 17 00:00:00 2001 From: Abhinav Sharma Date: Sat, 7 Mar 2026 20:53:50 +0530 Subject: [PATCH 2/5] fix: Use instant crate for WASM-compatible monotonic clock --- Cargo.lock | 5 +++++ core/engine/src/builtins/temporal/now.rs | 2 +- core/engine/src/context/time.rs | 21 ++++++++++++--------- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9b0076c5807..a815cf03931 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -439,6 +439,7 @@ dependencies = [ "icu_time", "indexmap", "indoc", + "instant", "intrusive-collections", "itertools 0.14.0", "jemallocator", @@ -2459,6 +2460,10 @@ version = "1.0.0-dev" dependencies = [ "boa_engine", "insta", + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", ] [[package]] diff --git a/core/engine/src/builtins/temporal/now.rs b/core/engine/src/builtins/temporal/now.rs index 0b075097d11..9737fd9e056 100644 --- a/core/engine/src/builtins/temporal/now.rs +++ b/core/engine/src/builtins/temporal/now.rs @@ -215,7 +215,7 @@ impl HostClock for &Context { fn get_host_epoch_nanoseconds(&self) -> TemporalResult { // Temporal needs actual Unix epoch time, not monotonic time let millis = self.clock().system_time_millis(); - let nanos = millis as i128 * 1_000_000; + let nanos = i128::from(millis) * 1_000_000; Ok(EpochNanoseconds::from(nanos)) } } diff --git a/core/engine/src/context/time.rs b/core/engine/src/context/time.rs index 4da59fe701b..c738695e6f8 100644 --- a/core/engine/src/context/time.rs +++ b/core/engine/src/context/time.rs @@ -1,5 +1,7 @@ //! Clock related types and functions. +use instant::Instant; + /// A monotonic instant in time, in the Boa engine. /// /// This type is guaranteed to be monotonic, i.e. if two instants @@ -158,8 +160,9 @@ pub trait Clock { /// A clock that uses the standard monotonic clock. /// -/// This clock is based on [`std::time::Instant`] and is guaranteed to be -/// monotonic. Time measurements are relative to an arbitrary starting point +/// This clock is based on [`instant::Instant`] which provides cross-platform +/// monotonic time, including WASM support via `performance.now()`. +/// Time measurements are relative to an arbitrary starting point /// (the first call to `now()`) and are not affected by system clock adjustments. /// /// This ensures that time never goes backward, which is critical for @@ -167,7 +170,7 @@ pub trait Clock { #[derive(Debug, Clone, Copy)] pub struct StdClock { /// The base instant from which all measurements are relative. - base: std::time::Instant, + base: Instant, } impl Default for StdClock { @@ -181,7 +184,7 @@ impl StdClock { #[must_use] pub fn new() -> Self { Self { - base: std::time::Instant::now(), + base: Instant::now(), } } } @@ -275,19 +278,19 @@ fn basic() { #[test] fn monotonic_behavior() { let clock = StdClock::new(); - + // Verify that time always moves forward let t1 = clock.now(); std::thread::sleep(std::time::Duration::from_millis(1)); let t2 = clock.now(); std::thread::sleep(std::time::Duration::from_millis(1)); let t3 = clock.now(); - + // Time must always increase assert!(t2 > t1, "Time must move forward"); assert!(t3 > t2, "Time must continue moving forward"); assert!(t3 > t1, "Time must be transitive"); - + // Verify that elapsed time is reasonable let elapsed = t3 - t1; assert!(elapsed.as_millis() >= 2, "At least 2ms should have elapsed"); @@ -299,10 +302,10 @@ fn clock_independence() { let clock1 = StdClock::new(); std::thread::sleep(std::time::Duration::from_millis(10)); let clock2 = StdClock::new(); - + let t1 = clock1.now(); let t2 = clock2.now(); - + // clock1 started earlier, so it should show more elapsed time assert!(t1.millis_since_epoch() >= t2.millis_since_epoch()); } From 3bee8d7dcd3668deaac5856fe226c203a937b243 Mon Sep 17 00:00:00 2001 From: Abhinav Sharma Date: Sat, 7 Mar 2026 23:56:09 +0530 Subject: [PATCH 3/5] chore: update instant->crate::sys::time --- core/engine/src/context/time.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/engine/src/context/time.rs b/core/engine/src/context/time.rs index c738695e6f8..839d50afe3d 100644 --- a/core/engine/src/context/time.rs +++ b/core/engine/src/context/time.rs @@ -1,6 +1,6 @@ //! Clock related types and functions. -use instant::Instant; +use crate::sys::time::Instant; /// A monotonic instant in time, in the Boa engine. /// From 47e9d84415b1eccea5d3ac224281e3635e45caec Mon Sep 17 00:00:00 2001 From: Abhinav Sharma Date: Sat, 14 Mar 2026 13:57:04 +0530 Subject: [PATCH 4/5] chore: update cargo lock file Signed-off-by: Abhinav Sharma --- Cargo.lock | 1 - 1 file changed, 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index a815cf03931..337ca7cc297 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -439,7 +439,6 @@ dependencies = [ "icu_time", "indexmap", "indoc", - "instant", "intrusive-collections", "itertools 0.14.0", "jemallocator", From 69452e0d6765e7cbded17629f4ac3867486c0a11 Mon Sep 17 00:00:00 2001 From: Abhinav Sharma Date: Sun, 15 Mar 2026 04:01:25 +0530 Subject: [PATCH 5/5] fix: update old comments Signed-off-by: Abhinav Sharma --- core/engine/src/context/time.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/engine/src/context/time.rs b/core/engine/src/context/time.rs index 839d50afe3d..f360dbe8c26 100644 --- a/core/engine/src/context/time.rs +++ b/core/engine/src/context/time.rs @@ -147,8 +147,8 @@ impl std::ops::Sub for JsInstant { pub trait Clock { /// Returns the current monotonic time. /// - /// This is guaranteed to be monotonic and should be used for measuring - /// durations and scheduling timeouts. + /// Implementers must ensure this is monotonic and should be used for measuring + /// durations and scheduling timeouts. The engine assumes monotonicity. fn now(&self) -> JsInstant; /// Returns the current wall-clock time in milliseconds since the Unix epoch. @@ -160,8 +160,8 @@ pub trait Clock { /// A clock that uses the standard monotonic clock. /// -/// This clock is based on [`instant::Instant`] which provides cross-platform -/// monotonic time, including WASM support via `performance.now()`. +/// This clock is based on [`web_time::Instant`] (via `crate::sys::time`) which provides +/// cross-platform monotonic time, including WASM support via `performance.now()`. /// Time measurements are relative to an arbitrary starting point /// (the first call to `now()`) and are not affected by system clock adjustments. ///