296 points · by nequo · 3y ago · 198 comments
This is a reality that our operating systems have chosen for us. It's bad. The way Unix does filesystem stuff is both too high level for great performance, and too low level for developer convenience and to make correct programs easy.
What would it look like to go higher level? For example:
- Operating systems could support START TRANSACTION on filesystem operations, allowing multiple operations to be performed atomically and with isolation. No more having to reason carefully about which posix file operations are atomic, no more having to worry about temp file TOCTOU etc.
- fopen(..., 'r') could, by default, operate on a COW snapshot of a file rather than on the raw file on the filesystems. No more having to worry about races with other processes.
- Temp files, like database temp tables, could by default only be visible to the current process (and optionally its children) or even the current thread. No more having to worry about temp file races and related issues.
That sort of thing. Maybe implemented like DBOS: https://dbos-project.github.io/. Or, you know, just get rid of the whole idea of processes for server-side applications. Was that really a good idea to begin with?
> However, if the locks you use are not re-entrant (and Rust's locks are not), having a single lock is enough to cause a deadlock.
I'm a fan of Java's synchronized, and sometimes wish that Rust had something higher-level object-level synchronization primitive that was safer than messing with raw mutexes (which never seems to end well).
Windows supports that since Windows Vista [1], and at least back then it was used by Windows Update and System Restore [2]. But programming languages usually only expose the lowest common denominator of file system operations in easy APIs, so approximately nobody uses it. Also, it's deprecated by now.
But maybe someone here has deeper insights in what went right and wrong with that implementation, because on the surface it looks like it would erradicate entire classes of security bugs if used correctly.
1: https://learn.microsoft.com/en-us/windows/win32/fileio/about...
2: https://web.archive.org/web/20080830093028/http://msdn.micro...
So, I think, this feature, just like WinFS, and probably ReFS after it, will just end up being cancelled / forgotten. The kind of users who use Windows aren't sophisticated enough to want advanced features from their storage, but support and development of this stuff is costly and demanding in other ways. If they cannot sell this as a separate product that runs independently of Windows, there's no real future for it. The only real future for Windows seems to be Hyper-V, but hypervisors, generally, have very different requirements to their storage than desktops. Simpler in some ways, but more demanding in other ways.
So, bottom line: it probably didn't see any use because the audience wasn't sophisticated enough to want that, and they couldn't sell it to the audience that was sophisticated enough, but was also smart enough not to buy from Microsoft.
This is why programming languages don’t rush to support hyped new platform features without some combination of wide support and/or a very compelling use case in their core design or standard libraries.
Aaaand there it is.
Such paradigms need years, at least a decade, to percolate into the general programming culture. Microsoft (and I daresay companies in general) just doesn't have the stability to shepherd such changes.
The same thing is happening pretty much everywhere in computer engineering. Our network protocols provide higher level abstractions (encryption, RPC calls, CRUD, …). Higher level graphics rendering libraries proliferate. Programming languages provide additional layers and safety guarantees.
> What would it look like to go higher level?
File systems aren't "bad" and don't need to be changed or replaced — we just need to use the higher abstractions that already exist much more. Use a proper database when it's appropriate. Or some structured object storage system, maybe integrated into your programming language.
Ultimately, accessing the file system should more and more become akin to opening a raw block device, a TCP socket without an SSL layer, or drawing individual pixels. Which is to say: there are absolutely good reasons to do so, but it shouldn't be your default. And it should raise a flag in reviews to check if it was the appropriate layer to pick to solve the problem at hand.
(added to clarify:)
This all is just to say: it's more helpful to proliferate existing layers above the file system, than to try to change or extend the semantics of the existing FS layer. Leave it alone and put it in the "low-level tools" drawer, and put other tools on your bench for quick reach.
The complaint is specifically about UNIX filesystem. And yeah, it's bad. It needs to be replaced, not wrapped in another layer of duct tape.
The examples of layers you described come not from any kind of sound design that evolved to be better. It was bad, design without foresight and much design at all. Historically, it won because it was first to be ready, and the audience was impatient. And it stayed due to network effect.
The consistency guarantees, the ownership model, the structure of the UNIX filesystem objects are conceptually bad. Whatever you build on top of that will be a bad solution because your foundation will be bad. The reason these things aren't replaced is tradition and backwards compatibility. People in filesystem business knew for decades that the conceptual model of what they are doing isn't good, but the fundamental change required to do better is just too big and too incompatible with the application layer to ever make the change happen.
Yes! But it's easier said than done when one of these things is in the stdlib and the other isn't.
Oh it's much worse than that. One of these things is what the user sitting in front of their computer has a nice integrated UI to view and search… if a photo editing applications starts storing my photos in a database that I can't easily and simply copy some photo out of, I'll be rather annoyed. And each application having their own UI to do this isn't the solution either, really.
[EDIT: there was some stuff here about shell extensions & co. It was completely besides the point. The problem is that the file system has become and unquestionably is the common level of interchange for a lot of things.] …didn't Plan 9 have a very interesting persistence concept that did away with the entire notion of "saving" something — very similar to editing a document in a web app nowadays, except locally?
Either way I don't know jack shit about where this is going or should go. I'm a networking person, all I can tell you for sure is to use a good RPC or data distribution library instead of opening a TCP socket ;).
It "works" only because 99.99% of all programs don't try to poke into other files and directories where their fingers don't belong. That's the only reason things are not in a complete chaos.
We need DB-like features in FS-es not just yesterday, but 10 years ago.
Some of the most successful projects I've seen and participated in were making a heavy usage of SQLite which does solve the FS deficiencies quite well. Though it does require a buy-in that's rarely there for most teams.
We don't need more abstractions on top of stuff. We need new ways of interacting with the old existing stuff while hiding the existing stuff forever.
Databases like Postgres implement such a transaction not through a lock, but by keeping multiple versions of the data/file until the transactions using them closed.
Yet other databases operate on the stream of changes and the current state of data is merely the application of all changes until a certain time, allowing multiple transactions to use different snapshots without blocking each other (you can parse a file while somebody else edits it and you won’t be interrupted).
I read about various filesystems offering some of these features, but not in IO APIs.
> Yet other databases operate on the stream of changes and the current state of data is merely the application of all changes until a certain time, allowing multiple transactions to use different snapshots without blocking each other (you can parse a file while somebody else edits it and you won’t be interrupted).
Databases have features in-place to merge those parallel strings of changes and at worst, abort transaction. Apps using that handle that.
Now try to explain to user why their data evaporated coz they had it open in 2 apps...
Nah. The file system is a slightly improved block storage management tool that isolates your database implementation from dealing directly with mass storage devices.
Thinking that the filesystem is viable as a database when it isn't — that's exactly the problem here :D
A totally shit database designed before we knew anything about databases. Well past time to retire them.
However, I don't know what's the recommended way to handle concurrent writes with SQlite. In the end we have a single process handling all the persistence logic, which becomes essentially a server just like Postgres?
I'm not a Java expert. But from looking it up it seems like Java's synchronized is worse in every way to Rusts Mutex(And you most of the time shouldn't even be using mutexes in Rust). You forget a synchronized annotation? Too bad. Whereas a mutex in Rust protects the access to a variable. You literally can't modify it (well modulo unsafe) unless you lock the mutex.
Mutexes and locks are also a really tricky API, but making them re-entrant has performance and functionality costs - you basically need to store the TID/PID of the thread that holds the lock inside the lock.
I'm sure there's a crate for a mutex-wrapped datatype, trading speed for ease of use, but if not, it's likely a very easy crate to put together.
On Linux, there are some new APIs you see crop up every once in a while. For apps running in the data center, you can use network storage with whatever API you want, instead of just using files. And on the Mac, there have been a couple shifts in filesystem semantics over the years, with some of the functionality provided in higher-level userspace libraries.
Solving the problems for databases seems really hard, just based on all the complicated stuff you see inside SQLite or PostgreSQL, and the scary comments you occasionally come across in those codebases. But a lot of what we use files for is just “here is the new data for this file, please replace the file with the new data”, and that problem is a lot more tractable. Another use case is “please append this data to the log file”. Solving the use cases one-by-one with different approaches seems like a good way forward here.
> - fopen(..., 'r') could, by default, operate on a COW snapshot of a file rather than on the raw file on the filesystems. No more having to worry about races with other processes.
You can go a few steps further. If you have some sort of O_ATOMIC mode on creating a file descriptor, that operates on a separate snapshot in both read and write mode (and in the case of open for write, will atomically replace the existing file with the newly written copy on close), that would have more correct semantics than existing POSIX I/O for most applications. You can't make it default at the syscall level, but most language I/O abstractions could probably make it default. Notably, this can be implemented in the OS kernel without actually touching filesystem implementations themselves, just the way the kernel arbitrates between userspace and the filesystem.
Another interesting file mode that fixes many use cases is having some sort of "atomic append" for files that handles the use case of simultaneous readers and writers of log files. Set up the API so that you can guarantee that multiple writers each get to add their own atomic log message (without other synchronization), and that readers can never see just part of a log message.
The difficult part of the filesystem to reason about is the file metadata and directory listings. I've seen suggestions in the past to use file descriptors instead of strings as the basis for handling directory queries in language implementations. If you don't do at least that much, it's basically impossible to solve TOCTOU issues, but I'm not sure there's a lot you can do with COW snapshotting of directories that still manage to be acceptable in performance.
> Temp files, like database temp tables, could by default only be visible to the current process (and optionally its children) or even the current thread. No more having to worry about temp file races and related issues.
Creating unnamed temporary files is a solved problem. Named temporary files is more difficult, but create-only-if-doesn't-exist exists on all platforms, and most language APIs have some way of getting to that (it's "x" flag in C11's fopen).
My understanding is that O_APPEND gives exactly this guarantee. Readers can read partial records, but with proper record marking it shouldn't be an issue.
I don't know what size record is guaranteed to be writable that way, if any, but I wouldn't assume it's infinity. Short writes aren't illegal. Perhaps you were pointing at this, but then you need to work around the limitations of the OS, and...
Why can't we just have transactions?
> Operating systems could support START TRANSACTION on filesystem operations, allowing multiple operations to be performed atomically and with isolation. No more having to reason carefully about which posix file operations are atomic, no more having to worry about temp file TOCTOU etc.
And your performance goes absolutely to trash once you start trying to make filesystem act as transactional database. Especially if you then try to use the filesystem for a database.
> fopen(..., 'r') could, by default, operate on a COW snapshot of a file rather than on the raw file on the filesystems. No more having to worry about races with other processes.
Another "performance goes to trash" option. Sure, now more palatable with NVMes getting everywhere, but still a massive footgun
> Temp files, like database temp tables, could by default only be visible to the current process (and optionally its children) or even the current thread. No more having to worry about temp file races and related issues.
Already an option O_TMPFILE
> O_TMPFILE (since Linux 3.11) > Create an unnamed temporary regular file. The pathname argument specifies a directory; an unnamed inode will be created >in that directory's filesystem. Anything written to the resulting > file will be lost when the last file descriptor is closed, unless the file is given a name. ... > Specifying O_EXCL in conjunction with O_TMPFILE prevents a temporary file from being linked into the filesystem in the >above manner. (Note that the meaning of O_EXCL in this case is differ- > ent from the meaning of O_EXCL otherwise.)
I'm not the author of the above proposal, but I'd imagine the implementation to be more in the same spirit as uring_io or EBPF: batch many operations together and execute them all at once, without interruption, without crossing multiple times between user-space and kernel-space, without resorting to implement the same guarantees on the side of the application which, inevitably, are going to be less efficient than those provided by the platform.
You fall into the same trap as many others who benchmark individual tiny features w/o seeing the larger picture where these features combined to accomplish the end goals. Applications want sane correctness guarantees, and if they try to accomplish those goals using existing tools they will have to use multiple features. Perhaps, individually, those features perform well, but in a useful (from the application standpoint) combination, they don't. And that combination is the one you need to benchmark.
My much more modest feature request from the kernel is a write barrier. If I’m using double-buffered pages or a write-ahead log, right now my code says write(); fsync(); write(); in order to ensure the log is written before updating the data itself. I don’t need the operating system to flush everything immediately - I just need to ensure the first write happens entirely before the second write begins. Like, I need to ensure order. A write barrier command is all I need here.
The posix filesystem apis are a sloppy mess. I have no doubt that the right apis would make my life better and improve the performance of my software.
> Another "performance goes to trash" option. Sure, now more palatable with NVMes getting everywhere, but still a massive footgun
Only because the filesystems aren't built that way. ZFS could handle this just fine.
The fact that adding SQLite into your application is often faster performance than doing raw disk accesses yourself says that our abstractions are wrong.
This is not portable.
(Of course, as we see time and again, the real portability solution is for users to standardise on a single platform)
This is one area where the Unix design is much closer to good compared to other historic approaches. The separation of file identity from file paths (not sure if it is a a Unix invention) pretty much allows temp files to be implemented, in fact I believe O_TMPFILE in Linux allows that.
> START_TRANSACTION
can be implemented on top. Transactions are quite involved, so I wouldn't blame a random file system for not implementing them. Use a database (yes, most of them skip the buffering and synchronisation layer of the filesystem they are stored on, and use e.g. O_DIRECT).
> fopen(..., 'r') could, by default, operate on a COW snapshot
Something like that would require the definition of safe states in the first place (getting an immutable view is pointless if the current contents aren't valid), so we're almost back at transactions.
I think Unix file systems are fine and usable as a common denominator to store blobs, like object stores do, but also easily allow single writers to modify and update them. As ugly and flawed and bugged as most file systems are, most of the value comes from the uniform interface. You need better guarantees than that, you probably have to lose that interface and move to a database.
Recursive locks are a nightmare. You cannot reason about lock acquisition order and have to invent new ways to make it safe.
Indeed. Imagine if on program start, each process gets its own sqlite database rather than a file system. So many issues would be solved. A user shell is then just another sqlite database that indexes process databases so you can inspect them using a standard interface.
There are two big problems with Java's synchronized that I can think of. It adds a monitor and therefore memory overhead to every single object. And it publically exposes the monitor allowing potentially bugs due to unintended use by clients.
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.
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.
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.
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?)
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.
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.
(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?
> 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
fn f<T: Into<MyType>>(t: T) -> MyType { t.into() }
Picturing a group of nuclear-winter survivors trying to restart a coal plant. Found the control room. Inside, a working diesel generator, a computer and a Rust manual. fn f<T: Into<MyType>>(t: T) -> MyType { t.into() }
We've got an introducer keyword 'fn'. We're defining a fn function named f. Cool, in C++ I might have gotten a long way before I found out what the function's name was. Hopefully this is an example name, obviously don't really just name your functions "f"<T: Into<MyType>> means there's a type parameter here, our f function can work with different types, T, however, it also constrains the type parameter by saying it must implement a Trait, named Into<MyType>. In Rust we're allowed to also write these type constraints separately, and if they're complicated it's bad style to put them here, but this constraint was very simple.
(t: T) means the f function takes a single parameter, named t (again, please give things better names in real life people) of type T, that T is the one we just met, it's some type which implements Into<MyType>
-> MyType means the function returns a value of MyType.
{ t.into() } is the entire function definition.
This function just calls the method into() on the parameter t. How does it know it can call into() ? If you're a C++ programmer you might assume it's just duck typed, C++ just does text replacement here which is how you get those horrible multi-page scrolling template errors, but nope, in Rust it knew because the thing we know about t is that its type is T, and the only thing we know about T is that it implements Into<MyType> which is a trait with exactly this into() method defined, where the return type of that into() method will be MyType. We actually didn't know how to do almost anything else with t except call into()
I do wonder if someone could design a language with a little more built in logic that would be able to know that an Arc won’t be moved, or that can understand String can be matched to a str, if that could function as the often requested “higher level Rust”
That's called "deref patterns" and it's been made to work on nightly only for String for now, but 1) the implementation is currently a huge hack, 2) development stalled over the holidays but there's multiple interested parties to see this implemented and stabilized and 3) the idea is to make these "just work" (without any extra sigils or keywords) for specific Deref impls, maybe with a new marker trait DerefPure, which might or might not be available for end users to (similar to trait Try). DerefMut is IIRC still an open question.
- The "functional abstraction" issues could some day be adressed with view types: https://smallcultfollowing.com/babysteps//blog/2021/11/05/vi...
- "Newtype abstraction" can be made nicer with third-party crates, or maybe in the future with project safe transmute
- "Views and bundles" I run into this one all the time, it's annoying
- "Deref patterns" could allow pattern matching to see through boxes one day, but there are unresolved design issues
There is! `std::pin`[0] does just this (and `Arc<T>` even implements `Unpin`, so the overall struct can be `Unpin` if everything else is `Unpin`). The page even includes a self-referential struct example, though it does use `unsafe`.
RFC text: https://github.com/jswrenn/rfcs/blob/safer-transmute/text/00...
I don't know what the status quo is, but it is very exciting work.
There are also crates in this domain that work today. The two I'm aware of are https://docs.rs/zerocopy/latest/zerocopy/ and https://docs.rs/bytemuck/latest/bytemuck/
"Beyond Locks: Software Transactional Memory" by Bartosz Milewski
https://bartoszmilewski.com/2010/09/11/beyond-locks-software...
I wonder how far it can be implemented in Rust? There are people trying:
https://github.com/aakoshh/async-stm-rs (updated just days ago)
I really like how the author used green/red backgrounds to show code that doesn't compile.
> Common expression elimination
I feel as though there should be a warning when a parameter that could be a reference is not. I usually run into this when a function that I've written is incorrectly taking ownership of a parameter.
> Newtype abstraction
The Rust compiler could implicitly call `into` and `inner` (and then possibly optimize those away), but this (explicit or implicit) is required for linear types. What could work is: `Hex(&bytes)`.
https://www.reddit.com/r/rust/comments/kbyb6z/what_is_the_pu...
Also, the "reference" issue described in the article later is painful, but can be solved w/the Yoke or Rental crates right now. I hope those make it into the stdlib, however.
What do you mean by "treat it in the same way" ?
#[repr(transparent)] does promise you something with identical layout and alignment. If whatever is in there is actually the same kind of thing then the transmute will work, but the problem is - what if it's not?
Take nook::BalancedI8 and std::num::NonZeroI8 these both have the same representation as Rust's i8 built-in type, they're one byte signed integers. But, wait a minute Option<BalancedI8> and Option<NonZeroI8> also have the same representation.
Now, if that single byte is the value 9, we're fine, all five of these types agree that's just 9, no problem. Same for -106 or 35 or most other values.
But, for 0 it's a problem. i8, BalancedI8 and Option<BalancedI8> all agree that's zero. However NonZeroI8 can't conceive of this value, we've induced Undefined Behaviour, and Option<NonZeroI8> says this is None.
Similarly at -128, i8, NonZeroI8 and Option<NonZeroI8> all agree that's -128, their minimum possible value. However the minimum value of BalancedI8 is -127 so this representation is Undefined Behaviour, and in Option<BalanacedI8> that's None.
Those languages let you just do the frickin' work TM.
self.counter.inc();
Where `self.counter` is a new struct that holds `x`. Because `counter` is its own struct field, I can call mutable methods on it while holding mutable references to other fields.What I've found is that often the current "object" naturally decomposes into different parts each of which can have their own methods that only need to work with their particular subset of the fields.
But to be honest that's bad code.
Are you afraid of grep asdf 1.txt | gzip ? Probably not, you probably don’t even noticed this is a parallel execution.
pub fn main() {
println!("Hello, world!");
}
If you're hitting the borrow checker and you haven't found yourself at that point because a profiler or benchmark suggested it, you might just be trying to access too much of Rust's power for what you need.You can always just throw everything inside of Rc<RefCell<...>> if you're using a single thread, or Arc<Mutex<...>>/Arc<RwLock<...>> if you're doing multi-threading. It looks expensive, but what you end up with is approx. the same accounting you find in higher-level languages, but the same guarantees.
It’s like, if you can use Arc than you can use garbage collection, in which case why battle the borrow checker and just use Elixir or something which better guarantees and an easier time.
let x = compute_x();
f(x.clone());
g(x);
was confusing/surprising to me. Isn't the whole point of default-immutable that you can use x without owning a copy? Forgive me if this is a stupid question. let x = compute_x();
f(&x);
g(&x);
Otherwise you have moves there. Now it depends on the API, it may want the value and not the reference (a borrow).For a non-trivial object (which apparently x is), you would always prefer to write &x (immutable reference to x) or at least &mut x (mutable reference, not applicable here because x is not defined as a mutable thing).
So apparently these functions intend to consume x. That's not common but there are a reasonable number of Rust APIs which consume larger things on purpose.
1. Suppose x is a Teapot, some complicated object with lots of internal state - it has about two cups of Early Grey in it, and is a lovely blue and white pattern.
If we call f(x) then we're giving our Teapot, x, to this f() function. It apparently doesn't give anything back, so the Teapot is gone now! In Rust we say x was moved into f.
Maybe f empties the tea out of the teapot, then smashes it and uses the broken pieces to fill a pothole in the road. Weird.
So we use the clone() call to ask for an exact duplicate of the Teapot, now f(x.clone()) only gives the clone to this function f, our original Teapot remains unaltered in our possession.
Because we've still got x, we can call g() which apparently like f also wants the actual Teapot, maybe this function plants a cactus in it and puts it on a high shelf. Once again our Teapot, x, is gone because we gave it to g().
Now, most Rust functions on complicated objects like a Teapot (or more realistically, a Vec or a String or File) don't move parameters like this, they want either a mutable reference which you'd write &mut x or an immutable reference, which is written &x. If these functions f() and g() only needed immutable references, our Teapot x is fine. We can't use mutable references because x itself is not labelled as mutable, if it was, the Teapot might be altered, but it's still a Teapot, the functions don't own it, they were just given a reference and so they aren't allowed to destroy it for example.
OK 2. Suppose x is just a 32-bit unsigned integer, u32 in Rust
Now things are different, because the u32 type implements Copy, a trait which tells the Rust compiler, "My value is literally the value of the bytes in RAM, if you copy those bytes, that's all I am, that's a copy of me".
So now even though f(x) moves x into f, the compiler knows x is just this 4 byte value, it can give f the same 4 byte value and keep the one in x, and everybody is happy. f() can do whatever it wants with that value, x is unaffected. We can call x.clone() if we want, but it just makes another identical 4 byte value, kinda pointless.
Then g(x) does the same, even if it wants to "move" the parameter, the compiler just gives it a copy anyway, no harm done.
Does this help?
- https://github.com/withoutboats/shifgrethor
But they don't look particularly usable.
Beyond that, yeah, it sucks.
Files are garbage collected. There is no use after free if someone deletes your file because the OS sees that you are still using it
- on Windows, another process deleting the file is prevented (unless you explicitly opted-in to cooperative FILE_SHARE_DELETE); and
- on Linux, another process deleting the file only unlinks its name, and your handle continues working with the nameless file and its content