In Rust, what does the Future contract allow when poll is called again on a future that has already returned Poll::Ready?
answer
- clients should not poll again
- anything but undefined behaviour
- async fn resumed after completion
- fuse for defined behaviour
basics
~20 sAlmost anything except undefined behaviour: the Future docs say a second poll after Ready may panic, block forever or misbehave. Compiler-generated async futures and std's Ready panic; the futures crate's fuse() makes extra polls return Pending.
solid answer
~40 sThe `Future` docs say that once a future has finished, clients should not poll it again, and that doing so may panic, block forever or cause other problems: the trait places no requirements on such a call. Because `poll` is a safe method, it must still never cause undefined behaviour. In practice the futures rustc generates for `async fn` and async blocks panic with "`async fn` resumed after completion", and `std::future::Ready` panics with "`Ready` polled after completion". Code that may poll too often, such as a hand-written select loop or a combinator, wraps the future with `FutureExt::fuse` from the futures crate: a fused future returns `Pending` forever after its `Ready` and reports `is_terminated()`. `.await` and a correct executor do not poll a finished future.
code
rust · 22 linesuse futures::future::{FusedFuture, FutureExt};
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Waker};
async fn read_sensor() -> u32 { 21 }
fn main() {
let mut cx = Context::from_waker(Waker::noop());
let mut fused = pin!(read_sensor().fuse());
println!("{:?}", fused.as_mut().poll(&mut cx)); // Ready(21)
println!("{:?}", fused.as_mut().poll(&mut cx)); // Pending, forever
println!("terminated: {}", fused.is_terminated());
let mut plain = pin!(read_sensor());
println!("{:?}", plain.as_mut().poll(&mut cx)); // Ready(21)
let again = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
plain.as_mut().poll(&mut cx)
}));
println!("second poll panicked: {}", again.is_err());
}go deeper
Know the rule: once a future has returned Ready, do not poll it again. .await and executors already follow it for you.
Explain that the trait leaves a second poll unspecified, that compiler-generated futures panic, and that safe code may never cause undefined behaviour.
Spot where double polls come from, such as hand-written combinators and select loops, and reach for fuse() and FusedFuture when a future may be polled too often.
Explain why the loose contract keeps every future cheap and pushes the cost of defined extra polls to the few call sites that need them.
## What the trait promises, and what it does not The `Future::poll` documentation has a section on exactly this case. Two sentences matter: - Once a future has finished, **clients should not poll it again**. - Calling `poll` after it has returned `Ready` **may panic, block forever, or cause other kinds of problems**; the `Future` trait places no requirements on the effects of such a call. And one limit: because `poll` is not an `unsafe` method, Rust's usual rules apply, and such a call **must never cause undefined behaviour**, whatever state the future is in. So polling after completion is a *logic* error the type system does not catch, never a memory-safety hole. ## What real futures do Different futures pick different behaviours, all allowed by the contract: | Future | Second poll after `Ready` | |---|---| | compiler-generated `async fn` or async block | panics: "`async fn` resumed after completion" (rustc 1.99.1 prints this text for async blocks too) | | `std::future::ready(v)` (`Ready<T>`) | panics: "`Ready` polled after completion" | | the futures crate's `fut.fuse()` (`Fuse<F>`) | returns `Poll::Pending`, and keeps doing so | | a hand-written future | whatever its author wrote, which is the worry | The panic in compiler-generated futures comes from the state machine having no state to resume after it returned; how that state machine is laid out is the business of the lesson on async functions and blocks. ## Who actually polls twice `.await` stops polling the moment it sees `Ready`, and a correct executor stops polling a task once its top-level future has completed. The second poll comes from code that drives futures by hand: 1. **Hand-written combinators** that hold several inner futures and poll all of them on every wake, forgetting which ones finished. 2. **Select loops** that race the same future across iterations of a `loop`, for example by awaiting `&mut fut`: `&mut F` implements `Future` when `F: Future + Unpin`, so a loop that awaits it again after it completed polls a finished future. 3. **Tests** that poll by hand with `Waker::noop()` and keep calling `poll` in a loop. A concrete case: a sensor gateway pins one `read_sensor()` future with `pin!` and keeps it alive across a loop that also handles control messages, racing `reading.as_mut()` against the next message on each iteration. The first iteration in which the reading wins consumes its `Ready`. If the loop does not replace `reading` with a fresh future, the next iteration polls the finished one, and with a compiler-generated future the gateway panics with "`async fn` resumed after completion". The fixes are to break out of the loop, to re-create the future after it completes, or to fuse it and check `is_terminated()`. ## Making extra polls safe with `fuse` The futures crate offers **`FutureExt::fuse`**. Its docs say that if a fused future is polled after having returned `Ready`, it returns `Pending` from then on, and that it drops the inner future as soon as it completes. The result implements **`FusedFuture`**, whose `is_terminated()` reports whether the future should no longer be polled. The futures crate's own `select!` relies on this and requires fused inputs, so a branch that already completed is skipped instead of being polled again. Tokio's `select!` solves the same problem differently, which the Tokio material covers. ## Writing your own future defensively When you write a leaf future by hand, choose its behaviour deliberately: - store the output in an `Option` and `take()` it, panicking with a clear message on a second poll, as `Ready` does; - or keep a `done` flag and return `Pending` without registering a waker, which is what `Fuse` does; - never touch freed or moved-out data on the second call: that would be undefined behaviour, which a safe `poll` must never allow. ## Why the contract is loose Leaving the behaviour unspecified keeps every future cheap. A requirement to return `Ready` again would force every future to keep its output around, often impossible for a value that is moved out; a requirement to return `Pending` would force every future to carry a completion flag. Rust puts the cost only where it is needed, behind `fuse()`.
- Is polling a finished future ever undefined behaviour?Not through a correct future. poll is a safe method, so the Future docs require that no call causes undefined behaviour, whatever the state. A hand-written future whose second poll reads freed memory through unsafe code is unsound, and the bug lies in that future.
- Why does the futures crate's select! require fused futures?select! is usually called in a loop over the same futures. FusedFuture::is_terminated lets it skip a branch that already completed instead of polling it again, which the Future contract does not make safe.
- A finished future returns the same Ready value again on every poll.
- Polling a completed future is undefined behaviour.
- Every future returns Pending after Ready, so extra polls are harmless.
- Executors routinely poll a task again after its future completes.
- fuse() caches the output and returns Ready again on later polls.