Skip to content

RFC: add poll_progress to AsyncIterator - #4020

Open
oconnor663 wants to merge 3 commits into
rust-lang:mainfrom
oconnor663:poll_progress_squashed
Open

oconnor663 wants to merge 3 commits into
rust-lang:mainfrom
oconnor663:poll_progress_squashed

Conversation

@oconnor663

@oconnor663 oconnor663 commented Oct 19, 2026 •

Copy link
Copy Markdown

Fix "Barbara battles buffered streams" and iterator variants of "Futurelock" by adding poll_progress to AsyncIterator. Define a strict AsyncIterator contract for when poll_next and poll_progress should be called, mirroring the strict Future contract in RFC #4019.

To avoid burying the lede: Effectively deprecating StreamExt::next will probably be the most controversial part of this RFC. See "What about .next()?" in the Drawbacks section.

Important

Since RFCs involve many conversations at once that can be difficult to follow, please use review comment threads on the text changes instead of direct comments on the RFC.

If you don't have a particular section of the RFC to comment on, you can click on the "Comment on this file" button on the top-right corner of the diff, to the right of the "Viewed" checkbox. This will create a separate thread even if others have commented on the file too.

Rendered

Fix ["Barbara battles buffered streams"] and iterator variants of
["Futurelock"] by adding `poll_progress` to `AsyncIterator`. Define a
strict `AsyncIterator` contract for when `poll_next` and `poll_progress`
should be called, mirroring the strict `Future` contract in RFC TODO.

To avoid burying the lede: Effectively deprecating [`StreamExt::next`]
will probably be the most controversial part of this RFC. See "What
about `.next()`?" in the Drawbacks section.

["Barbara battles buffered streams"]: https://rust-lang.github.io/wg-async/vision/submitted_stories/status_quo/barbara_battles_buffered_streams.html
["Futurelock"]: https://rfd.shared.oxide.computer/rfd/0609
[`StreamExt::next`]: https://docs.rs/futures/latest/futures/stream/trait.StreamExt.html#method.next

### `for await`

We can't desugar this RFC's version of `for await` syntax into a loop ([like

@kpreid kpreid Oct 22, 2026 •

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.

I think this is a noteworthy change to the big picture of async. Right now, when teaching how async works, it is possible to say (and I have said) that

async/await by itself does not add concurrency; the execution of your async code, and the things it awaits, remains fully sequential. Writing async code just makes it possible to suspend execution. All concurrency is introduced either by executors or by combinators that implement Future manually.

(This helps explain things to people who are trying to achieve concurrency and don’t yet understand why just putting async on everything doesn’t help — perhaps because they are familiar with JavaScript async, where every async function call effectively spawns itself.)

With this change, that will no longer be true; for await will, all by itself, introduce concurrency between the loop body and the iterator. This is probably worth the conceptual complexity, but I think it should be called out more explicitly in the RFC as a cost to understanding and teaching async.


It also might be interesting to design a more primitive concurrency construct that for await can be desugared to; if there can be such a thing, it might be useful to offer to users for situations that need this same kind of concurrency but don’t fit async for.

@oconnor663 oconnor663 Oct 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

for await will, all by itself, introduce concurrency between the loop body and the iterator

If I understand you correctly, I think I disagree with this. If I write an async gen fn and then iterate over it with a for await loop ("just sprinkle some async on my code"), control will alternate between the two, and nothing will run concurrently. The observable behavior is the same as the non-async version. That's true of today's AsyncIterator/Stream, and it remains true under this RFC. I can't tell whether that was already clear.

What's different under this proposal is that, if I implement AsyncIterator manually -- similar to implementing Future manually like you mentioned -- I have the option of doing concurrent work in poll_progress. An async gen fn by itself won't take advantage of this option. If you want your for await loop or .for_each(...) closure to run concurrently with your async gen fn, you need to wrap it in an adapter like the Buffer1 example.1 However, for await loops and other consumers will wire up poll_progress appropriately for every iterator they loop over, in case any of those happen to be concurrent iterators like Buffer1/Merge/FuturesUnordered. Those poll_progress calls mean we can't desugar for await into a loop without breaking short-circuiting operators, but in simple "sprinkle async on it" situations they're all no-ops,2 and there isn't any real concurrent work.

The long discussion of the proposed "PollNext::Pending rule" (this section and the following section) is also relevant here, specifically:

there's a footgun: Map::poll_progress shouldn't always try to fill that buffer slot, or else the first loop above will start printing "NUMBER 1" while its body is sleeping.

Precisely because we don't expect ordinary async iterators to run concurrently with the loops that drive them, we need to think about how easy it is do that accidentally in manual implementations, which has implications for the details of the contract.

Footnotes

  1. Writing an inherently concurrent async gen fn could be possible if we added something like the hypothetical await all syntax in the "Future possibilities" section. ↩

  2. There's some discussion in the RFC about whether/when a generated poll_progress function should be literally a no-op that the optimizer can easily delete, vs something with asserts in it. I need advice here from folks with compiler experience. Maybe this is also something we can experiment with later without breaking backwards compatibility? Famous last words I know. ↩

@kpreid kpreid Oct 23, 2026 •

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.

for await will, all by itself, introduce concurrency between the loop body and the iterator

If I understand you correctly, I think I disagree with this. …

What's different under this proposal is that, if I implement AsyncIterator manually -- similar to implementing Future manually like you mentioned -- I have the option of doing concurrent work in poll_progress. An async gen fn by itself won't take advantage of this option.

I see, and I agree with your logic for the case I wrote out — it will still be true that you cannot choose to add concurrency by just asyncifying things, and we will still need to teach people that.

However, I think it also matters for teaching and debugging purposes that in this new world, for await will be introducing a scope in which concurrency occurs, which is something that async/await syntax (and for syntax) has never done before. (Today, join(a, b).await is concurrent but the concurrency is between parts of the join, not the join and something else.) It means that, if the code containing the loop and the async iterator have some interaction the developer cares about (whether an explicit one via interior mutability, or an implicit one via timing or peak memory usage), then the developer needs to think about the code in the loop body differently from the code outside the loop body, in a way other than just “the loop body is executed more than once”.

I don’t think this is a harmful thing, but it’s something that should be acknowledged prominently in the design (which the guide-level explanation already does) and in documentation.

Comment on lines +1059 to +1060
the docs, and a panic that says "there's a rule you didn't know about" is
better than confusing control flow bugs. We can't do this for the

@tmccombs tmccombs Oct 31, 2026 •

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.

Ok, so the panic might, maybe catch some kinds of bugs. But:

  1. panicking in this situation isn't guaranteed, it is also allowed to "misbehave" in other ways, which may be difficult to debug.
  2. In more complicated combinators, the panic may not be consistently reached, say because poll_progress is only called while poll_next is pending in certain situations. Which leads to the panic not getting caught until the code is "in production".
  3. I might argue that a panic is still a confusing control flow bug.
  4. Not being allowed to call to poll_progress on an iterator that is already pending could potentially make some implementations more complicated. For example, the imlementation of poll_progress for a Merge iterator would need to keep track of which if any children are in the pending state to ensure it doesn't call poll_progress on those.

All in all, I think it would be better to define the semantics of calling poll_progress while poll_next is pending as one of the following:

  1. (my preference) Return Poll::Pending, it may cause a spurious poll, but can also do nothing (a no-op).
  2. Return Poll::Pending and do nothing else. calling it is harmless, but should not change the state or do work on the future.
  3. Always panic. This is my least favorite, but at least the behavior is consistent.

For 1 or 2, the definition for Then::poll_progress would look like:

fn poll_progress(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
    if self.future.is_none() {
         self.project().stream.poll_progress(cx)
    } else {
        Poll::Pending  
    }
}

View changes since the review

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

panicking in this situation isn't guaranteed, it is also allowed to "misbehave" in other ways, which may be difficult to debug.

Note that this wording is modeled somewhat on our existing docs for Future::poll: "Once a future has completed (returned Ready from poll), calling its poll method again may panic, block forever, or cause other kinds of problems; the Future trait places no requirements on the effects of such a call." That doesn't make it necessarily the right thing to do, but I do think it makes sense for Future::poll to work that way.

In more complicated combinators, the panic may not be consistently reached

True. And continuing the analogy, there are also many futures that you can successfully poll even after they return Ready. Some document this as a feature (e.g. Fuse), and some don't (e.g. Sleep). However, the most common type of future is an async fn future, and the fact that those reliably panic means that most callers who make this mistake hit a panic quickly. I think if we do something similar with async gen fn, it will have a similar effect.

I might argue that a panic is still a confusing control flow bug.

For sure, I think panicking is just the lesser of a few evils here, and it's good and important that regular users writing regular async fn and async gen fn code won't be exposed to this stuff. Personally, the bug I'm most worried about is a combinator that violates the "PollNext::Pending rule" (like the "lazy" Merge implementation in the RFC) combined with an async iterator (like the "that's nice and simple, but is it correct?" Map implementation in the RFC) that's only correct if the rule is followed. That combination can cause hangs and deadlocks, and those will be murder to debug.

Not being allowed to call to poll_progress on an iterator that is already pending could potentially make some implementations more complicated.

Take a look at this section and the section after and tell me what you think about what I wrote there. In particular, I agree you that this rule makes Merge more complicated, but I'm worried that the alternative makes almost everything else more complicated.

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.

Those sections provide rationale for why calling poll_next is necessary, but IMO the motivation for forbidding calling poll_progress is rather weak. It adds a constraint on the caller that isn't really necessary.

I think the arguments in https://blog.yoshuawuyts.com/the-future-trait-has-a-missing-state also apply here.

What if in this case poll_ready is supposed to return a third state that means "you need to call poll_next"? Then the poll_ready implementation for merge could potentially just be calling poll_progress on each nested iterator, and if it gets back this third result it calls poll_next on that iterator and buffers the result if needed.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

If I understand you correctly, I think this approach would share some of the downsides of the "lazy merge" way of doing things described in the draft. For example, consider the Then adapter:

pub struct Then<St, Fut, F> {
    #[pin]
    stream: St,
    #[pin]
    future: Option<Fut>,
    f: F,
}

Under the "PollNext::Pending rule", its poll_progress method looks just like the trivial one for Map that I talked about in the two sections I linked above:

fn poll_progress(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
    self.project().stream.poll_progress(cx)
}

But in the world you're describing, where poll_progress can be called while poll_next is pending and must report whether poll_next ought to be called instead, we'd need it to look something like this:

fn poll_progress(self: Pin<&mut Self>, cx: &mut Context) -> PollProgress {
    if self.future.is_some() {
        // The future slot is populated! We don't have an item slot to capture its output,
        // so the caller needs to drive us with `poll_next` instead.
        return PollProgress::PleaseCallPollNextInstead;
    }
    self.project().stream.poll_progress(cx)
}

That's not crazy complicated in isolation, but I want to emphasize that Then is not a concurrent stream. This is new complexity that we'd be imposing on every stream that owns a future internally. (So not e.g. Take or Map, but including e.g. TakeWhile and Filter.) This would be very easy to get wrong. If we were supposed to write the second version above, but we wrote the first one instead, our broken Then would nonetheless appear to work most of the time. But in rare cases where it was the direct child of a Merge or similar, it would be prone to hangs and deadlocks. If my application locked up in production because of something like this, and I had to wade through GDB and Ghidra dumps to find this, I think I'd be angry at whoever designed AsyncIterator.

Here's a playground example of this mistake, using a modified AsyncIterator trait with a 3-state PollProgress enum. Ctrl-f for "Uncomment these 3 lines to fix the deadlock." You'll also find some other "XXX" comments where I think this approach creates awkwardness.

When I work through alternatives like this, I come out believing that these "nice to have" properties of the current draft are actually kind of critical:

  • Only concurrency primitives need to do anything non-trivial with poll_progress.
  • Even writing concurrency primitives, where we're talking about small amounts of code mostly written by experts, this sort of mistake is likely to panic in common cases.

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.

we'd need it to look something like this

That looks an awful lot like the implementation in the RFC text except with a return instead of a panic (from an assert).

And without the panic, then you could still get a deadlock without a panic if it gets stuck on the future.

but I want to emphasize that Then is not a concurrent stream

it kind of is. But the concurrency is between a future and a stream/AsyncIterator.

From the linked playground:

What should we do if we've already buffered an item, but the child stream demands that we accept another one? Here we just panic.

then you should return PollProgress::PleaseCallPollNextInstead so the caller can consume the buffered item.

@oconnor663 oconnor663 Nov 18, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

That looks an awful lot like the implementation in the RFC text except with a return instead of a panic (from an assert). And without the panic, then you could still get a deadlock without a panic if it gets stuck on the future.

The important difference is that the assert in the RFC version is optional. The only way it can fail is if an incorrect caller breaks the contract, and if we left it out the caller would still be at fault for the deadlock. But the return in the playground example here is mandatory, and forgetting it is enough to cause a deadlock all by itself. Then would be at fault in that case.

then you should return PollProgress::PleaseCallPollNextInstead so the caller can consume the buffered item.

Oh good point.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

the concurrency is between a future and a stream/AsyncIterator

It can be, but in my mind that's kind of in the same sense as how a regular iterator could spawn threads, and a regular .map() closure could end up running in parallel with those threads. That doesn't make .map() a "parallel iterator" in any way that the implementation need to pay attention to though. Same with async .then(). You can chain a dozen of them together, and there still won't be any concurrency in your program. (This is what kpreid was asking about above.) Only concurrency primitives like .merge() or FuturesUnordered or Buffer1 will do that.

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.

No, async then is different. The threaded equivalent would be something like a channel with a producer on another thread, and you call map on that with a function that spawns a thread to do something, then join that thread. It's not a great analogy though, because I'm not sure why you would spawn a thread just to immediately join it.

Say you have a Then implementation where poll_next() only calls poll on the future if it currently has a future. But the stream holds an async lock, and won't release it until the next time it is polled (either with poll_next or poll_progress), but the Future is waiting to acquire that lock too. Now you have a deadlock. But if Then calls poll_progress on the stream while polling the future, its fine.

I guess they don't need to be concurrent, but if they aren't you can get the same kind of deadlocks this RFC is trying to prevent.


(See "What about `.next()`?" below for a more complicated case.)

### [`tokio_stream::StreamExt::merge`] docs

@tmccombs tmccombs Oct 31, 2026 •

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.

I think it would be useful to see some example code of how AsyncIterator would be implemented on Merge (or FuturesUnordered) with this RFC.

View changes since the review

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

It's not in the text itself, but there's an example of implementing Merge in the fixed playground example in the Motivation section. Ctrl-f for "here's the sequence of events".

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.

Well. That is certainly more complicated, and more subtle, than existing implementations.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Substantially more complicated, absolutely. This is why I feel so strongly about isolating these concerns to concurrency primitives, and about panicking aggressively on top of that. Imagine tracking down the deadlock example I just linked above without knowing exactly what you were looking for.

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.

I'm not really sure what the solution is, but I am concerned that this makes writing any kind of "concurrency primitive" significantly more difficult. And even with aggressive panicking, and an author who knows what they are doing, I'm worried it would be easy to make mistakes.

And panicking when calling poll_progress doesn't really tell you either way, whether poll_next is called "promptly". That is, it is possible to not call poll_next promptly without ever calling poll_progress either, and it's also possible to call poll_progress, but also call poll_next promptly afterwards.

@madsmtm madsmtm left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Left a few comments mostly around clarifications, I'm not experienced enough in async to tell whether the exact details are right (though the idea seems solid).

I think it'd be nice to hear more from the ecosystem as well - I see that Alice has seen the other RFC, so I assume tokio people are aware of them, but I don't know if the futures maintainers are present here? I've pinged people on the Smol and Embassy Matrix channels now, that should maybe give this a few more eyes.

View changes since this review

Comment on lines +243 to +249
Depending on how it's implemented, `fetch_images` could be downloading the next
`jpeg` concurrently while `save_image` is running. A regular iterator could
potentially do something like that by spawning a thread, but threads complicate
borrowing and short-circuiting and usually require heap allocation. Async
iterators can do concurrent work without threads or allocations, and with full
support for local borrowing and straightforward behavior for `break` and
`return` (cancellation).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This helped me a lot in understanding this RFC: that AsyncIterator isn't just a weird Iterator<Item = impl Future>, but actually a proper combination of the two effects (and thus being able to poll while iterating is desirable).

Might be worth making more explicit? Though don't know how I'd write it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@yoshuawuyts thoughts?

could be an interesting optimization, but it's not clear whether anybody wants
that to be the fundamental building block of async iteration.

## Prior art

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A valid piece of prior art might be to investigate how the same situation would unfold if you replaced async with threads, and how the OS solves the problem?

I would also be very interested in how other languages handle this?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

RFC 4019 (the "strict" Future contract) has a section that compares futures to threads. It's a condensed version of this section in an earlier blog post, which does the same with more footnotes and a couple playground examples that I really like. It might make sense to link directly to one or both of those things from this RFC too.

My understanding is that OSs mostly "solve" this problem by either not letting you pause threads at all, or by putting scary warnings all over the functions (like fork and sigaction) that directly or indirectly pause threads. Bryan Cantrill also mentioned an interesting thread pausing bug that Solaris used to have here: https://oxide-and-friends.transistor.fm/episodes/futurelock/transcript. Ctrl-f for "the end to end scheduling model".

@madsmtm madsmtm Nov 15, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I read those examples, and I think they would be valuable to link, but I think I'd be more interested in if there's some OS equivalent to AsyncIterator that we could draw inspiration from?

Vaguely, some sort of "thread iterator" / rayon / epoll implementation details (I don't know what the analogous thing would be, that's why I'm asking ;) ).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I can't think of anything quite like what you're describing, but you did remind me that there are a lot of Rayon deadlocks that stem from the fact that the pool of worker threads is finite. If you manage to block all of them, no further work will happen, even if there's a waiting task that's going to somehow unblock everything. Not directly relevant here maybe, but one of the interesting cases where async Rust is actually easier to get right than regular sync Rust.

| `poll_next` returned `PollNext::Pending` | You must call `poll_next` again at the next wakeup. <ins><strong>`poll_progress` is not allowed,</strong></ins> and it might panic or otherwise misbehave (within the bounds of safe code). |
| `poll_next` returned `PollNext::Done` | You must not poll again. Either `poll_next` or `poll_progress` might panic or misbehave. |
| `poll_progress` returned `Poll::Pending` | You can call `poll_next` whenever you want another item, otherwise you must call `poll_progress` again at the next wakeup. |
| `poll_progress` returned `Poll::Ready` | No requirements. You can call `poll_next` whenever you want another item, or you can stop polling. Further calls to `poll_progress` are allowed but usually have no effect. |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Further calls to poll_progress are allowed but usually have no effect.

This feels weird, given that Future::poll has a requirement that once Ready is returned, you're not allowed to poll again?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Actually, does the return value from poll_progress even make sense? Why would you need to know whether the iterator is going to be immediately ready with a new item?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Note that returning Ready from poll_progress doesn't mean the next call to poll_next is guaranteed to return an item. This earlier bit is important:

When no more internal progress is possible without calling poll_next again, poll_progress returns Ready.

That is, returning Ready from poll_progress means something more like "I haven't registered any wakeups", not necessarily "I have a buffered item to give you". Non-concurrent async iterators like futures::stream::iter or TcpListenerStream will always return Ready from poll_progress, because they don't contain any futures* and don't do any work in the background.

* That said, you can make a Vec of futures and then convert that into a futures::stream::iter, and in fact that's what e.g. buffer_unordered expects you to do today. This might be an interesting corner case to consider in the RFC 4019 unresolved question about whether we want to warn when an idle future is retained across an .await.

This feels weird, given that Future::poll has a requirement that once Ready is returned, you're not allowed to poll again?

The main(?) reason Future::poll needs that rule is that Poll::Ready has a generic payload. Once a Future<Output=T> has handed you its T, it might not be able to conjure up another one on demand. On the other hand, poll_progress isn't generic. Its return type is always Poll<()>, so it can always return Ready(()).

I haven't seen any cases where the assumption "the caller won't call poll_progress again after Ready" would simplify a poll_progress implementation. (Even with that guarantee, the caller might call poll_next, get an item, and then call poll_progress again. If you've implemented that, then repeated calls to poll_progress probably already do the right thing.) At the same time, asking async iterator combinators to do the bookkeeping necessary to avoid calling poll_progress on their children again after they return Ready would be annoying extra work in a lot of cases. There's an unresolved question about whether for await loops should do that sort of bookkeeping internally, and I can see arguments for both sides.

@madsmtm madsmtm Nov 15, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This earlier bit is important

Ah, I missed that on my first read (or tbh skim) through.

Its return type is always Poll<()>, so it can always return Ready(()).

The first thing that comes to mind is that maybe a different type is appropriate then? Something like enum PollProgress { Pending, CallPollNext }?

In any case, I'm still not sure I understand why the caller needs to know that information? Does it make implementing FuturesUnordered more efficient or something?

I haven't seen any cases where the assumption "the caller won't call poll_progress again after Ready"

Yeah, that makes sense, I was mostly asking because I was mapping this to Future::poll semantics.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

There's a reasonable argument for having poll_progress just return (). That would actually remove a fair bit of boilerplate from concurrent stream implementations. The downside is that we couldn't implement hypothetical flags like the one described here: https://github.com/oconnor663/rfcs/blob/poll_progress_squashed/text/0000-poll-progress.md#should-for-await-loops-track-some-sort-of-progress-pending-flag.

(FuturesUnordered isn't the right category here, because it contains futures and not streams, but StreamMap might care about this. On the other hand, heap-allocating collections like those could accomplish something similar with Wakers, even if poll_progress returned (). I think the callers that might really care about this are no-std-compatible ones, including for await itself. This is one of the areas where I could go either way, and I hope someone can come up with a decisive reason to pick one.)

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.

#4020 (comment) could potentially be a reason to prefer having a return type (although I would kind of prefer a dedicated enum, or maybe even a boolean to returning Poll)

| Previous return | Requirements |
| --- | --- |
| `poll_next` returned `PollNext::Item` | You must <ins><strong>poll again promptly,</strong></ins> either `poll_next` if you want another item or `poll_progress` if not. |
| `poll_next` returned `PollNext::Pending` | You must call `poll_next` again at the next wakeup. <ins><strong>`poll_progress` is not allowed,</strong></ins> and it might panic or otherwise misbehave (within the bounds of safe code). |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: Wordings such as "might panic or otherwise misbehave" feels unnecessary here? These are invariants of the trait, and panic! or misbehave is what (safe) code does when invariants are broken, so it feels unnecessary to call out in this table?

Suggested change
| `poll_next` returned `PollNext::Pending` | You must call `poll_next` again at the next wakeup. <ins><strong>`poll_progress` is not allowed,</strong></ins> and it might panic or otherwise misbehave (within the bounds of safe code). |
| `poll_next` returned `PollNext::Pending` | You must call `poll_next` again at the next wakeup. <ins><strong>`poll_progress` is not allowed.</strong></ins> |

(If you really want to state this, then maybe state it for all the requirements/invariants instead of only some of them?)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

As written it's kind of echoing this part of the Future::poll docs:

Once a future has completed (returned Ready from poll), calling its poll method again may panic, block forever, or cause other kinds of problems; the Future trait places no requirements on the effects of such a call. However, as the poll method is not marked unsafe, Rust’s usual rules apply: calls must never cause undefined behavior (memory corruption, incorrect use of unsafe functions, or the like), regardless of the future’s state.

Also @RalfJung distinguishes "safety properties" from "liveness properties" in his comments on RFC 4019. It might make sense to explicitly allow panicking when one of the former is violated, but not the latter? Or maybe allow panicking specifically as a possible implementation of deadlock detection, but not other forms of misbehavior? I don't have much intuition about these concepts myself.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think I agree that it makes sense to call this out in API docs, as sort of a teaching tool of "what is safety" (Eq has a similar notice).

Also @RalfJung distinguishes "safety properties" from "liveness properties" in his comments on RFC 4019. It might make sense to explicitly allow panicking when one of the former is violated, but not the latter?

Took me a little while to grok that (because my brain understood "safety property" as "soundness"), but yeah, that makes sense.

Maybe change the table to | Previous return | Requirements | Effect if violated |? Or add to "poll_next returned PollNext::Item`" that not calling promptly might lead to deadlocks?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It is usually impossible to panic upon violation of a liveness property -- the very definition of a liveness property is that any prefix of an execution can be continued in a way that makes the liveness property true.

But calling poll_progress when it is not allowed to be called is a violation of a safety property and panicking seems fine. (Maybe I am missing some context here.)

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.

But calling poll_progress when it is not allowed to be called is a violation of a safety property and panicking seems fine.

but there isn't any reason it needs to be a safety property. AFAICT the only purpose for forbidding calling poll_progress is so to help you catch if you call poll_progress when you should be calling poll_next. But if poll_progress would just return instead of panicking, it wouldn't really break anything. Future::poll has to panic in some situations, because the value in Poll::Ready is owned, so after the future completes, the Future may no longer have a value to return in Ready, and there isn't anything to wait on for Pending. But in the case of poll_progress, that isn't an issue. poll_progress could just return Poll::Ready<()> instead of panicking.

Comment on lines +474 to +475
Instead we can describe the steps `for await` takes internally, [the same way
`.await` is described][await]. To evaluate the expression:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I find this list hard to parse. Maybe it would make sense to add an example for await expression and the desugaring for it?

Alternatively, I see that the reference docs for .await also has an approximate desugaring, I think the same idea would help here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Oh that's a good idea. It might be that what we need here is an approximate desugaring for for await plus a modified approximate desugaring for .await. The loop needs to add its iterator to some virtual list of "active async iterators" (because for await loops can be nested) and then any .await in the body needs to call poll_progress on each active iterator right before the yield Poll::Pending line of pseudocode. The "call poll_next to get the next item" part of the for await desugaring also counts as an .await in this sense, with respect to any other for await loops it might be nested under.

| --- | --- |
| `poll_next` returned `PollNext::Item` | You must <ins><strong>poll again promptly,</strong></ins> either `poll_next` if you want another item or `poll_progress` if not. |
| `poll_next` returned `PollNext::Pending` | You must call `poll_next` again at the next wakeup. <ins><strong>`poll_progress` is not allowed,</strong></ins> and it might panic or otherwise misbehave (within the bounds of safe code). |
| `poll_next` returned `PollNext::Done` | You must not poll again. Either `poll_next` or `poll_progress` might panic or misbehave. |

@tmccombs tmccombs Nov 18, 2026 •

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.

The nicest behavior for this case, from the caller at least, would be if the iterator continued to return Done indefinitely.

I'm not sure that that necessarily needs to be a requirement, it isn't for Iterator, but at the very least, it should be something that is a allowed if the AsyncIterator specifies that it is safe. And maybe have a FusedAsyncIterator trait to mark implementations that continue to return PollNext::Done after completion.

View changes since the review

| Previous return | Requirements |
| --- | --- |
| `poll_next` returned `PollNext::Item` | You must <ins><strong>poll again promptly,</strong></ins> either `poll_next` if you want another item or `poll_progress` if not. |
| `poll_next` returned `PollNext::Pending` | You must call `poll_next` again at the next wakeup. <ins><strong>`poll_progress` is not allowed,</strong></ins> and it might panic or otherwise misbehave (within the bounds of safe code). |

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.

But calling poll_progress when it is not allowed to be called is a violation of a safety property and panicking seems fine.

but there isn't any reason it needs to be a safety property. AFAICT the only purpose for forbidding calling poll_progress is so to help you catch if you call poll_progress when you should be calling poll_next. But if poll_progress would just return instead of panicking, it wouldn't really break anything. Future::poll has to panic in some situations, because the value in Poll::Ready is owned, so after the future completes, the Future may no longer have a value to return in Ready, and there isn't anything to wait on for Pending. But in the case of poll_progress, that isn't an issue. poll_progress could just return Poll::Ready<()> instead of panicking.

Comment on lines +1059 to +1060
the docs, and a panic that says "there's a rule you didn't know about" is
better than confusing control flow bugs. We can't do this for the

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.

we'd need it to look something like this

That looks an awful lot like the implementation in the RFC text except with a return instead of a panic (from an assert).

And without the panic, then you could still get a deadlock without a panic if it gets stuck on the future.

but I want to emphasize that Then is not a concurrent stream

it kind of is. But the concurrency is between a future and a stream/AsyncIterator.

From the linked playground:

What should we do if we've already buffered an item, but the child stream demands that we accept another one? Here we just panic.

then you should return PollProgress::PleaseCallPollNextInstead so the caller can consume the buffered item.


(See "What about `.next()`?" below for a more complicated case.)

### [`tokio_stream::StreamExt::merge`] docs

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.

I'm not really sure what the solution is, but I am concerned that this makes writing any kind of "concurrency primitive" significantly more difficult. And even with aggressive panicking, and an author who knows what they are doing, I'm worried it would be easy to make mistakes.

And panicking when calling poll_progress doesn't really tell you either way, whether poll_next is called "promptly". That is, it is possible to not call poll_next promptly without ever calling poll_progress either, and it's also possible to call poll_progress, but also call poll_next promptly afterwards.

[drive_next]: https://github.com/oconnor663/drive_async_iterator
[loop_select_deadlock]: <https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&code=use+futures%3A%3AStreamExt%3B%0Ause+futures%3A%3Astream%3A%3AFuturesUnordered%3B%0Ause+tokio%3A%3Aselect%3B%0Ause+tokio%3A%3Async%3A%3AMutex%3B%0Ause+tokio%3A%3Atime%3A%3A%7BDuration%2C+sleep%7D%3B%0A%0Aasync+fn+work%28%29+%7B%0A++++static+LOCK%3A+Mutex%3C%28%29%3E+%3D+Mutex%3A%3Aconst_new%28%28%29%29%3B%0A++++let+_guard+%3D+LOCK.lock%28%29.await%3B%0A++++sleep%28Duration%3A%3Afrom_millis%28rand%3A%3Arandom_range%280..5%29%29%29.await%3B%0A%7D%0A%0Aasync+fn+more_work%28%29+-%3E+impl+Future%3COutput+%3D+%28%29%3E+%7B%0A++++sleep%28Duration%3A%3Afrom_millis%281%29%29.await%3B%0A++++work%28%29%0A%7D%0A%0A%23%5Btokio%3A%3Amain%5D%0Aasync+fn+main%28%29+%7B%0A++++let+mut+futures+%3D+FuturesUnordered%3A%3Anew%28%29%3B%0A++++loop+%7B%0A++++++++select%21+%7B%0A++++++++++++%2F%2F+Add+more+jobs+as+they+come+in.%0A++++++++++++job+%3D+more_work%28%29+%3D%3E+%7B%0A++++++++++++++++println%21%28%22got+a+job%22%29%3B%0A++++++++++++++++futures.push%28job%29%3B%0A++++++++++++%7D%0A%0A++++++++++++%2F%2F+Handle+the+outputs+of+running+jobs.%0A++++++++++++Some%28_%29+%3D+futures.next%28%29+%3D%3E+%7B%0A++++++++++++++++println%21%28%22finished+a+job%22%29%3B%0A++++++++++++++++work%28%29.await%3B+%2F%2F+Deadlock%21%0A++++++++++++%7D%0A++++++++%7D%0A++++%7D%0A%7D>

If we use a helper function like this inside an `async gen fn`, we won't be

@tmccombs tmccombs Nov 19, 2026 •

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.

This, in particular seems like a really big downside to this proposal. Whether it is the linked hypothetical syntax or something else, I think there should probably be some solution to this as part of async gen fn.

View changes since the review

## Drawbacks
[drawbacks]: #drawbacks

### What about `.next()`?

@tmccombs tmccombs Nov 19, 2026 •

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.

I think there may actually be a way to keep .next().

Specifically, if the Next future implementation continues calling poll_progress() on the iterator, and doesn't return Ready yet until the poll_progress returns Poll::Ready.

I put together a playground with a proof of concept.

It does require that the underlying iterator eventually returns Poll::Ready from poll_pending, and doesn't just return Poll:Pending forever. And it also means there may be a delay before getting the result of Next.

It may be worth having the helper function and/or the concurrency syntax as well.

View changes since the review

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It does require that the underlying iterator eventually returns Poll::Ready, and doesn't just return Poll:Pending forever.

imo if next() has to have semantics like that, then we'd be better off not naming it next() since intuition from Iterator will totally mislead you.

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.

I don't follow. Iterator doesn't have an equivalent of poll_progress so I'm not sure why intuition from Iterator would mislead you.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Because I don't expect most people writing async code to know or care about poll_progress, they just want their code to work how they expect (just like iterators but async), and next() breaks expectations by either not polling the stream once next() returns Ready(_) or by delaying returning Ready(_) well beyond what they'd reasonably expect.

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.

In most cases, I don't think people would have to care about poll_progress. Yes, it could possibly be delayed a little longer than you might expect, but the same could be true for an iterator that doesn't return an item as soon as it is available.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

delaying potentially infinitely (if the stream always has background work) longer than expected is imo a foot-gun. I think delaying "a little longer" is definitely underselling the problem.

Comment on lines +1231 to +1237
Almost! One difference is that the `Merge` struct will (probably) always
forward `poll_progress` to both its children, even in the case where
`poll_next` has never been called (e.g. on the right side of a [`Chain`]). But
in this `async gen fn` version, if `poll_next` has never been called, then
control hasn't entered either of the `for await` loops. We haven't done the
`IntoAsyncIterator::into_async_iter` conversion yet, and we won't/can't forward
`poll_progress`. That might be an unfortunate footgun.

@tmccombs tmccombs Nov 19, 2026 •

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.

What if it was something like:

for await all item in self {
    yield item;
} and item in other {
    yield item
}

and poll_progress will proceed far enough to construct both child iterators, and call forward poll_progress to them.

View changes since the review

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.

6 participants