Skip to content

Add a configurable clock for QUICHE - #2893

Open
Aalima201 wants to merge 2 commits into
cloudflare:masterfrom
Aalima201:simulated-time-pr
Open

Aalima201 wants to merge 2 commits into
cloudflare:masterfrom
Aalima201:simulated-time-pr

Conversation

@Aalima201

Copy link
Copy Markdown

Summary

This PR introduces support for a configurable clock abstraction to QUICHE, allowing its internal clock to be synchronized with an external discrete-event simulator.

Motivation

QUICHE currently relies on Rust's Instant::now() for internal timing operations. When integrated with discrete-event network simulators such as ns-3, these operations need to use the simulator's notion of time rather than the system's real-time clock.

Changes

  • Introduced a clock abstraction in src/clock.rs with support for real-time and simulated-time modes.
  • Added set_simulated_time_us() to update the externally supplied simulated time.
  • Added use_real_clock() to restore real-time clock operation.
  • Exposed quiche_set_simulated_time_us() through the C FFI and declare it in include/quiche.h.
  • Replaced direct Instant::now() calls in the relevant Rust source files with the new clock abstraction.

Testing

  • Built QUICHE with FFI support using cargo build --release --features ffi.
  • Verified the exported quiche_set_simulated_time_us symbol in the compiled shared library.

Related Work

See [QUICHE-Timer] for the implementation details.

@Aalima201
Aalima201 requested a review from a team as a code owner November 17, 2026 07:14
@Aalima201

Copy link
Copy Markdown
Author

@estcarisimo , could you please take a look at this PR? I would appreciate your feedback.

Comment thread quiche/src/clock.rs
@@ -0,0 +1,49 @@
// quiche/src/clock.rs

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like you lost changes from several commits on master including da28c7a and c99613b

I would consider re-creating this PR from first principles:

  • add this file, SIMULATED_TIME.md and do the renames of Instant::now() to the new struct.
  • Add the ffi method to interact with the simulated clock.

Comment thread quiche/src/clock.rs
SIM_MODE.store(true, Ordering::Release);
// Force epoch initialization now, so epoch() is stable from here on.
let _ = epoch();
SIM_OFFSET_US.store(time_us, Ordering::Release);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The quiche implementation requires that time moves forward monotonically. I think you should ensure that time_us provided is >= SIM_OFFSET_US via a compare and swap.

Comment thread quiche/src/clock.rs
SIM_OFFSET_US.store(time_us, Ordering::Release);
}

/// Reverts to the real OS clock (mainly useful for tests).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This API seems difficult to implement correctly given the requirement imposed by quiche that time doesn't move backwards. I would consider removing this in favor of comments stating that once you enter simulated clock mode, there is no going back to regular clock. And strongly encourage the first call to enable the simulated clock happen before creation of the quiche connection.

@estcarisimo estcarisimo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Aalima and team, for opening this, and for the clear write-up in SIMULATED_TIME.md. Simulated time would make quiche much easier to use with ns-3.

Antonio's comments come first, especially recreating the PR from current master. My comments below are meant to fit with his, and they include code you're welcome to reuse. I tried these changes on top of current master: the new unit tests pass, and clippy is clean on macOS and Linux. CI hasn't run on this PR yet, so some of this would only have shown up there.

Happy to take another look once the PR is updated. Please feel free to ask questions here.

Comment thread quiche/src/clock.rs
use std::sync::OnceLock;
use std::time::{Duration, Instant};

static EPOCH: OnceLock<Instant> = OnceLock::new();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Building on Antonio's comments on this file, here is one way to put them together:

  • Time can't go backward. fetch_max() does the compare-and-swap Antonio mentioned in one atomic step, so a smaller value is simply ignored.
  • No way back to the real clock. use_real_clock() is gone, and the module docs say simulated time stays on and should be enabled before creating any connection.
  • Tests that don't interfere with each other. The state lives in a small Clock struct with one global instance. Unit tests create their own Clock, so they never change the time seen by other tests that cargo test runs in parallel.
  • License header. New files in quiche start with the same BSD license header as the other files (for example, quiche/src/recovery/bytes_in_flight.rs).
Proposed clock.rs (license header omitted)
//! The clock that quiche uses for every time read.
//!
//! By default this is the system's monotonic clock, `Instant::now()`. An
//! application such as a network simulator can drive time instead by calling
//! [`set_simulated_time_us()`]. Simulated time applies to every connection in
//! the process, and once enabled it can't be turned off. Enable it before
//! creating any connection.

use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::OnceLock;
use std::time::Duration;
use std::time::Instant;

/// Process-wide clock state.
static CLOCK: Clock = Clock::new();

/// Returns the current time as quiche should see it.
pub(crate) fn now() -> Instant {
    CLOCK.now()
}

/// Enables simulated time, and sets it to `time_us` microseconds since the
/// simulated epoch. The epoch is fixed by the first call.
///
/// quiche requires time to move forward, so a value smaller than the current
/// simulated time is ignored.
#[cfg_attr(not(feature = "ffi"), allow(dead_code))]
pub(crate) fn set_simulated_time_us(time_us: u64) {
    CLOCK.set_simulated_time_us(time_us);
}

/// Returns `time` as an offset from the simulated epoch, or `None` when
/// simulated time is not enabled.
// Only the FFI uses this, and only on platforms where it converts times.
#[allow(dead_code)]
pub(crate) fn since_simulated_epoch(time: Instant) -> Option<Duration> {
    CLOCK
        .simulated_epoch()
        .map(|epoch| time.saturating_duration_since(epoch))
}

struct Clock {
    epoch: OnceLock<Instant>,
    offset_us: AtomicU64,
    simulated: AtomicBool,
}

impl Clock {
    const fn new() -> Self {
        Clock {
            epoch: OnceLock::new(),
            offset_us: AtomicU64::new(0),
            simulated: AtomicBool::new(false),
        }
    }

    fn simulated_epoch(&self) -> Option<Instant> {
        // `simulated` is set only after `epoch`, so the epoch is always
        // initialized here.
        if self.simulated.load(Ordering::Acquire) {
            self.epoch.get().copied()
        } else {
            None
        }
    }

    fn now(&self) -> Instant {
        match self.simulated_epoch() {
            Some(epoch) =>
                epoch +
                    Duration::from_micros(
                        self.offset_us.load(Ordering::Acquire),
                    ),

            None => Instant::now(),
        }
    }

    fn set_simulated_time_us(&self, time_us: u64) {
        self.epoch.get_or_init(Instant::now);

        // `fetch_max()` is an atomic compare-and-swap that never lowers the
        // stored value, so time can't move backward.
        self.offset_us.fetch_max(time_us, Ordering::AcqRel);

        self.simulated.store(true, Ordering::Release);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Each test uses its own `Clock`, so tests running in parallel never
    // see each other's simulated time.

    #[test]
    fn real_clock_by_default() {
        let clock = Clock::new();
        let before = Instant::now();

        assert!(clock.now() >= before);
        assert_eq!(clock.simulated_epoch(), None);
    }

    #[test]
    fn simulated_time_follows_setter() {
        let clock = Clock::new();

        clock.set_simulated_time_us(1_000);
        let t1 = clock.now();

        clock.set_simulated_time_us(26_000);
        let t2 = clock.now();

        assert_eq!(t2 - t1, Duration::from_millis(25));
        let epoch = clock.simulated_epoch().unwrap();
        assert_eq!(t2 - epoch, Duration::from_micros(26_000));
    }

    #[test]
    fn simulated_time_never_moves_backward() {
        let clock = Clock::new();

        clock.set_simulated_time_us(5_000);
        let t1 = clock.now();

        clock.set_simulated_time_us(1_000);

        assert_eq!(clock.now(), t1);
    }
}

since_simulated_epoch() is for the quiche_send_info.at fix in ffi.rs (see my comment there).

Comment thread quiche/src/lib.rs
// Best effort to get Instant::now() and SystemTime::now() as closely
// together as possible.
let now = Instant::now();
let now = crate::clock::now();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

quiche's lib.rs sets #![warn(unused_qualifications)], and CI builds with RUSTFLAGS="-D warnings", so crate::clock::now() here will fail the build once CI runs. Since clock is a module of the crate root, this can be:

        let now = clock::now();

The same applies to the other calls in lib.rs and to crate::clock::set_simulated_time_us() in ffi.rs. In the other modules, crate::clock::now() is fine.

Comment thread quiche/src/ffi.rs
/// (quiche_conn_recv, quiche_conn_send, quiche_conn_on_timeout, etc.)
/// whenever the external simulator's clock has advanced.
#[no_mangle]
pub extern "C" fn quiche_set_simulated_time_us(time_us: u64) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing that affects ns-3 results: quiche_conn_send() reports the pacing time in quiche_send_info.at, and std_time_to_c() converts it using the real system clock. With simulated time on, at ends up in neither the real timeline nor the ns-3 one. If the ns-3 side ignores at, packets go out without pacing, which matters for BBR.

A small change in std_time_to_c() reports at in the same timeline that quiche_set_simulated_time_us() uses:

#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
fn std_time_to_c(time: &Instant, out: &mut timespec) {
    // With simulated time, report times in the simulator's timeline, the
    // same one used by quiche_set_simulated_time_us().
    if let Some(since_epoch) = clock::since_simulated_epoch(*time) {
        out.tv_sec = since_epoch.as_secs() as libc::time_t;
        out.tv_nsec = since_epoch.subsec_nanos() as libc::c_long;
        return;
    }

    // ... existing conversion unchanged ...
}

ns-3 can then schedule the send at at as simulation time. On macOS and Windows, std_time_to_c() currently always returns zero, so this only helps on Linux. That limitation is worth a line in SIMULATED_TIME.md. This could also be a follow-up PR if you'd rather keep this one small.

Comment thread quiche/include/quiche.h
Comment on lines +149 to +154
// Drives quiche's internal clock from an external simulator (e.g. ns-3),
// instead of the real OS clock. |time_us| is microseconds since this
// process' simulated epoch. Call this before any quiche API that depends
// on current time (quiche_conn_recv, quiche_conn_send,
// quiche_conn_on_timeout, etc.) whenever the simulator's clock advances.
void quiche_set_simulated_time_us(uint64_t time_us);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggest documenting the rules a caller needs to follow here:

Suggested change
// Drives quiche's internal clock from an external simulator (e.g. ns-3),
// instead of the real OS clock. |time_us| is microseconds since this
// process' simulated epoch. Call this before any quiche API that depends
// on current time (quiche_conn_recv, quiche_conn_send,
// quiche_conn_on_timeout, etc.) whenever the simulator's clock advances.
void quiche_set_simulated_time_us(uint64_t time_us);
// Switches quiche to simulated time, driven by an external simulator such as
// ns-3, and sets it to |time_us| microseconds since the simulated epoch. The
// first call fixes the epoch.
//
// Simulated time applies to every connection in the process and can't be
// turned off. Make the first call before creating any connection, then call
// it again whenever the simulator's clock advances, before any quiche API
// that depends on the current time (quiche_conn_recv(), quiche_conn_send(),
// quiche_conn_on_timeout(), and so on). Time must not move backward, so a
// value smaller than the current one is ignored.
void quiche_set_simulated_time_us(uint64_t time_us);

Optional: ns-3 keeps time in nanoseconds, and at 10 Gb/s a 1500-byte packet takes about 1.2 µs to send. Taking nanoseconds (quiche_set_simulated_time_ns()) would avoid rounding pacing times in fast simulations. It's easy to change now, before anyone depends on the name.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants