Skip to content

Use tokio::time instead of std::time, to enable tokio's cool testing helpers - #947

Open
njsmith wants to merge 1 commit into
hyperium:masterfrom
njsmith:tokio-instant
Open

Use tokio::time instead of std::time, to enable tokio's cool testing helpers#947
njsmith wants to merge 1 commit into
hyperium:masterfrom
njsmith:tokio-instant

Conversation

@njsmith

@njsmith njsmith commented Aug 21, 2026

Copy link
Copy Markdown

tokio::time::Instant is a trivial newtype wrapper around std::time::Instant, and normally tokio::time::Instant::now() simply calls the std version, so it's a zero-cost drop-in replacement. But! If you build tokio with the test-util feature enabled, then it also adds a quick check to see if you've overridden the clock for testing.

It's not documented/publicized as much as it should be, but tokio's clock testing mode is actually really cool. When you call sleep, tokio doesn't actually sleep, it just makes a note that the task should be awakened when the virtual clock reaches the given timestamp, and then whenever all tasks are idle it peeks at the timer wheel and advances the virtual time to whatever thing wants to wake up next. So as long as you make sure your test code doesn't perform any real system IO, then you can write arbitrarily complex tokio programs involving sleeps and time calculations, and they run super fast and deterministically. It's awesome for testing, fuzzing, etc.

Anyway, you can almost use h2 in these tests, except there are two places where it uses std::time::Instant instead of tokio::time::Instant. This PR fixes that.

I also switched two existing tests that use real sleeps to use the fake sleeps instead. I doubt it makes much difference because the sleeps were pretty short anyway, but in principle it should make them faster + less likely to get broken by janky CI runners with noisy neighbors, etc.

I also asked Claude to go look for invariants that would be good to test but aren't tested currently b/c real timing tests are so annoying and it came up with a few tests that look plausible enough to me, but I don't understand the code enough to really judge so I'll stick those up as a followup PR that you can take or leave. edit: I can't figure out how to post a stacked-PR from a fork into another org's repo, so I'll just link to the claude-slop tests here: https://github.com/njsmith/h2/compare/tokio-instant...tokio-instant-tests?expand=1

These are identical in all situations, except when using tokio's
virtualized-wallclock testing mode, which makes time-based tests fast
and deterministic, and is fantastic for things like fuzzing. This makes
h2 behave correctly in any downstream codebases with this style of test.
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.

1 participant