diff --git a/Cargo.lock b/Cargo.lock index c9013e4fa2..c1d51c5ec8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -355,6 +355,22 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" +[[package]] +name = "futures-test" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4d0ceb932f7909033988f82e244109c50e5f3978ca031c576533dd3480a7605" +dependencies = [ + "futures-core", + "futures-executor", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "futures-util", + "pin-project", +] + [[package]] name = "futures-util" version = "0.3.34" @@ -964,6 +980,26 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -1590,6 +1626,7 @@ dependencies = [ "blake2", "bytes", "futures", + "futures-test", "headers", "hex", "http", diff --git a/changelog.d/20508.misc b/changelog.d/20508.misc new file mode 100644 index 0000000000..85a18ac405 --- /dev/null +++ b/changelog.d/20508.misc @@ -0,0 +1 @@ +Add a Rust `Clock::sleep` method. diff --git a/rust/Cargo.toml b/rust/Cargo.toml index a495e5e6e1..b299371ffb 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -62,7 +62,7 @@ reqwest = { version = "0.12.15", default-features = false, features = [ ] } http-body-util = "0.1.3" futures = "0.3.31" -tokio = { version = "1.44.2", features = ["rt", "rt-multi-thread"] } +tokio = { version = "1.44.2", features = ["rt", "rt-multi-thread", "sync", "time"] } tokio-postgres = "0.7" once_cell = "1.18.0" itertools = "0.15.0" @@ -72,3 +72,6 @@ postgres-protocol = "0.6.10" blake2 = "0.11.0" hex = "0.4.3" rustc_version = "0.4.1" + +[dev-dependencies] +futures-test = "0.3.34" diff --git a/rust/clippy.toml b/rust/clippy.toml index bf2f715c8e..ea6f6cf76e 100644 --- a/rust/clippy.toml +++ b/rust/clippy.toml @@ -7,4 +7,14 @@ disallowed-methods = [ { path = "tokio::runtime::Runtime::spawn_blocking", reason = "leaks past RustRuntime shutdown; see rust/src/runtime.rs" }, { path = "tokio::runtime::Handle::spawn_blocking", reason = "leaks past RustRuntime shutdown; see rust/src/runtime.rs" }, { path = "tokio::task::block_in_place", reason = "blocks a tokio worker thread; see rust/src/runtime.rs" }, + { path = "crate::clock::set_virtual_time_msec", reason = "should only be called from Python unit tests; see rust/src/clock.rs" }, + # Tokio's timers wait on the real time, so they do not follow the virtual + # clock that Synapse's unit tests run on. `Clock::sleep` (see + # `rust/src/clock.rs`) does. + { path = "tokio::time::sleep", reason = "ignores the virtual clock in tests, use `Clock::sleep` in rust/src/clock.rs" }, + { path = "tokio::time::sleep_until", reason = "ignores the virtual clock in tests, use `Clock::sleep` in rust/src/clock.rs" }, + { path = "tokio::time::timeout", reason = "ignores the virtual clock in tests, race the future against `Clock::sleep` in rust/src/clock.rs" }, + { path = "tokio::time::timeout_at", reason = "ignores the virtual clock in tests, race the future against `Clock::sleep` in rust/src/clock.rs" }, + { path = "tokio::time::interval", reason = "ignores the virtual clock in tests, loop on `Clock::sleep` in rust/src/clock.rs" }, + { path = "tokio::time::interval_at", reason = "ignores the virtual clock in tests, loop on `Clock::sleep` in rust/src/clock.rs" }, ] diff --git a/rust/src/clock.rs b/rust/src/clock.rs index 5e5fc264e4..2cf5f3d225 100644 --- a/rust/src/clock.rs +++ b/rust/src/clock.rs @@ -20,44 +20,95 @@ //! homeserver's [`RustRuntime`](crate::runtime::RustRuntime) owns a [`Clock`] //! that can be read without the GIL. //! -//! Synapse's unit tests run against a virtual reactor clock, where time only -//! moves when a test says so. The test reactor keeps this clock in step via -//! [`set_virtual_time_msec`]. See `ThreadedMemoryReactorClock` in -//! `tests/server.py`. +//! The complication here is that we need to support manually changing time in +//! both Python and Rust unit tests. In Python unit tests the virtual time is +//! shared across the whole process (as only one test is run at a time), while +//! in Rust multiple independent tests can run in parallel within the same +//! process. +//! +//! We support this by having each [`Clock`] set to either track the +//! process-wide time (either the system clock or the python set global virtual +//! time), or independently track a virtual time that can be set directly (for +//! Rust unit tests). use std::{ - sync::atomic::{AtomicU64, Ordering}, + sync::OnceLock, time::{Duration, SystemTime, UNIX_EPOCH}, }; -use pyo3::pyfunction; +use pyo3::{pyfunction, Python}; +use tokio::sync::watch; -/// A sentinel value stored in [`VIRTUAL_MILLIS`] while the clock is -/// reading the real time. This value indicates that the clock should read the -/// real system time rather than a virtual time. +/// A time that only moves when a test sets it. /// -/// We choose a value that will never be used in tests, namely the maximum `u64` -/// value. This is 584 million years after the epoch. -const REAL_TIME_SENTINEL: u64 = u64::MAX; +/// Clones share the same time. +#[derive(Debug, Clone)] +pub struct VirtualTime { + /// The time in milliseconds since the Unix epoch. This is a channel so + /// that [`Clock::sleep`] can wait for the time to change. + millis: watch::Sender, +} -/// The virtual time in milliseconds since the Unix epoch, or -/// [`REAL_TIME_SENTINEL`]. Only ever set by tests, via [`set_virtual_time_msec`]. -/// -/// We use an AtomicU64 (rather than e.g. `Option<..>`) so that reads are fast -/// and do not require locking. -static VIRTUAL_MILLIS: AtomicU64 = AtomicU64::new(REAL_TIME_SENTINEL); - -/// Pin the clock to the given time, in milliseconds since the Unix epoch. -/// -/// Only tests call this. Nothing unpins the clock, since a test reactor -/// and the runtimes attached to it live for a single test. -#[pyfunction] -pub fn set_virtual_time_msec(millis: u64) { - if millis == REAL_TIME_SENTINEL { - panic!("Cannot set virtual time to the sentinel value REAL_TIME_SENTINEL"); +impl VirtualTime { + /// A virtual time that starts at `millis` since the Unix epoch. + pub fn new(millis: u64) -> Self { + VirtualTime { + millis: watch::Sender::new(UNIX_EPOCH + Duration::from_millis(millis)), + } } - VIRTUAL_MILLIS.store(millis, Ordering::Relaxed); + /// Move the time to `millis` since the Unix epoch, and wake up any + /// sleepers that are now due. + pub fn set_millis(&self, millis: u64) { + // Only wake the sleepers if the time has changed. Python's unit + // tests advance the reactor by zero seconds a lot. + let instant = UNIX_EPOCH + Duration::from_millis(millis); + self.millis + .send_if_modified(|now| std::mem::replace(now, instant) != instant); + } + + fn now(&self) -> SystemTime { + *self.millis.borrow() + } + + /// Wait until the time has moved on by `duration`. + async fn sleep(&self, duration: Duration) { + // The virtual time counts whole milliseconds. Round up so that we never + // wake early. + let duration_millis = + u64::try_from(duration.as_nanos().div_ceil(1_000_000)).expect("duration is too large"); + + let mut millis = self.millis.subscribe(); + let wake_up_time = *millis.borrow() + Duration::from_millis(duration_millis); + + // Wait for the test to move the time far enough. `wait_for` checks + // the current time before it waits, so we cannot miss a change that + // happens on another thread meanwhile. + millis + .wait_for(|now| *now >= wake_up_time) + .await + .expect("we hold a sender, so the channel cannot close"); + } +} + +/// The virtual time that Python's unit tests control via +/// [`set_virtual_time_msec`]. Unset outside of those tests, which is what +/// tells a [`Clock::Process`] to read the real time. +static PYTHON_VIRTUAL_TIME: OnceLock = OnceLock::new(); + +/// Pin every [`Clock::Process`] in this process to the given time, in +/// milliseconds since the Unix epoch. +/// +/// Only Python's unit tests call this. +/// +/// A Rust unit test must never call this, as it would change the time under +/// every other test in the process. Use a [`Clock::Internal`]. It takes a +/// `Python` argument to indicate it should be run from Rust. +#[pyfunction] +pub fn set_virtual_time_msec(_py: Python, millis: u64) { + PYTHON_VIRTUAL_TIME + .get_or_init(|| VirtualTime::new(millis)) + .set_millis(millis); } /// The current time as the Rust side of a homeserver sees it. @@ -65,38 +116,45 @@ pub fn set_virtual_time_msec(millis: u64) { /// Like `synapse.util.clock.Clock` on the Python side, this is a wall clock. /// While these are two separate, independent implementations, they both read /// the same system clock (on Linux both are -/// `clock_gettime(CLOCK_REALTIME)`).Code that needs a monotonic clock should +/// `clock_gettime(CLOCK_REALTIME)`). Code that needs a monotonic clock should /// use [`std::time::Instant`] directly. /// /// In future, this may be extended to support per-homeserver looping calls /// (which is why this is not a global clock). /// /// See [`crate::clock`] docs for more details. -pub struct Clock {} +#[derive(Debug, Default)] +pub enum Clock { + /// Reads the process clock, which is either the system clock or the time + /// set by Python unit tests. c.f. [`set_virtual_time_msec`]. + #[default] + Process, -impl Default for Clock { - fn default() -> Self { - Self::new() - } + /// Follows a [`VirtualTime`] that the caller controls for Rust unit tests. + /// + /// Ignores the Python virtual time set by [`set_virtual_time_msec`]. + Internal(VirtualTime), } impl Clock { - /// A clock reading the real time. - pub fn new() -> Self { - Clock {} - } - /// The current time. /// - /// Reads the same system clock as `synapse.util.clock.Clock.time_msec()` - /// on the Python side. See the module docs. + /// This will return the current time according to the process clock or the + /// internal virtual time, depending on the variant of the `Clock`. pub fn now(&self) -> SystemTime { - // Check if virtual time is set, otherwise fall back to real time. - match VIRTUAL_MILLIS.load(Ordering::Relaxed) { - // On Linux this is a vDSO call rather than a syscall, so it is - // cheap enough to make on every read. - REAL_TIME_SENTINEL => SystemTime::now(), - virtual_millis => UNIX_EPOCH + Duration::from_millis(virtual_millis), + match (self, PYTHON_VIRTUAL_TIME.get()) { + (Clock::Process, None) => SystemTime::now(), + (Clock::Process, Some(virtual_time)) => virtual_time.now(), + (Clock::Internal(virtual_time), None) => virtual_time.now(), + (Clock::Internal(_), Some(_)) => { + // We should never be combining a Clock::Internal with Python + // virtual time. Clock::Internal is used by Rust unit tests, + // while Python virtual time is used by Python unit tests. + // + // If we have both then something has gotten very confused + // somewhere. + panic!("Internal clock should not be used with Python virtual time") + } } } @@ -111,10 +169,49 @@ impl Clock { .expect("system clock was set before the Unix epoch, 1970") .as_millis() as u64 } + + /// Wait until `duration` has passed on this clock. + /// + /// Use this in place of [`tokio::time::sleep`], which always waits on the + /// real time. On a virtual time this finishes once the test has moved + /// the time to the wake-up time. + /// + /// Under Python's unit tests, `reactor.advance()` wakes the sleeper but + /// does not wait for it. The task carries on later, on a Tokio worker + /// thread. A test has to keep advancing the reactor until the result has + /// come back to it. + /// + /// # Panics + /// + /// On the real time this uses Tokio's timer, so it panics if polled + /// outside a Tokio runtime. On a virtual time it runs anywhere. A unit + /// test that polls the future by hand therefore cannot catch a caller + /// that is not on a runtime. + pub async fn sleep(&self, duration: Duration) { + match (self, PYTHON_VIRTUAL_TIME.get()) { + (Clock::Process, None) => + { + #[expect(clippy::disallowed_methods, reason = "…")] + tokio::time::sleep(duration).await + } + (Clock::Process, Some(virtual_time)) => virtual_time.sleep(duration).await, + (Clock::Internal(virtual_time), None) => virtual_time.sleep(duration).await, + (Clock::Internal(_), Some(_)) => { + panic!("Internal clock should not be used with Python virtual time") + } + } + } } #[cfg(test)] mod tests { + use std::{ + pin::pin, + task::{Context, Waker}, + }; + + use futures::FutureExt; + use super::*; #[test] @@ -122,15 +219,72 @@ mod tests { // Any real wall clock reads later than this (2020-09-13). const PLAUSIBLE_WALL_CLOCK_MILLIS: u64 = 1_600_000_000_000; - let clock = Clock::new(); + let clock = Clock::Process; assert!(clock.now_millis() > PLAUSIBLE_WALL_CLOCK_MILLIS); - set_virtual_time_msec(12345); + let virtual_time = VirtualTime::new(12345); + let clock = Clock::Internal(virtual_time.clone()); assert_eq!(clock.now_millis(), 12345); assert_eq!(clock.now(), UNIX_EPOCH + Duration::from_millis(12345)); // Zero is a legitimate virtual time. The memory reactor starts there. - set_virtual_time_msec(0); + virtual_time.set_millis(0); assert_eq!(clock.now_millis(), 0); } + + #[test] + fn virtual_time_sleepers_are_woken_up_in_order() { + let virtual_time = VirtualTime::new(0); + let clock = Clock::Internal(virtual_time.clone()); + + // Schedule two sleepers with different durations. The one with the + // shorter duration should wake up first. + let mut sleep1 = pin!(clock.sleep(Duration::from_millis(10))); + let mut sleep2 = pin!(clock.sleep(Duration::from_millis(5))); + + let mut cx = Context::from_waker(Waker::noop()); + + // Initially, both sleepers should be pending because virtual time has + // not advanced yet. + assert!(sleep1.poll_unpin(&mut cx).is_pending()); + assert!(sleep2.poll_unpin(&mut cx).is_pending()); + + // Advance virtual time to wake up the sleepers. + virtual_time.set_millis(5); + + // After advancing virtual time to 5 milliseconds, the second sleeper + // (with a 5ms duration) should be ready, while the first sleeper + // (with a 10ms duration) should still be pending. + assert!(sleep1.poll_unpin(&mut cx).is_pending()); + assert!(sleep2.poll_unpin(&mut cx).is_ready()); + + virtual_time.set_millis(10); + + // After advancing virtual time to 10 milliseconds, the first sleeper + // (with a 10ms duration) should now be ready. + assert!(sleep1.poll_unpin(&mut cx).is_ready()); + } + + #[test] + fn virtual_time_advance_notifies_the_sleeping_task() { + let virtual_time = VirtualTime::new(0); + let clock = Clock::Internal(virtual_time.clone()); + + let (waker, awoken_count) = futures_test::task::new_count_waker(); + let mut cx = Context::from_waker(&waker); + + let mut sleep = pin!(clock.sleep(Duration::from_millis(5))); + assert!(sleep.poll_unpin(&mut cx).is_pending()); + assert_eq!(awoken_count.get(), 0); + + // Setting the time it already has wakes nobody. + virtual_time.set_millis(0); + assert_eq!(awoken_count.get(), 0); + + // The other tests poll by hand. A real task is only polled again + // once its waker is called. + virtual_time.set_millis(5); + assert_eq!(awoken_count.get(), 1); + assert!(sleep.poll_unpin(&mut cx).is_ready()); + } } diff --git a/rust/src/runtime.rs b/rust/src/runtime.rs index 426860983b..bfdfa953d2 100644 --- a/rust/src/runtime.rs +++ b/rust/src/runtime.rs @@ -209,7 +209,7 @@ impl RustRuntime { reactor, tokio: Mutex::new(TokioState::NotStarted), worker_threads, - clock: Clock::new(), + clock: Clock::Process, dispatcher, dispatch_reader, });