Rust Async Working Group
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- 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.)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully