by dcow · 3y ago · 0 comments
Even though Rust does slightly skirt the colored function issue, my code still bifurcates because truly correct async code needs to use async variants of the standard lib for file access. Knowing when something you call blocks, or grabs a lock, etc. is something which the compiler doesn’t help you with but should. And then how the hell are you supposed to use any code sanely when the entire community is using different async runtimes? Why can’t the runtime be part of the core language with hooks into parts that might need to be customized in hyper special cases?
It really feels like we lost the steam behind async Rust and we’ve got this partially complete thing that’s neither high level enough to be convenient nor low level enough to be fearlessly correct. Async traits still aren't a thing and it’s been years.
It's not that big of a deal in practice. You pick a runtime. Most of the library ecosystem doesn't care about the async runtime used, and that which does uses tokio.
> Why can’t the runtime be part of the core language with hooks into parts that might need to be customized in hyper special cases?
Because Rust ships a minimal runtime.
> Async traits still aren't a thing and it’s been years.
They were blocked on generic associated types which landed recently, and will land in stable in the near future. For everything else there's `#[async_trait]`.
Also, "fearless concurrency" is a lower level kind of "fearless" than "how do I use an async API." It's about memory safety and program soundness in the presence of concurrent execution. The fact that the only fears we have are about the ecosystem and APIs is a testament to how Rust eliminated the deep fear of concurrent execution.
And if we're going to take a shot at async, let's take a shot at how fucking hard it is to implement a correct async executor and how bad the docs are. std Rust does next to nothing to abstract or make your life easier.
“minimal runtime” is semantics. Rust shipped async. IMO that would expand the definition of what is minimal for Rust to include in the runtime. I’m 100% certain no async anything would need to make it into programs that don't use async so the surface area of the runtime need not change for anybody unduly if Rust supported async.
I’m not saying Rust hasn't made async things better. It has. But it’s still really messy. It doesn't give me the same peace of mind that Rust does around memory safety.
And that’s my gripe. I admit it’s a rather privileged one. But that’s Rust’s fault. Rust has shown me how nice it is to fight with the complier till I want to scream if it means my program isn't going to have dangling pointers everywhere. I am a lazy dev and want the same for my concurrent code. Rust currently doesn't deliver on that promise, IMO. And it surely could with some continued work and slight philosophy adjustment.
It’s literally incorrect to use parts of Rust’s stdlib from async code. You can’t tell me that’s a good thing. C.f. Swift where the async support is thoroughly cooked into the language, runtime, and stdlib. Rust can do better here.
I agree that this is a problem, which is why "providing an abstraction layer for runtimes" is something that comes up often as a desired project, but if you zoom out I believe the choice to not have a baked in runtime was the right call. It allowed schedulers to experiment with their APIs and internals in a way that anything in the stdlib can't. It allowed for the existence of schedulers for embedded devices. You can write a keyboard firmware using async/await to deal with IO events! How cool is that?
Granted, if you're working in a single "vertical", like web services, this sounds like "useless gold plating", but precluding use cases like that one would go counter to Rust's goals. If Rust didn't care about the language scaling from embedded to HPC, then you could indeed have "Easy Rust" that erases a bunch of sharp edges of the language.
> Rust can do better here.
The team agrees. We're working on it. It was a major area of focus on 2021 and wg-async still exists and is making progress. Some things take time be finished because there's a lot to do, not enough people and they are just plain hard.
Anyway, I don't keep up day-to-day on Rust happenings. I'm just a user of the language who sometimes needs to dive into the issue tracker when I run into bumps. If all this stuff is being worked on then awesome, simply take my critique as validation that you're working on the right stuff. At the end of the day, though, my experience and feedback is driven by what's currently available to me, not what's in the works but hasn't shipped yet. And part of my critique is that it takes quite awhile for Rust to move on issues that really only exist because something was shipped in a partially completed state. Perhaps the community could be more aggressive with the notion of a version 2.0 and that would unlock changes that are really difficult and annoying and time consuming to make in a compatible way but would be much more palatable if allowed to break a few things here and there. It's great that we have nightly Rust, but perhaps it's about time for a rust-next where people can start staging breaking changes.
Managing concurrency outside of Rust and then calling Rust for the more focused and specialized work is a good combination IMO.
> Lunatic's design is all about super lightweight processes. Processes are fast to create, have a small memory footprint and a low scheduling overhead. They are designed for massive concurrency.
> Lunatic processes are completely isolated, with a per-process stack and heap. If a process crashes, it won't affect others in the runtime.
I don't understand. Is each Lunatic process an OS process or not? If it is, it sounds anything but lightweight. If it is not, it is not "completely isolated", at least not in the usual sense of the word.
Well that's where lunatic comes in. Lunatic provides the isolation and abstraction so you can run various wasm binaries side by side. If one of those binaries segfaults, lunatic presumably catches the interrupt and kills the corresponding wasm instance that caused it rather than just giving up and crashing.
Having use async/await in production a bit, I wouldn't really recommend it to anybody: the async runtimes are large dependencies typically that are difficult to roll your own, understand or debug. Code built on top of them has numerous performance issues that I uncovered when running it through it's paces. Much as I'm a fan of Rust, a fan of async await, I am not.
I have no idea about this myself, it's just a bit of public opinion that felt worth noting in the back of my mind!
The main reason to use async in rust is that seemingly every network library uses async. And of course servers that would have to start a huge number of threads without async, though from a performance standpoint many servers could honestly live without it.
Yes. I was calling that "async contamination" a few years back when that trend started. There's a strong lobby for doing web backend stuff in Rust, and they want it to work like Javascript.
On the thread side, deadlocks can be a problem. You don't get any help from the language in keeping your lock hierarchy consistent. There are systems that can detect at compile time that one path locks A before B, and another path locks B before A. Rust needs such analysis.
It turns out that the built in mutexes are not "fair". Actually, they're worse than not fair. If you have two thread loops that do "get item, lock, handle item, unlock", one of them can be starved out completely. This happens even though there's a moment when the mutex is unlocked and something is waiting on it. It's a consequence of an optimization in std::sync::Mutex for the fast case.
The "parking_lot" crate has fair mutexes, but it doesn't have panic poisoning and is not unwind safe, so catching failed threads to get a clean shutdown is hard. This is an issue for GUI programs, because failing to catch panics means the user experience of a failure is that the window closes with no message.
The 98% solution to this problem is to dodge it entirely. Communicate with things like channels, mailboxes, and actors, or other higher-level primitives. This is how Go programs hold together in general despite not even having as much support as Rust does for this sort of analysis.
The rule I've given to my teams is, never take more than one lock. As soon as you think you need to, move to an actor-ownen-resource or something. The "real" rule (as I'm sure you know, but for others) with multiple locks is "always take them in the same deterministic order" (and even that's a summary, it really also ought to discuss how only mutexes that can ever be taken at the same time have to be considered in order, and heck for all I know it gets complicated beyond that too; at this point I bug out entirely) but this is, in my opinion, the true source of "thread hell" as written about in the 90s. I don't think it was threading that was intrinsically the problem; yes, threads are more complicated than a single thread, but they're managable with some reasonable guard rails. What was insane was trying to do everything with locks.
In theory, this rule breaks down at some point because of some transactionality need or another; in practice, I've gotten very far with it between a combination of being able to move transactionality into a single actor in the program or offload it to a transactionally-safe external DB. For which, much thanks to the wizards who program those, test those, and make them just a primitive I can dip into when I need it. Life savers, those folk.
Isn't it easy though to use an async function as a blocking function, by polling in a loop? (though maybe that still requires an async runtime?)
https://docs.rs/crossbeam/latest/crossbeam/channel/index.htm...
still some options that don't require async:
attohttpc
oxhttp
ureq
But in theory, because of the I/O, it should be much more efficient to run this async. So I tried doing it async on a single thread to start with. That was a bit more difficult to get working, just because of all the messiness around async. And it was much slower because of the single thread.
I then tried to get that working with multiple threads. That proved problematic. I tried libraries like par_streams but ran into issues. I ended up using Tokio’s buffered_unordered to get a simpler setup with a pool of Tokio tasks.
This ended up giving quite unpredictable performance and being very heavy on memory usage. It seemed like it was going to need quite a bit of tweaking to get it to work as smoothly as the multithreaded version. I ended up abandoning it, since I didn’t have time to debug the black box of Tokio’s internal scheduling.
The lesson I took from this is that unless you have a really strong need to use async, multithreaded is going to be a lot easier and more reliable to implement, and the code will be much more transparent, not littered with awaits and complex Future type signatures.
I'm not sure why people are disagreeing with this: how would you cancel UdpSocket::recv without an async runtime? If you're using just the sync UdpSocket, you will need to go set a read timeout and repeatedly poll and insert your own cancellation points, or otherwise jury-rig your own mechanism up with syscalls to select/epoll/whatever, and be careful the whole time you're not leaking anything. However, if you're using an async runtime, you only have to drop the future and the recv is cancelled and the FD is dropped from the scheduler's waitset and everyone is happy.
And that's usually where the zero-cost [compared to hand rolling it] abstractions come in, but it turns out that's not enough, we would also need composability (decomposability to be precise), because async Rust is doing a lot, especially if you need only the cancellation feature.
Stepping back, it all depends on the development budget and goals. If time is short but there's plenty of RAM and performance budget, just go with Tokio. If that's too bloated, go with something low-level, eg. mio, and if you need every last bit of performance, then you are basically bargaining with the kernel anyway, so io_uring, and XDP (eBFP) ... and along the way there are potential stops at Seastar (a C++ framework) and dark alleys like DPDK (https://talawah.io/blog/linux-kernel-vs-dpdk-http-performanc...) :)
Light threads + messaging (whether proper like Erlang or bastardized like Go) feels like far superior model for concurrency in near-all cases and also easier to write and reason about (series of "functions" sending messages looks very similar to serial code) but I'd imagine it would be very hard to make convenient in GC-less language
I've been coming to the same conclusion after working with C# async/await significantly in the last few years. I suspect that async/await in javascript was better than callbacks, so it entered the industry zeitgeist as absolutely good as opposed to relatively good.
Honestly, and this might be a hot take, but I think that's easy to solve. Just pretend that tokio is in the standard library and use it. And refuse to support anything else. Tokio is stable, fast, well maintained and supported. There's really no reason to use anything else in 98% of cases.
If yall want everyone to use Tokio then tell me why it's better than async_std. Tell me why it's the de-facto community standard. Because "popular web framework" uses it? Why are all the cool kids using it? Because the others are?
No. Either I want some group with authority to bless a core async runtime implementation that aligns with Rust's philosophy and value prop and bring it under their wing so that it can be made to serve the goals of the project which might include being configurable enough to deploy in all of the myriad scenarios and environments where people use Rust today.
Or in lieu of that, provide the necessary abstraction layer so everyone can bring their own executor like it's supposed be.
The entire premise of Rust not providing a blessed implementation is so that people could pick and choose based on their preferences and use cases. That's the argument. The reality is that the goal is not realized because Rust has not done the work to enable everyone to simply bring their own runtime and call it day. So Rust has not delivered on the core reason for not shipping a runtime in the first place.
The solution of "just use a de-facto blessed runtime" really seems like a concession if Rust's argument for not having one is to be respected.
Hmm, if Tokio is the de-facto community standard, isn’t that saying that the authority of “people who write and run async code for actual production systems” is blessing it as a preferred option?
> The reality is that the goal is not realized because Rust has not done the work to enable everyone to simply bring their own runtime
Or, another possibility is that it hasn’t been realized because building a robust, production-ready, well-maintained runtime is itself a lot of work, and Tokio is the only project that has actually done it.
Being the most popular async runtime (a de-facto status) is one thing. Being a community standard voted on by the rust community and blessed as such is another.
> Or, another possibility is that it hasn’t been realized because building a robust, production-ready, well-maintained runtime is itself a lot of work...
The Rust people only need to provide a standard async abstraction layer, not build the runtime.
Then everyone can bring whichever runtime they want, which is the argument for why Rust doesn't ship/bless one.
Basically Rust wants to have its cake and eat it too. "We don't want to add an async runtime to rust because rust has a small runtime that only supports some of the features the language offers and we want to enable people to interchangeably use their own based on their own use cases and needs." vs the reality that "In order to use their own runtimes interchangeably would require an async abstraction layer which we also don't provide."
So we're left with the worst of both worlds. We have neither (a) a blessed community standard so other runtimes can die, nor (b) an abstract interface atop which authors can write async code and beneath which runtime implementers can hook in interchangeably. We have (c) a bunch of disparate little runtime ecosystems with their own sets of compatible code which can't be used together.
But now it feels productive, and if you're totally in the async world, it all works pretty well.
The lack of async traits is my main pain point today, but you can mostly work around that with the async_trait crate. Generally it's been slow progress on usability but I think it's in a much better place than it was a year ago, and will clearly be better in another year.
https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-i...
Although I'm still not sure how they return the unsized Future without the whole pin box method
trait Foo {
type bar_Returns<'s>: Future<Output = Result<u64, ()>>
where Self: 's;
fn bar<'s>(&'s self) -> Self::bar_Returns<'s>;
}Are not colored functions precisely the compiler helping you identify when the code has the potential to block? If I write a block of JS in a non-async function context, I can be 100% guaranteed that no other task will interfere with my function's execution. If I write a block of JS in an async context, I can be 100% guaranteed that the only times when any other task may interfere with my functions execution are explicitly marked with `await`. I love this! I can't imagine writing serious code without it (barring some go-like messaging model), and I have no idea why people hate it so.
> If I write a block of JS in an async context, I can be 100% guaranteed that the only times when any other task may interfere with my functions execution are explicitly marked with `await`. I love this!
You only need to think about it because runtime isn't parallel. If you want ordering in execution you should be using synchronization primitives anyway.
In Go doing "async" via channels could possibly start running the code the instant you instantiate it, on however cores there are available. Go have problem of that requiring a bunch of boilerplate (as there is no macros), but with generics now it is manageable and I can just say "here is function, run it on all elements of the slice in parallel" very easily and it all be pretty reasonabe, like
out = ParallelMapSlice(mapFunc,8,in)
All done async without thinking about async.It should be noted that similar code is possible in JS with WebWorkers. Async/Await is more for same-thread concurrency.
The term blocking isn't well defined. How slow does an operation have to be to be considered blocking? There are no rules. Fetching google.com/robots.txt is by universal agreement a blocking operation. Reading a file from the filesystem is considered blocking in JS but may not be in other languages, especially given that very fast disks like Optane or modern NVMe Flash can be only an order of magnitude or two slower than RAM. Taking a lock may or may not be considered blocking. Computing pi to a trillion digits would usually not be considered blocking because it doesn't make any async OS API calls, even though it might cause long delays before it returns, but if the author chose to implement it as an async iterator then it could be considered blocking.
Worse, async vs not async is about latency requirements of the caller, but the function author can't know that. If you're in a UI thread doing 60fps animation maybe even reading a file would be too slow, but if you're in a script then it doesn't matter at all and you'd rather have the simpler code. You're calling the same function, the only thing that changed is the performance requirements of the user.
So "potential to block" is to some extent a makework problem that occurs in JS because V8 isn't thread safe, and V8 isn't thread safe because JS isn't, because it was designed for the web which is a kind of UI toolkit. Such toolkits are almost never thread safe because it's too much hassle to program a thread safe renderer and would make it too slow, so that browser-specific implementation constraint propagates all over the JS ecosystem.
Final major problem: some languages use async hype as an excuse to not properly support threads at all, but that's often the only way to fully exploit the capabilities of multicore hardware. If your language only does async you'll always be restricted to a single core and you have to hope your use case parallelizes embarrassingly well at the top level.
If you have threads then this whole problem just goes away. That's the core argument that Java makes with Project Loom. Instead of introducing colored functions everywhere with poorly defined and inconsistent rules over which color to use, just make threads work better. Suddenly the binary async/not async distinction becomes irrelevant.
Still, there's a good reason most languages don't do the Loom approach. It's a massive PITA to implement. The Java guys are doing it because of their heavy investment in advanced VMs, and because the Java ecosystem only rarely calls out to native code. It'd be a lot harder in an ecosystem that had less of a focus on "purity".
The rule is very simple IMO, I already described it: if other execution can run while you wait for the value, it's blocking. (Edit: to be specific, other observable execution, so in your thread with write access to state you can see)
> Worse, async vs not async is about latency requirements of the caller,
I disagree. To me, async vs not async is about interruptibility. As you already mentioned, the code that computes a trillion digits of Pi is async if its interruptible, and not async if it isn't. If you're in a UI thread doing 60fps animation, async vs not async isn't really all that relevant (barring the slight inherent overhead in calling an async function). What you need is a profiler to tell you where you have a non-interruptible block consuming your 16ms. The compiler can't know this a priori, unless you make significant restrictions to the type of code you write (no unbounded loops, for instance).
> Such toolkits are almost never thread safe because it's too much hassle to program a thread safe renderer and would make it too slow, so that browser-specific implementation constraint propagates all over the JS ecosystem.
From here on you seem to not be aware of the fantastic recent developments in WebWorkers, it is now quite easy to spin up worker threads in JS, which communicate with the main thread via message passing.
is gmtime() blocking ? Technically it needs to ask kernel to get the time so it has same potential to block as any other call
> As you already mentioned, the code that computes a trillion digits of Pi is async if its interruptible, and not async if it isn't.
Very bad definition as either
* every single code is because kernel can always reschedule thread to do something else * none of the compute code is if language runtime can't interrupt it (old versions of Go had that behaviour for tight loops IIRC) * every of compute code is if language can arbitrarily interrupt it.
> From here on you seem to not be aware of the fantastic recent developments in WebWorkers, it is now quite easy to spin up worker threads in JS, which communicate with the main thread via message passing.
That's entirely worse approach as sharing any data structures is impossible and where mutex would be enough you're now shoveling tons of data around. It's workaround at best
It's like saying "my language is multithreaded because we started many processess and communicate via redis"...
> if other execution can run while you wait for the value, it's blocking.
How does that not capture any operation with a callback, and why does this definition depend on being "in your thread"? I don't think this is a definition that's widely used or understood.
> async vs not async is about interruptibility
By this definition Java fully supports async functions, because you can call Thread.interrupt() on any thread at any time. But I think most people would say Java doesn't do what is commonly understood by "async" including the Java developers themselves.
(What I meant by partially skirting the colored function issue is that you don't have to call await on the result of a function if you dint want to. So you can call a blue function from a red function just fine and do stuff with the result. You just can’t await it. This adds back lots of flexibility that some async impls in other languages don’t allow for.)
By this do you mean you can choose between waiting for a value in a way that halts the entire rest of the runtime while it resolves and one that will attempt to perform other tasks while waiting for the resolution?
Any time you call an async function you get a Future. The future does not resolve until you await it. So you can call an async function from a non-async function normally and do things with the future. You just cant call future.await to yeild until the result is is ready unless you’re in an async context. You can ask the runtime to resolve the future if you want, but that’s a blocking call so it’s up to you to make sure it’s safe to block.
> If I write a block of JS in an async context, I can be 100% guaranteed that the only times when any other task may interfere with my functions execution are explicitly marked with `await`. I love this!
You only need to think about it because runtime isn't parallel. If you want ordering in execution you should be using synchronization primitives anyway.
In Go doing "async" via channels could possibly start running the code the instant you instantiate it, on however cores there are available. Go have problem of that requiring a bunch of boilerplate (as there is no macros), but with generics now it is manageable and I can just say "here is function, run it on all elements of the slice in parallel" very easily and it all be pretty reasonabe, like "out = ParallelMapSlice(mapFunc,8,in)".
All done async without thinking about async.
Devil's advocate: can you give an example of something complicated you ran into that wasn't "simply" solved by Arc<Mutex<T>>?
If you have code that needs to wait on IO (regardless of how fast or slow it could be, the point is that it's not predictable), and want to call it from an async function, why not make that code an async function too?
If it's library code, than yeah I agree it can suck. I tend to wrap those in my own API instead of inline spawning. At least it localises the uglyness, and that approach tends to compose well for me in practice. It does require a bit more code though, but my business logic code and plumbing code end up being separated and as a result easie to maintain too.
> Oh, now everything has to be static.
I will grant you that the static lifetime is a bit confusing until it clicks, but the issue is often that people have a wrong intuition about what a static lifetime bound means because it's introduced a bit clumsily and glossed over in the book.
I agree that async blocks feel a bit "smelly" syntax wise (for lack of better word).
I feel like some of these are just async woes that aren't trivial to solve, but I'd be surprised if the language teams weren't aware of this already and working towards solutions for these things. Async is very much MVP-ish in Rust anyway
c.f. Swift’s async/await impl. Swift solved a lot of these woes because it ships a stdlib and runtime that supports async code.