owned this note
owned this note
Published
Linked with GitHub
---
title: "Design meeting 2024-05-09: Liveness and backpressure"
tags: ["WG-async", "design-meeting", "minutes"]
date: 2024-05-09
discussion: https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async/topic/Design.20meeting.202024-05-09
url: https://hackmd.io/RblquL8zQdqscplFTKFGqw
---
# Discussion
## Attendance
- People: TC, tmandry, eholk, David Barsky, Vincenzo
## Starvation demo
TC: We've talked about starvation in the context of buffered streams that yield futures. I wanted to look at it in a different context, so here is a relatively short and self-contained demo of that to perhaps inspire discussion. There's a playground link at the bottom.
```rust
// This is a demonstration of starvation with `AsyncIterator` and `for
// await` syntax.
//
// The idea here is that we have a connection pool and the stream
// hands out one connection from it at a time. The user of this
// stream takes a connection and sends a message. The user wants to
// send only one message at a time (this is our bottleneck).
//
// The trouble is that the connections in this pool can timeout.
// Since we starve the stream during the body of the loop, we end up
// timing out the connections in our pool since we can't send
// keepalive messages.
//
// Author: TC
// Date: 2024-05-09
//@ edition: 2024
#![feature(async_for_loop, async_iterator)]
#![feature(precise_capturing, impl_trait_in_assoc_type)]
#![allow(incomplete_features, unused)]
use core::{
async_iter::AsyncIterator,
pin::Pin,
sync::atomic::{AtomicU64, Ordering},
task::{Context, Poll},
};
use std::collections::VecDeque;
fn main() {
block_on(async {
let mut limit = 30; // This is just so we can exit the loop.
let pool = Pool::new();
// We get a connection from the stream and send to it.
for await mut conn in pool {
// ^^^^
// ^ This is what gets starved.
match conn.send(()).await {
// ^^^^^^^^^^^^^^
// ^ This is what starves the pool.
Ok(_) => println!("Sent!"),
Err(TimeoutError) => println!("ERROR: Timed out."),
}
limit -= 1;
if limit == 0 { break; }
}
});
}
// This is a connection pool. Each connection must be kept alive
// periodically or it will time out.
struct Pool {
pool: VecDeque<Connection>,
}
// This is the critcal impl.
impl AsyncIterator for Pool {
type Item = Connection;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> { unsafe {
let mut this = self.get_unchecked_mut();
for x in &mut this.pool {
x.keepalive();
//^^^^^^^^^^^
// ^ This is the progress that gets starved.
}
this.pool.push_back(Connection::new());
Poll::Ready(this.pool.pop_front())
}}
}
// This is a simulation of wall clock time.
static TIME: AtomicU64 = AtomicU64::new(0);
impl Pool {
fn new() -> Self {
let mut pool = VecDeque::new();
for _ in 0..10 {
pool.push_back(Connection::new());
}
Self { pool }
}
}
// This is a connection. Note that it times out
// if we don't keep it alive.
struct Connection {
start: u64,
send_delay: NPending,
}
struct TimeoutError;
impl Connection {
fn new() -> Self {
let start = TIME.load(Ordering::Relaxed);
Self { start, send_delay: NPending(20) }
}
fn is_alive(&self) -> bool {
let now = TIME.load(Ordering::Relaxed);
now - self.start < 10
}
fn keepalive(&mut self) {
if !self.is_alive() {
return;
}
self.start = TIME.load(Ordering::Relaxed);
}
async fn send(&mut self, _: ()) -> Result<(), TimeoutError> {
if !self.is_alive() {
return Err(TimeoutError);
}
(&mut self.send_delay).await;
Ok(())
}
}
// Supporting code...
// This is an executor that also ticks the clock above.
use executor::*;
mod executor {
use super::*;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
pub fn with_context<F: FnOnce(&mut Context) -> T, T>(f: F) -> T {
const NOP_RAWWAKER: RawWaker = {
fn nop(_: *const ()) {}
const VTAB: RawWakerVTable =
RawWakerVTable::new(|_| NOP_RAWWAKER, nop, nop, nop);
RawWaker::new(&() as *const (), &VTAB)
};
let waker = unsafe { Waker::from_raw(NOP_RAWWAKER) };
f(&mut Context::from_waker(&waker))
}
pub fn block_on<F: IntoFuture>(f: F) -> F::Output {
let mut f = core::pin::pin!(f.into_future());
loop {
TIME.fetch_add(1, Ordering::Relaxed);
match with_context(|cx| f.as_mut().poll(cx)) {
Poll::Pending => (),
Poll::Ready(x) => break x,
}
}
}
}
// This is a future that returns `Pending` N times.
struct NPending(u64);
impl Future for NPending {
type Output = ();
fn poll(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Self::Output> {
if self.0 > 0 {
self.0 -= 1;
Poll::Pending
} else {
Poll::Ready(())
}
}
}
```
[Playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=726031a0edc54b34a2430fed7e0f0bf5)
## Spawning
David Barsky: Why not spawn a task to avoid timing out?
TC: You could do that, of course, but then you would need to propagate backpressure in a different way.
David: Usually I see backpressure handled with something like Tower, effectively something like `futures::Sink`.
TC: There are many ways to do this, including e.g. with channels. The question is, to what degree are we leading people into a liveness trap where anytime you write `for await` you must spawn a task or risk liveness issues?
David: I think there are reasons why you might want to do this; it's very dependent on the system itself.
TC: The main benefit of backpressure in systems design is that it's compositional. As long as every element in your system implements backpressure, you can plug them together and your entire system will exhibit backpressure. That backpressure will flow end to end through the entire system. This allows you to reason locally rather than globally.
TC: Once this becomes tied to liveness, however, this doesn't work. Future-like things that are starved of liveness are not compositional, and will be prone to deadlocks and other liveness issues unless global reasoning is employed.
TC: (Unless, perhaps, you were to define some shared starvation contract for your system and were to prove, e.g. with TLA+, that this restores compositionality somehow.)
David: I think we're on the same page about being compositional, but looking at the specific case, what you're referring to as starvation is a consequence of the way the author has written the code. My suspicion is that this is an inherent property of the fact that futures don't make progress until polled.
TC: That's not what I'm describing. The problem is the alternation between polling and then starving. We can wait as long as we want to before we first poll the future-like thing. That's why this is *not* starvation:
```rust
x.await; // Not starving `y`.
y.await; // Not being starved.
```
TC: Since we haven't polled `y` yet, it's not being starved as we await `x`.
## Terminology
David: I disagree about the terminology here.
tmandry: I agree "liveness" and "starvation" are overloaded terms, but what alternatives would you suggest?
David: Perhaps borrow from CPU profiling... "off-executor waking" comes to mind.
tmandry: It's good to have terms to talk about things, I found the way TC broke this down on Zulip helpful.
## Definitions
TC: Those definitions that tmandry mentioned are:
### Liveness guarantee
In the context of Rust, a *liveness guarantee* means that once we start polling a value, we must continue to poll that value in a *timely* manner until the poll function returns an indication that it should no longer be polled or until we decide to drop the value.
As an example, if the `Waker` unparks the thread responsible for polling the value and yet we park the thread again without polling it, then we are not polling it in a timely manner.
### Starvation safety
A type is *starvation safe* if, after each time the poll function returns a non-`Pending` value, the poll function *expects* that an arbitrary and extended amount of time might pass before the poll function is called again.
## Possible ways of solving this
tmandry: The ways of solving this include `ConcurrentStream`, which would use internal iteration, or `poll_progress`.
TC: Switching to internal iteration, *by itself*, isn't enough to solve this case.
tmandry: `ConcurrentStream` has a progress mechanism; it can enforce that that gets polled by owning the execution when you call `.for_each(||...).await;`
TC: Yes, if invoking progress is included in the definition of `for_each`, that certainly works. That's what I mean by internal iteration not being enough "by itself"; there still has to be a new place, on the impl side, where we encode how progress should be made.
TC: As an aside, we could conceivably express something like this with external iteration also (other than by `poll_progress`), with something like:
```rust
while let Some(x) = stream.next().await {
merge!(stream.progress(), x.work());
// ^^^^^^^^^^^^^^^^^
// ^ Progress stream.
}
```
TC: (Though that encoding in particular wouldn't pass the borrow checker.)
eholk: What's wrong with the internal iteration approach?
TC: Nothing; it can work. It's just that we need a place on the impl side to encode how the progress happens. I.e., we can't make the `poll_next` method written in the demo above work *just* by switching to internal iteration. We still need something else.
eholk: Ah, right. We need a generic place to call `keepalive()`. E.g.:
https://docs.rs/futures-concurrency/latest/futures_concurrency/concurrent_stream/trait.ConcurrentStream.html#tymethod.drive
```rust!
impl ConcurrentStream for Pool {
async fn drive(self, consumer: impl Consumer) {
join!(
async {
for x in 0..10 {
consumer.consume(x).await;
}
self.progress()
).await
}
}
// ..later..
pool.for_each(async |item| { ... }).await;
```
eholk: If we let streams overload `for_each` they can do whatever they want for progress and handle the interleaving between the closure and its own iteration state.
TC: Right. I.e., we make progress part of the monadic operator.
## Difference with sync code
David: Wouldn't a sync iterator have the same problem?
tmandry: Good point, you would need to spawn a thread in sync code.
tmandry: This makes me think it's the combinator APIs leading people astray.
David: My experience agrees
David: I'm also not satisfied with the general lack of guidance here, e.g. around spawning APIs...
TC (afterward): In sync code, `Pool` itself would have spawned a thread to handle the pool. Similarly, we could of course have `Pool` spawn a task in async code to handle this (and then, e.g., use channels), but we still need to define a liveness contract that tells people *when* they *must* spawn rather being able to rely on a future-like thing being timely polled.
TC (afterward): This is what's different from sync code. In sync code, the contract is clear (things not spawned block the thread). In async code, we have this more nuanced interplay. We can spawn things, and that's roughly like threads. But we can also have expectations around when non-spawned things are polled.
## Merging
eholk: I think these examples are more interesting if they involve a merge, something like:
```rust
let (tx, rx) = Channel::new();
for await event in merge(acceptor, rx) {
match event {
Left(new_connection) => {
spawn(handle_connection(new_connection, tx.clone()));
}
Right(request) => handle_request(request).await,
}
}
```
If `handle_request` takes a long time, we won't respond to new connections promptly. For the `rx` stream, presumably this is okay because it returned `Ready`, meaning it is in a state where it expects to not run for a bit. I.e., it would be *starvation safe* to use the language TC proposed.
TC: +1.
## Similarity between overriding `poll_progress` and overriding `for_each`
TC: These have many of the same properties because they are structurally similar. In both cases we're overriding something for a type so as to slot in progress.
eholk: `for_each` actually seems more powerful.
eholk: One thing I don't like about `poll_progress` is that if you race two `next()` futures you'll end up with the same problem; then we would need to thread `poll_progress` through futures as well to solve it.
TC: Agreed. Have you thought it through about how this works with layering different streams with different progress properties?
eholk: Not yet; need to think more about it.
TC: Intuitively, it seems this should still be OK.
## Is language syntax/semantics the right place to solve this problem?
eholk: The requirements for backpressure, buffering, etc. seem likely to be application-specific. Would we be better off providing various libraries, frameworks, runtimes, etc. to meet application-specific needs rather than finding a solution that works for everyone and building that into the language?
dbarsky: I'm sorta inclined to agree with eholk: today's ecosystem solve issues like this with things like `futures::Sink`, `tower::Service`, or spawning a task in the background.
eholk: Having the right primitives in the language to let libraries define their own policies is important though!
TC: I agree with this, modulo that 1) we still need to define and document the liveness guarantees for the constructs that we stabilize, and 2) it would be nice if we had a more powerful primitive that allowed these patterns to be written in a more direct style, as in the next item for us to discuss.
## Coroutine approach
TC: One thing I don't like about `poll_progress` is that it's not clear how this would lead to a first-class syntax for expressing these patterns in the language. We've been adding things like ATPIT, `gen`, and `async gen` so as to better avoid having to write state machines manually. It'd be nice if, whenever we need to encode progress, we don't have to drop back down to manual implementations.
TC: If we had coroutines, e.g., we could model this progress pattern directly using the `resume` argument:
```rust
let plates = Plates::new();
coro |mut ready_for_val| {
plates.spin(); // <-- The progress.
if !ready_for_val {
ready_for_val = yield None;
} else {
ready_for_val = yield plates.pop();
}
}
```
tmandry: This doesn't feel that much nicer than writing `poll_progress` manually, which you'll only need to do in "leaf" streams. Combinators will just propagate it. High level users would just use `for await` which magically polls it and propagates it.
TC: I work on, e.g. implementations of protocols. It's desirable to write these in a sans I/O style where all network calls are removed from the protocol implementation itself. These sort of protocols almost all need to handle progress. If our construct isn't powerful enough to express progress, then all of these must be written as by-hand state machines. Which is fine, but in many cases, it would be more elegant to be able to write these in a direct style and use the coroutine transformation.
eholk: I like `async gen` and like not having to drop down to lower level implementations. We can't do that with `DoubleEndedIterator` and other similar examples today. Don't know how to make it more powerful.
David Barsky: I don't think you would want a size hint or double-ended iterator on an async stream. In async use cases you usually can't.
eholk: I could imagine, e.g. an async file API where you could read from the beginning and end. But I agree that it will be less useful in an async world.
David: I'm thinking of APIs where you can do random access... not sure how they would map to streams.
eholk: Maybe you don't want to map to streams.
tmandry: A more powerful mechanism would be nice to have, but we don't need to shove it into AsyncIterator.
TC: Agreed, that's the idea. With a more powerful mechanism available (or planned), e.g. coroutines, we can just tell people not to use `AsyncIterator` in this way, document its exact limitations, and tell people what to use instead.
---
David: Maybe runtime instrumentation (e.g. tracing) is a good way to determine that you have this problem or are modeling your problem in the wrong way.
(The meeting ended here.)