An OS with no threads: The Actor Model (timdbg.com)
290 points by ingve 16 hours ago
zoom6628 13 hours ago
OLd(er) person here. If you want look at earliest Actor models then look at COBOL programs from 70s that used queues (it's part of COBOL standard).
Programs would read from specific queues for input data, transform that data and then write some to data stores and some to downstream queues. This created DAG environments for data and transaction flow.
Scaling in these environments was done by monitoring load and back pressure in the queues and firing multiple readers. Transaction Processing Monitors like VRX and CICS managed this at OS level and the COBOL programs managed at unit level.
COncurrency was running multiple units reading from same queue to do same function.
this is one reason why a ton of these older systems still running.
DAG workflow, automatic balancing, queue based actor models with transactions.
Seems like what is old is new again.
dapperdrake 9 hours ago
Thank you.
This is the kind of knowledge and wisdom I come to HN for. Seriously.
The systems from the 60s and 70s and 80s were designed by brilliant people.
What is old is new again.
christophilus 11 hours ago
COBOL systems and the related hardware was excellent. I remember our company running Unisys mainframes way back in the days, and they were absolute beasts. I think we need a modern equivalent. COBOL was truly an unpleasant language (to me) and yet pretty elegant in many ways.
antonvs 11 hours ago
COBOL did not implement the actor model. There are several devils in the details here which distinguish the actor model from the similarities to COBOL systems.
One of the biggest differences is that in actor systems, there's no intermediate queue-like channel that messages are sent to. Messages are sent directly between actors, peer-to-peer. Each actor manages its own private message queue. Similarly, each actor has logically isolated state, so actors can't affect each other except by sending messages.
To achieve the kind of queue-based concurrency you mentioned, the idiomatic actor pattern is to spawn a new actor per request. In the Erlang BEAM VM for example, an actor (Erlang calls them processes) typically spawns within a few hundred nanoseconds.
If you want a shared queue, you can implement an actor to serve that purpose, and there are standard implementations of this. This is kind of the opposite of what COBOL does. The actor and its peer to peer communication are the primitives, and things like shared queues are implemented at the application level. This alone means COBOL does not follow the actor model.
Another big difference is how OS process and thread management are used. No COBOL system ever implemented what Erlang does, which is a single, reliable OS process that manages multiple strongly isolated actors with preemptive scheduling.
CICS came the closest in its early versions, running multiple tasks/units in a single address space on a single thread. But it used cooperative multitasking, not preemptive, and isolation between tasks was fragile - it was quite common for unhandled exceptions or memory overwrites to bring down the the entire CICS address space, terminating all active users. The logical isolation of actors solves for the latter issue. In Erlang, each actor has its own garbage-collected memory pool, and actors can crash without affecting the rest of the system.
The way that was solved in the COBOL world was to move to relying on OS-level concurrency. Tandem NonStop, designed for high availability, was a good example of this. In fact, Erlang inventor Joe Armstrong was influenced by it, but he took advantage of the actor model to implement a much more reliable version of what early CICS systems had - a single OS process running multiple tasks, but with preemptive scheduling and strong task isolation.
You don't have to squint too hard to see resemblances between COBOL and the actor model, but key features of actors, including peer-to-peer task messaging and either (1) strong task isolation or (2) no dependence on OS-level concurrency mechanisms like processes or threads, were never implemented in COBOL systems (afaik).
Actor model systems like Erlang allow for the possibility of running without an OS, because they already handle their own process scheduling, memory isolation, and IPC, so all that's left is drivers, networking, and a bootloader.
Several projects have done this, and the OP article is describing a non-Erlang system in that vein.
Examples of Erlang/BEAM as OS include LING (runs directly on the Xen hypervisor), GRiSP (runs on bare metal embedded systems), AtomVM (for microcontrollers with only kilobytes of RAM), and Nerves (runs on a bare minimum Linux kernel with BEAM as PID 1, to take advantage of hardware drivers.)
adrian_b 11 hours ago
> Messages are sent directly between actors
Such a thing cannot exist whenever more than 1 actor can be executed simultaneously.
An actor may have a single input queue, and all other actors can send messages to that unique input queue.
In this case, because there is a 1-to-1 mapping between input queues and actors you could identify the input queues with the actors.
But inside the code implementing the actor, you must have a loop that extracts messages from the input queue, so you must be aware that the input queue exists and it is not the same thing as the actor.
If you had a bad actor implementation without a unique input queue, than you would need something like a separate mailbox for every other actor, where the other actors would deposit messages and each actor would have to poll continuously all such mailboxes, to catch the arrival of any messages, which would be very inefficient.
"Spawning a new actor per request" just means that the implementation of the actor is split into 2 parts, the loop that extracts messages from its input queue and a function that is invoked upon the arrival of a new message, having the message as argument.
Such a splitting makes sense, because the loop handling the input queue could be the same for all actors (but acting on different input queues), with only the function that is invoked for a message containing the part that is different for each actor.
spinningslate 10 hours ago
eproxus 11 hours ago
antonvs 11 hours ago
speed_spread 11 hours ago
Message queues never went away but were certainly set aside during the personal computer revolution. One thing that changed is that users now expect timely if not immediate results; Actor models like Erlang's bring a notion of realtime constraints that AFAIK didn't exist in previous batch processing architectures.
DonHopkins 12 hours ago
So Factorio.
torginus 10 hours ago
I am a bit skeptical of the non-blocking claims, as actor systems usually make several tradeoffs, that handle the classical 'blocking' issue differently (by which I mean I read a 100MB file synchronously on the UI thread, and the program appears to freeze).
Classical actor systems at their simplest only support sending one-way messages, and these are indeed non-blocking.
But they are not very powerful either. People usually introduce the 'remote procedure call' on top of this, by which actor A can call actor B and expect B to respond. You can do this with corellation IDs for example.
The question is what does actor A do while waiting for 'B'? In the simplest form it continues to serve other messages, making the actor reentrant, which can create incredibly surprising scenarios as code executes while you don't expect to changing actor fields in unexpected ways.
Or you can have actor A wait to finish processing the call to 'B'. But now you have blocking, as 'B' can prevent anyone talking to 'A' from making progress.
Or you can do something computer-sciencey, like doing transactions and specifying the conditions under which A can server multiple ongoing requests, and how to reconcile them.
I'm sure there are many options, but actors have been a cool idea for a while, and many event driven paradigms borrow from it, that are incredibly widespread to the point that I'm sure most people have programmed in a system before, and have experienced 'callback hell'.
So they are not a panacea.
gwbas1c 8 hours ago
You are right. I inherited an early version of a product built in the Actor model, and we quickly had to go to a hybrid approach doing some of the things you describe.
Specifically, we introduced a single actor that manipulated shared state and was responsible for some critical IO. Other actors could see the shared state in a non-blocking manner, so there ended up being a lot of "refresh my shared state" or "abort if the shared state changed".
My longer-term conclusion was that the actor model wasn't correct for the product, because it obscured the procedural nature of what happened in each operation. It should have been multithreaded (or green threads) with each operation spawning a thread; and then classical read/write locks (with timeouts) on shared state. In some cases where batching happened (for some API calls), some kind of message passing would be needed, but the parent thread would need to block on the thing that does the batch.
timmisiak 8 hours ago
It's non-blocking through the use of stackless futures. The ReplyTo gives you enough to get back to your future, so you can restore your state and continue execution. It might feel like splitting hairs, but it lets you get rid of threads. As for "callback hell", you only get the async/await pattern inside stateless tasks that can send a message back to the parent actor when the task is complete. Then the parent actor can update its own internal state "atomically" with no interruptions.
Is it a panacea? No, certainly not. But I do think it provided some interesting capabilities and tradeoffs that are useful to think about.
dapperdrake 9 hours ago
Fire and forget versus fork and join.
Fire and forget is mostly useless. One of the many counter-examples is the existence of TCP and QUIC. Raw UDP has legitimate use-cases, but falls short for many other real-world use-cases.
01HNNWZ0MV43FF 10 hours ago
> In the simplest form it continues to serve other messages, making the actor reentrant, which can create incredibly surprising scenarios as code executes while you don't expect to changing actor fields in unexpected ways.
That's probably why GUI programming is so hard and every GUI sucks.
Anything that happens outside RAM requires you to respond to every possible input in the middle of any possible operation
torginus 9 hours ago
I'm not sure if actors are still a popular paradigm in UI programming, which I think it's where most people who used it had a chance to encounter it. Win32 certainly used to use it as did traditional Qt, but modern systems have moved to more of a MVC approach.
cowlevel 6 hours ago
Oldschool UIs would often just unapologetically freeze or make a ding sound if you did things out of order.
In Win32, when you show a message box, that MessageBox or DialogBox function doesn't return until the dialog box closes. Inside the function is a separate event loop (or message pump, by the Win32 name) and whenever it gets a user input event unrelated to the dialog, it plays a ding noise, flashes the dialog box, and ignores it. The whole time it's on-screen, the program is sitting there with a bunch of stuff on its stack, probably blocking in the middle of an event handler. And yet nobody found this unintuitive to use or to program!
(This is obvious to anyone who's programmed Win32 but I figure a lot of HN readers have only done web)
dapperdrake 9 hours ago
Re-entrancy
Thread-safety
What is old os new again.
Unix also learned this the hard way with signals and job control. Signals are still footguns.
Permik 2 hours ago
torginus 8 hours ago
notpublic 11 hours ago
May I recommend the following 2 talks on this subject:
https://www.youtube.com/watch?v=37wFVVVZlVU Panel Discussion with Sir Tony Hoare, Joe Armstrong, and Carl Hewitt
https://www.youtube.com/watch?v=7erJ1DV_Tlo Hewitt, Meijer and Szyperski: The Actor Model (everything you wanted to know...)
The first one is a rare gem: a conversation among the creators of the foundational concurrency models. Carl Hewitt (Actor Model), Tony Hoare (CSP, Communicating Sequential Processes, which inspired Go's goroutines and channels), and Joe Armstrong (co-creator Erlang).
f13f1f1f1 7 hours ago
That panel discussion is probably my favorite programming video I've found. Just amazing to see the three come together and see the different attitudes they take and how that's reflected in the different traditions.
tancop 14 hours ago
You can extend this with "linear type" message passing where you transfer ownership of an object. That avoids physically copying memory and the sender loses write access to enforce the one writer at a time constraint.
It means a pipeline of actors can process a file with the same memory usage and only a tiny bit more CPU than a monolithic program, but it stays isolated and hot swappable.
This might already be implemented in the OS but the post doesn't mention it.
timmisiak 7 hours ago
I should have mentioned that ownership of messages is transferred. That seems to have caused confusion. It's one of the nice things that easily came out of enforcing all rust everywhere.
dugmartin 12 hours ago
The BEAM on Erlang sort of does this with its global binary heap so you can have multiple readers. The binary must be larger than 64 bytes so it's stored on the global binary heap instead of copied onto process heaps. Its not really linear type though as there is no transfer since all data is immutable.
ch4s3 12 hours ago
Implementing linear messages at the OS level is a cool idea. I’ve loved building linear types in my language, they’re super nice to work with and give you some good tooling and compiler options. I’ll bet an OS could do a lot with the idea.
NooneAtAll5 6 hours ago
I still don't understand why it's called "linear" when it's obviously one-time-use
mrkeen 6 hours ago
"it is called linear logic because it involves semantics which resemble structures from linear algebra."
https://math.stackexchange.com/questions/2339147/why-is-it-c...
torginus 13 hours ago
The headline advertises 'no threads', but in the article, it mentions all actor methods are non-blocking, and async. Not blocking what?
The whole purpose of async is to have a message pump thread, and allow concurrency by yielding the timeslice. It's also needed because many async runtimes interact with APIs that need to be called from a single main OS thread.
I would presume an OS designed to be all actors, all the way down would do away with the need for a message pump thread, and single threaded APIs. In this case, cross-actor calls might as well be sync, with required preemption handled on the OS level.
Having to pay the async overhead over 100% of cross-actor calls is very expensive.
Asmod4n 12 hours ago
There are two schools of thought for this.
One is the poll model, you ask the OS when you can use something.
The other one is the completion model, where you ask the OS to do something on your behalf and ask it when it’s done.
In the former you are the mailbox yourself, in the latter the OS is the mailbox.
When you are the mailbox yourself threads are kind of needed. When the OS is the mailbox it can implement them however it wants to.
I’d guess this OS is doing Mailbox duty itself instead of letting userspace handle it.
adrian_b 12 hours ago
There is an extra step after "you ask the OS to do something on your behalf and ask it when it’s done".
That is "you ask the OS to do something on your behalf and you do not have to check when it is done", because you have a unique queue where you receive notifications about everything that is of interest for you, including the completions of I/O activities that you have requested previously.
"You ask the OS to do something on your behalf and ask it when it’s done" was an ancient method to perform asynchronous I/O, which survived in many operating systems much more years than it should. Continuing to use such a method today is a mistake.
The best method for asynchronous I/O is with a unique input queue, like in the Linux io_uring. The second best method, because it can be used to implement a unique input queue, is with what in DEC RSX-11M was called "Asynchronous System Trap Service Routine", i.e. a callback function to be invoked upon I/O completion, which was inherited from DEC RSX-11M into DEC VMS, from where it was inherited into Microsoft Windows NT, and then in 1994 MS Windows NT 3.5 introduced the "I/O Completion Ports", which was AFAIK the first improvement in asynchronous I/O handling after what DEC RSX-11M did 20 years earlier, in 1974 (which was again the first improvement over what IBM PL/I already had in 1964, when it had the equivalent of WaitForMultipleEvents, but in a more powerful variant than in Windows NT).
Asmod4n 10 hours ago
zelphirkalt 12 hours ago
> The headline advertises 'no threads', but in the article, it mentions all actor methods are non-blocking, and async. Not blocking what?
I think the very brief answer to that is: "Processes." as in the general concept of communicating processes. How those are actually implemented on another layer depends on the platform. You can also run an actor system on a machine, that can only do one thing at a time, using a single CPU core. The work the process does is not blocking, but the platform might not have the capability to do more than one thing at a time. But this is different from work being inherently sequential.
timmisiak 8 hours ago
Actor methods aren't async. You can create async tasks, but there's no message pump thread. Every "await" results in a suspension via a future that gets carried as data, essentially tied to a response message. Reasoning about async from a threaded perspective won't make sense, because there are no threads. Async here just gives you a nice state machine, not a message pump.
inkyoto 12 hours ago
«Threads» imply «shared state» within the confines of the same process, hence the need for locking primitives, mutexes, and alike.
«Actors» imply «no shared state» – there is a message inbox and a message outbox, but the state is private to the actor.
Both can be asynchronous.
zbentley 12 hours ago
I think this taxonomy is not good. It’s comparing apples to oranges, or apples to fruit sugars or something.
Threads are not a programming paradigm or style, any more than a CPU is a programming paradigm or style. They’re a tool, an existential piece of the landscape which can be used to perform paradigms/styles. Like CPUs, they do have affinity for certain use cases, but the car is not the road trip.
layer8 11 hours ago
inkyoto 10 hours ago
nmcfarl 11 hours ago
imtringued 12 hours ago
Threads are an OS level concept introduced by a kernel, e.g. the Linux kernel. If you do not have an OS at all, you do not have threads (lets ignore hardware threading for the sake of the argument). You just have the core itself be occupied by the actor scheduler, but no thread scheduler.
Blocking is not a threading or even OS concept. Blocking is a CPU core and programming language concept derived from sequential processing. Blocking means that instructions behind the block are not being executed while the block is in progress.
In the actor model, sending a message must never prevent the execution of instructions that follow after sending the message. The continued execution of further instructions must be guaranteed until the actor has processed the message. Responses must be received through the actor's mailbox.
Since blocking as an absolute concept may not make much sense, because all sequential processes (e.g. execution of an instruction) are blocking temporarily, the author decided instead to define a time bound, so if mail box processing takes too long, simply because the algorithm is CPU intensive, the author considers it blocked as well and schedules the next actor.
Edit: I guess the confusion comes from the fact that Rust's async facility automatically converts the code into a state machine that is compatible with actor execution semantics, but technically violates the spirit of actors.
majke 12 hours ago
I look at it differntly. There is no fundamental difference between async paradigm and threads. The only difference is where the call stack is.
It just happens that in threads, there is this magical place called stack that you can SUPER fast allocate memory for new function frame. If you have a complex program that uses many deep very deep calls to functions withing functions within functions, you dont need to deal with register allocation or even "local stack frame" for local variables allocations. You just zip in and zip out of the "thread" stack all the time, millions times per second.
The disadvantage is that if for whatever reason a deeply nested thing needs to do _something_, typically I/O, then there is no easy way to yield and allow someone else to use ALU. One option is to change stack register to some other stack and continue other stream of compute. This done by OS is called a context switch.
However, for certain problems, there is an alternative - async. In async the "stack" for local variables is more explicit, very often on the heap, and is managed differently. Every time you are calling a nested function it also needs to store the local variables somewhere, so either you emulate stack somehow (in which case this is not much differnet than normal thread) or allocate the nested function local variables space using memory allocator on heap or special memory.
This is great beause it allows you to reduce the cost of a context switch - now you don't need to change the stack pointer and save context, becasue context is by definition saved in the async block. Asnc also allows you to NOT overcommit on stack size for some future deep deep nested fucntion calls that might never happen. In async you know exactly where you can yield and can plan for it.
However it's not like these two models are fundamentally different. It's the same problem of "where the local variables live" and "how to allocate this memory". We have far bigger problem - due to historical reasons "blocking" is a thing, but this is is only because we made mistakes designing operating systems (I'm looking at you fsync, open, close, or even bpf() syscalls).
cowlevel 5 hours ago
zbentley 12 hours ago
gpderetta 5 hours ago
adrian_b 11 hours ago
On ancient single-core single-thread CPUs, threads were indeed a concept introduced by the operating system, and the use of threads was completely optional.
On modern CPUs, which have many hardware threads, the operating system and the user programs must handle at least the number of hardware threads, e.g. 32 threads on an AMD 9950X.
Implementing more threads than the hardware threads is optional, but the hardware threads must have their own states and stacks and if they exchange messages the inter-thread messages must pass through message queues located in shared memory and using algorithms that enable concurrent accesses.
Naive implementations of message queues can use locks for mutual exclusion, but better implementations exploit the fact that message queues, like also arrays, can be dynamically partitioned using atomic fetch-and-add instructions, so that many threads can access concurrently a message queue, without using either mutual exclusion or optimistic accesses (which may need retries).
It is possible to have an operating system where there exists no shared state between threads, with the exception of the shared message queues.
Because message queues can be implemented without the need for mutual exclusion, it is possible to have an operating system where mutual exclusion (i.e. locks) is not used anywhere.
Whether an operating system without shared state between threads can have a performance comparable with e.g. Linux or Windows, is an open problem.
The lack of shared state does not mean that superfluous copies are needed. The messages may contain pointers to buffers in shared memory through which the bulk of the data is transferred between threads, but those buffers always have a current owner, i.e. the receiver of the message, and no other thread attempts to access them, including the sender of the message, which has written the buffer before sending the message.
cowlevel 5 hours ago
cowlevel 5 hours ago
Blocking is a threading concept. It means the thread is immediately descheduled and will not be scheduled until a certain event happens.
MarceColl 14 hours ago
I did build something very similar[1] a few months ago.
For me the core idea was that I wanted two things:
* Simple persistence by default, not bolted on (files, sqlite, postgres). Each actor is an Elm-like init/update/view set of functions and a storage type. That storage type is saved after every update and can be offloaded to disk while the app doesn't receive new messages. So building durable state is very simple (there are some mechanisms for ephemeral state as well).
* Actor based capabilities, an actor has access to other actors that provide capabilities. Because actors can also be created ad-hoc with custom code (the language is a lisp-like language) you can narrow down capabilities as much as you'd like. For example if you have access to make arbitrary HTTP requests, you can create an ad-hoc actor that delegates making HTTP requests only to a certain domain and pass it. A capability is just the address of another actor.
With these two primitives (+ a content-addressable store underneath) a very capable and interesting system emerged IMO. You can have thousands and even millions of applications running, they hibernate automatically and only consume CPU when they receive a message. Clicks, typing, etc is all events on applications that receive it.
Most OS stuff can be hidden behind special actors, and you can give capabilities by providing those addresses.
THere's a pic and some more explanations at BlueSky[2]
[1] https://tangled.org/dzi-ban.bsky.social/KokoroOS/tree/master [2] https://bsky.app/profile/dzi-ban.bsky.social/post/3murg4lhmt...
tontinton 6 hours ago
What I don't understand is how you do backpressure if sending to an actor is never blocking?
I get the idea of avoiding cyclic deadlocks (A waiting on B waiting on A, or maybe in a longer chain), but crashing on OOM seems like a bad tradeoff.
Apparently this is the same in Erlang.
Or are you actually bounding the number of items that can live in mailbox and make "send" fail when full? Then you can do (bad) backpressure with timers, or register a "wakeup" message when the mailbox got an entry.
Honestly, I would be wary of running an OS that doesn't handle backpressure well, resources get contended all the time in performance critical apps like databases.
Would like to hear your thoughts on this.
nvarsj 12 hours ago
Ime with Akka and Beam, the main drawback of actor systems is debugging. Because you’ve now forced your problem into a distributed problem always. Beam is much better at least since you can execute commands in the runtime to check things. Akka is almost impossible and I don’t miss working with it at all. Unclear here if the author has thought about it as they focus on concurrency bugs which imo are generally easier to reason about in a traditional threaded system.
fpoling 12 hours ago
With actor systems with no shared memory and explicit state implementing time traveling debug support is rather straightforward and gives you a record of all state transitions not just a call stack. This is vastly more useful.
The drawback is that one can have stack trace in prod but no time-traveling debugging. But then a typical workaround is to log explicitly state transitions. Depending on how it is done it can be sufficiently ergonomic and still gives more information than stack traces.
timmisiak 8 hours ago
I was actually thinking about doing time-travel debugging as the next article in the series. I worked on the microsoft time travel debugger, and it's almost funny how easy of a problem it becomes when you have no shared state and a narrow kernel interface. But on the flip side, the biggest reason debuggers are ever useful are the exact sort of bugs that aren't likely in a system like this.
jghn 11 hours ago
I also had this experience with Akka. For people who were able to build up a good mental model of what was what, it wasn't so bad, but still not as efficient as with a standard model. And of course, not all people are capable of having a sufficient mental picture and were totally lost.
I liked it, but my takeaway was that the negatives outweighed the positives, especially when factoring in not everyone was capable of dealing with it. I'm sure there are use cases where that calculus changes, but not the ones I had.
ch4s3 12 hours ago
I’ve never worked with Akka but I’ve always found GenServers on the BEAM pretty easy to debug. You outline all of your state transitions and you can usually see why something is going wrong.
zelphirkalt 12 hours ago
What do you mean by "outline all of your state transitions"? How do you outline them? Where? Is that something you do in the code? In the documentation? In your debugging setup?
ch4s3 10 hours ago
halfmatthalfcat 10 hours ago
It's a state machine, how was it hard to debug? Was it the actual distributed (Akka Cluster) bits or just the system in general?
NBJack 10 hours ago
How would you gather a consistent snapshot of the states each actor maintains to debug it? Unlike a more traditional execution model, there's no direct means of pausing the world to inspect what's going on. It can get shockingly complex.
vbezhenar 13 hours ago
UNIX had no threads originally. Processes are similar to actor model. You create pipe and you exchange bytes between processes.
Of course there are more ways to exchange data between processes, like explicitly allocating shared memory. But "idiomatic" way seems to me pretty much similar to actors.
cowlevel 5 hours ago
Still doesn't. The Linux kernel makes no distinction between threads and processes. What we commonly call "processes" are in fact "thread groups" and play a minor role, mostly related to signal handling and the ability to exit them all at once with a syscall.
The clone syscall allows you to fork a thread with varying levels of sharing. Usually a thread library will share almost everything and a process fork will share almost nothing, but those aren't the only choices. Yu can choose, say, to duplicate the memory map but share the file descriptor table.
monocasa 13 hours ago
Yep, and poll(2) (or later select(2)) to coalesce all possible events into one logical event queue.
signa11 13 hours ago
this is talking about the kernel not the userland.
dapperdrake 9 hours ago
Same difference.
The kernel is a global lock on shared (hardware) resources and stuff like pipe buffers. It is also a library of hardware drivers. Calling the kernel just happens to be termed calling the system "syscall".
From this perspective the BEAM VM or the language run-time are also "kernel".
abound 9 hours ago
I'm surprised nobody has mentioned Hubris [1] yet in this thread. Hubris is Oxide's Rust-based message passing OS. Main differences are that Hubris is focused on embedded devices, has static task registration, and supports preemptive multitasking, but still interesting to compare the choices made for each.
cestith 8 hours ago
I have a book from years ago about writing an OS, and the example OS used in it, MMURTL, used message passing heavily but IIRC not exactly the actor model. It allowed one to swap out parts of the OS the same way, though. One could spin up a new copy and have new messages go to the new version while the old cleared its queue. You could choose to stop processing the queue in the old one and let the messages queue up to let the new one start processing the input queue once the old messages were drained.
https://bookfinder.com/search/?isbn=9780672306556
The core of the actor model is that an actor can interact with the rest of the system in three ways, not just two. It can receive messages, send messages, or spin up a new actor.
cowlevel 5 hours ago
I think usually for hot code replacement of a stateful service, you want to freeze the incoming queue, run a state update procedure, and then resume processing of incoming messages by the new code. For a stateless service the strategy you described can work.
KentLatricia 9 hours ago
An example of the actor model from the embedded world, QP, https://www.state-machine.com/
scroot 8 hours ago
Posting about uFork [1] again! It's a ground-up design for a computing system that is actor based, and one of the most clever things I've encountered in recent years.
peter_retief 13 hours ago
Interesting concept Tim, I borrowed some ideas from you
timmisiak 8 hours ago
Very cool! There's a certain infrastructure system at Microsoft with a similar job, and folks would joke that it was an email server repurposed as a message queue.
nxobject 11 hours ago
I’m curious to see whether “no pre-emption” will hold as applications scale up. Given the aggressive enforcement of time-slicing, I’d have trouble writing, say, tasks that lends itself to a recursive call structure yet yields in a predictable amount of time.
(I wrote a parser-compiler for the classic Macintosh OS, which notoriously had cooperative multitasking… by the end I ended up simulating pre-emption by sprinkling calls to a routine that did “check timer, yield to OS if needed”.)
cowlevel 5 hours ago
Perhaps they could add a special kind of compute-bound actor that is preemptible but can't receive messages asynchronously, other than termination.
dapperdrake 9 hours ago
Obviously, it won’t hold up. That is why most production systems converge on non-cooperative externally pre-empted multi-processing and multi-threading.
halfmatthalfcat 10 hours ago
I absolutely love actors and what I really wish existed (and where Rust/Embassy/Ector get really close to and where QuantumLeaps has somewhat of a monopoly on) is a full embedded actor system toolchain.
Interrupts and timers are such native embedded concepts that fit into hardware, its literally a perfect fit for an actor system.
cestith 9 hours ago
One nice thing with an interrupt system handled through an actor system I suppose would the ability for an interrupt handler actor to optionally jump the line and put its messages at the front of another actor's queue while everything else is FIFO. If the input queue is external to the actor and managed by the OS (or actor library/runtime if running on top of a non-actor OS), this should be trivial to do.
Panzerschrek 13 hours ago
> A handler always runs to completion in a bounded amount of time
What if I want to start a computation and I can't reason how long it takes, so that the OS kills my program, because it spent too much time? In a traditional OS it's not a problem, it can interrupt my program at any moment and resume it later.
> An idle actor instance has no stack, and no register context to save
If I have no stack, what can I use to save program state? Do I need to mess with global variables for this?
timmisiak 8 hours ago
> What if I want to start a computation and I can't reason how long it takes
I wrote about that. It's the main weakness of this approach. You can solve it fairly easily for a linear style of task (decompression, encryption, etc.) because you can capture your state as a simple future. For cpu intensive recursive algorithms, it gets far messier.
> If I have no stack, what can I use to save program state? Do I need to mess with global variables for this?
All state is actor instance state. Kind of like any class based programming paradigm for an object not actively executing.
cowlevel 5 hours ago
I presume you could still make your own stack, and even save the stack pointer and program counter as part of your instance state?
dapperdrake 9 hours ago
How does he prove termination for boundedness in the general case?
Sounds like someone is still discovering the difference between the necessary assumptions for their wish to become true and the assumptions they are actually making.
timmisiak 7 hours ago
It's a constrained system. CPU intensive loops are easily transformed into potentially yielding futures. But not everything fits well in the model. CPU intensive recursive algorithms are messier.
There's no claim in the article that this is a superior system than threads in the general case.
Findecanor 7 hours ago
Reminds me of Microsoft's research OS Midori which also did not have preemption: only "green threads" with async and coroutines, albeit on multiple hardware threads.
https://joeduffyblog.com/2016/11/30/15-years-of-concurrency/
frumiousirc 14 hours ago
An interesting project, I say as a fan of actor pattern at the application level.
> A single handler execution has a limited time window and must run to completion in a small time window. The kernel enforces this by killing any instance that exceeds the limit.
And then what? If the actor was in the process of writing a file, what is left of the bytes on disk? Does another or the same actor get restarted to complete the write without introducing corruption?
Also, how does this system handle multi-threading inside an actor? The prior post says Linux apps are supported so it's not just actors all the way down. Do multi-threaded Linux programs starve the OS?
And what is the shape of the OS kernel? Presumably there is a core monolith that handles message passing and execution. Is it ignorant of the hardware? "I can change out a graphics driver, storage driver, or an application all without a reboot" implies the answer is "yes". But, that can't be the whole answer because the core must know about hardware resources in order to know how to execute and kill actors.
Maybe a follow up post covering these core OS issues?
nrdvana 12 hours ago
> If the actor was in the process of writing a file, what is left of the bytes on disk? Does another or the same actor get restarted to complete the write without introducing corruption?
It wasn't spelled out, but my reading is that an actor is never "in the process of writing a file" because that would be a blocking operation. It probably has to start with a message which requires data to be written and then copies data into a buffer and generates a message to the kernel that the buffer needs flushed along with a message to its future self about what to write next, then exits. If it wrote everything it needed into the available buffer, it would emit a different message saying the file needs closed. AFAIK it all boils down to the same coding style as Node.js where every blocking file operation becomes an async re-entry point.
zbentley 12 hours ago
Hmm. Then the GP’s question ends up being about transactions (interrelated series of messages sent by an actor). What happens if an actor is killed by timeout in the midst of sending and waiting for responses from a bunch of “append bytes to file” messages?
dapperdrake 9 hours ago
Waldo et al. (1994)
Distributed system equals partial failure and concurrent execution.
The partial failure part is where most naive map-reduce approaches get stuck. This is also where exception handling gets stuck.
tgv 12 hours ago
This is cooperative multi-tasking all over again. I don't think it's for a real, widely used OS.
Not only would the file get cut off, but tasks will run faster on one machine than on another, meaning that your program may run fine on your computer, but what it'll do on another is anybody's guess.
It also uses one thread on one processor, so it basically throws a lot of performance out of the window. Perhaps it works on embedded, although the idea of a time limit on every message seems rather harsh.
timmisiak 7 hours ago
It's explicitly cooperative outside of the Linux VM that it runs. It's deployed to exactly one computer sitting on the desk next to me. So no, not widely used.
> It also uses one thread on one processor
Zero threads, and 6 processors.
hn_submit 9 hours ago
I doubt if a fully cooperative threading operating system (because that's what it is essentially) can be made useful. MMURTL, for example, is mostly a cooperative threading operating system but it does have some preemption mostly to handle high priority messages coming from interrupts.
timmisiak 8 hours ago
I'd agree that it's not useful as a general purpose model with a third party app system. In this system, "native" apps are all built and verified with a single toolchain, and anything outside of that lives in a lightweight Linux VM.
So for purpose-built applications I think it can be useful. As a general purpose OS where people want to run a browser, it's probably not likely to be useful.
evmar 8 hours ago
The OS runs Firefox (per another post on the blog), which itself uses threads. How does that work? I guess you need some sort of translation layer to run Linux binaries, which then implements threading atop this actor system?
skilesare 11 hours ago
Neat! I've been working on generalizing the Motoko(actor based language that compiles to warm) to a general runtime at https://moxzi.ai, and I hadn't considered pushing it down to the OS level. If you are looking for a higher level actor based language motoko is worth a look.
hollowonepl 11 hours ago
Yep, it's super fun to write your own OS. Especially in the AI era to accelerate theory testing as the one attached in the blog post.
If I agree with it, I don't know.. I have my OS development testing my own theories for last 6 months.. and again.. all I can say is that it's fun, thoughtful and interesting to pursue product management learning points in such project. Completely doable for a single person to have something that works and is complete and from scratch. No Temple OS bullshit for schizophrenics.. No need to be cursed by Perkele like Linus to find devil's skills to convince the community to adopt a school project and go nuts with global adoption..
just for fun, real, yet homebrew OS that can run on your own hardware.. or cyberdeck that may be your next project when you get your OS running on boring mundane laptop just fine.
signa11 15 hours ago
perhaps it is time to discuss the torvalds-vs-tannenbaum debate once again in $CURRENT era ?
pjmlp 14 hours ago
That has already been won, outside BSD/Linux universe, most OSes are hybrid, with tons of userspace processes and drivers, also microkernels have won on the embedded RTOS space.
Also running cloud software, serverless runtimes, or distroless containers, on top of type 1 hypervisors, is pretty much a microkernel like architecture.
kvuj 10 hours ago
> outside BSD/Linux universe
I feel like you're glossing over 80%+ of smartphones and 90%+ of all servers with that single mention, lol
pjmlp 9 hours ago
hnlmorg 15 hours ago
Were they talking about actor models too?
I remember the debates about monolithic vs microkernel designs. But it was so long ago that I can’t remember any of the specifics.
mrkeen 15 hours ago
Yeah, the thrust of the pushback was something along the lines of "great, your individual modules are small enough to reason about individually, but now you've dumped too much complexity into the communication channels instead"
hnlmorg 14 hours ago
cowlevel 5 hours ago
OS development has kind of stalled out for the past two decades - we just took whatever we had in 2002 and froze it there. This presentation is about the hardware side but still inspiring: https://www.usenix.org/conference/osdi21/presentation/fri-ke...
hnlmorg 3 hours ago
signa11 15 hours ago
> ... debates about monolithic vs microkernel designs
message passing was the mechanism underneath the debate, and not the headline afaik.
rbanffy 13 hours ago
I would love to see a Smalltalk implementation on top of this.
abecedarius 10 hours ago
E wasn't Smalltalk but was designed by Smalltalk enjoyers: https://web.archive.org/web/20261128134610/www.erights.org/
Shorel 8 hours ago
That kinds of remind me of preemptive scheduling in Windows 3.1.
There are no actual threads, all programs collaborate to share the single processor they had at the time.
thornjm 14 hours ago
Im familiar with the actor pattern but completely naive to their implementation. I’m having trouble imagining a few things and might be way off the mark. A few questions that might help others resolve my confusion:
1. Are there as many processes as there are cores on the CPU?
2. Is there a single message queue shared across cores?
3. Presumably two networking actors or two filesystem actors could be processing different messages on different cores and hardware resources can still be contested?
RossBencina 13 hours ago
I'm only familiar with implementing run-to-completion actors. If a message is sent to an actor, the actor's behavior needs to run to process the message. You could have a message queue per thread (physical or logical core), or a message queue per actor, with a separate scheduler to decide when each actor should get a chance to run. There are obvious performance benefits to keeping communication local to a core, so hierarchical architecture where there are core-local actor networks and cross-core networks can make sense.
As to your final question, actors processing messages is a computation, i/o of any kind would involve sending messages to other lower-level i/o actors that multiplex or coordinate access to individual hardware resources.
mightyham 12 hours ago
> 3. Presumably two networking actors or two filesystem actors could be processing different messages on different cores and hardware resources can still be contested?
I won't presume this is how DbgOS works, but considering that the author mentions writing drivers as actors, I would imagine that two actors would not be allowed to represent the same underlying resource. You would have one actor for each device, then and only then can any number of other concurrent actors build functionality on top of it through message passing.
monocasa 13 hours ago
1) Typically the number of actors and hardware threads are disconnected and it uses some MxN scheduler. There's a lot of related techniques here, green threads, user threads, coroutines, fibers, etc. Though the implementation under discussion here only uses one hardware thread, and looks a lot like the single threaded models like how node wraps libuv.
2) It can be thought of as at least one message queue per actor.
3) Yep.
McKorty 8 hours ago
I my passion game project is my world-server an only node-process with eventloops, presence, movements, talk bubbles etc. run without threads. A challange is a chess computer, he run in an own worker_threads, they comunicate only about messages and don't share space. Max. 2 claculatons at the same time, others wait in a queue. Is this yet a Actor-Modell or stilla worker-pool?
mosura 13 hours ago
Is it possible this guy never ran into a UI event loop? Like winmain or the Android Handler . . .
Android actually works an awful lot like this, without calling it actors.
nottorp 12 hours ago
Well most async enthusiasts haven't either :)
textlapse 6 hours ago
How does this compare with Swift actor model?
objectforlife 14 hours ago
So.. message passing? Alan Kay was right all along?
InsidiousWombat 13 hours ago
"right" is one dimensional. It was always a good tool from reasoning perspective. Just not always from performance perspective
flossly 12 hours ago
Next: async/evented model? Just one giant event loop (per CPU)? /joke
zbentley 12 hours ago
You joke, but that’s … almost kinda-sorta just what a hardware interrupt controller is.
YesThatTom2 13 hours ago
Sounds like a great follow-on project to Amoeba OS by Andrew Tanenbaum.
cess11 14 hours ago
"We need a way to send a request to another actor, and provide it a way to send back a response that can be connected to the original request. For that, we have a “reply slot”, represented as a ReplyTo<R> in the code for actors."
It's probably partly due to habit but I like the BEAM solution to this, i.e. provide your sender ID and let the receiver figure it out. Oftentimes you don't care about a response, you just want to flick a switch at a distance or throw some garbage into a bucket.
For me it makes the basic model simpler to hold in my mind and it's been a nice learning experience to look at how stuff on the BEAM gets from there to state machines and generic servers and supervisors and so on.
One of the nicest things with the BEAM is that it feels like I have an OS available when programming. I don't get that with threading in e.g. Java, and I don't think I'd get it from Golang either.
Does Rust have pattern matching on function declarations? I.e. could the match-block be switched for several handle-functions instead in the example? If not, then I think I prefer the BEAM way there too, it's quite nice to break out the message handlers into functions matching on the message instead of going through a match/case and then into the actual handlers.
The preemptive multitasking on the BEAM is convenient too, it almost always gives the result I want.
I don't see an example in TFA of how the actors are addressed, do they get a number when instantiated or somesuch and then one does like a send-syscall with that number?
timmisiak 7 hours ago
> Does Rust have pattern matching on function declarations?
Nope, that'd make this a fair bit nicer.
> how the actors are addressed, do they get a number when instantiated or somesuch
There's a system to register an instance with a name for lookups, everything else is based on explicit handles passed around.
pjmlp 13 hours ago
> One of the nicest things with the BEAM is that it feels like I have an OS available when programming. I don't get that with threading in e.g. Java, and I don't think I'd get it from Golang either.
I certainly feel like that when doing Java and .NET runtimes, Java especially is what made me stop caring about POSIX.
Both are the closest I have been able to do in mainstream to the OS abstraction layers, past my Smalltalk and Lisp experiences.
kibwen 13 hours ago
> Does Rust have pattern matching on function declarations?
Rust supports patterns in function declarations, but not for the purposes you're thinking of. In function arguments, patterns are required to be irrefutable, so no redeclaring a function with different refutable patterns each time. Rust only wants a single source of truth for each function (possibly attributable to an allergy of anything that could be mistaken for C++-style function overloading), and since Rust pointedly declines interprocedural type inference, redeclaring your function multiple times with full type annotations every time would just be more verbose anyway (in contrast to something like Haskell, which supports what you're asking for but allows type inference in function signatures).
jvanveen 10 hours ago
Another Rust OS, running (almost) on a Fairphone, https://pinnacle-os.eu/blog/fairphone-4/
jerf 10 hours ago
There are some serious drawbacks with this being the fundamental model of an OS. An OS needs to be able to handle everything that you might want that OS to be able to do. A strict actor model has some performance issues, because it requires all message communication to be copied around. There are some pathological cases for this where you need lots of copying and communication for things that are not difficult with sharing. Even Erlang actually doesn't have full memory isolation, because it can share immutable binary terms between processes and do garbage collection on the references rather than copying them around entirely. Since the language has no way to modify the immutable values, it's safe, but it also means the naive understanding of "no shared state" is not actually true, in a way that will matter to an OS.
You can also get some performance issues depending on how your route messages; for instance Erlang does this pattern matching thing on messages but that can let them back up and create subtle and hard-to-diagnose memory leaks, and subtle performance issues trying to pick certain messages out of a queue. In a specific Erlang program the solution is, broadly speaking, "don't do that", but an OS must be ready for vastly more pathological conditions than "a specific Erlang program".
Also, cooperative multitasking at the operating system is well explored and a known major failure. It damn near killed MacOS and required a massive and expensive effort to get MacOS off of it before it did kill it. In a nutshell, as you scale up the probability that at least one process will misbehave and fail to give up its time slice approaches one, at scales much smaller than what constitutes a modern OS. I don't like it even today even in my own code, but the only reason it is even remotely viable is that it is still contained to single OS processes and even if one OS process has something not cooperating the surrounding OS is fundamentally pre-emptive. If that was not the case, all "async" code would be dead in the water today and nobody would be using it at all. If an OS is going to be actor based I would 100% expect those actors to be threads, in the sense of being independently scheduled entities. not being cooperatively scheduled.
Or, to put it another way, the reason anyone is using cooperative multitasking today is precisely because they're using it in an OS that is ensconcing them within a threaded environment at the OS level (where here an "OS process" is a thread for these purposes). If you take that layer away and everything is running in the same cooperative context, suddenly the costs of cooperative multitasking literally exponentially skyrocket and it is completely unappealing.
I also think there's some dissonance between having Rust and having a requirement that all code be actors within a given OS, because the two overlap a lot. Actors are already a fairly viable mechanism for managing memory, if you just don't let actors fiddle with other actor's memory. So this super rich and complicated borrowing mechanism is really doing a lot of work that is redundant to the actor boundary. "Actors" as one technique in a Rustacean's toolbelt is a fine choice, but if the OS itself is going to lift up actors as the one true and fundamental approach to writing code, Rust burns a lot of design budget on problems that are suddenly nowhere near as large anymore, because the OS really ought to be providing isolation fundamentally.
Now, of course, if you're just playing around, hey, do as you like. But as a serious foundation for an OS that others might use there are major issues here.
On the plus side, as Erlang demonstrates, if you make it so actors can communicate across the network then you get the ability to build large computers out of small ones with some relative ease. Though to raise actors up to the OS level, you might need to do something that Erlang really doesn't and make a real, type-level distinction between local actors and actors that might be remote, because actors over the network necessarily have unreliable message passing, and implementing local OS services with "unreliable message passing" will add additional complication to every such interaction. Being able to do what Go does with channels and make message handoff and reception an explicit synchronization point is really, really convenient, and can even be harnessed to do some OS-level optimizations like "hey OS, here's my buffer, you're the OS and specially blessed so instead of sending me a copy of a byte buffer for me to then copy into my own local representation why don't you just take this handle to some memory and slam it straight in there" fairly safely, mitigating some of the performance impacts I mentioned at the top.
timmisiak 7 hours ago
> An OS needs to be able to handle everything that you might want that OS to be able to do
This isn't designed to be a fully general purpose OS.
> it requires all message communication to be copied around
In most cases there are zero copies. Ownership is transferred.
> Erlang does this pattern matching thing on messages but that can let them back up
Not covered in the article, but this OS doesn't let an actor choose what to handle. Which has its own issues.
evmar 8 hours ago
> In a nutshell, as you scale up the probability that at least one process will misbehave and fail to give up its time slice approaches one
The OP mentions that the kernel kills processes that fail to give up their time slice. This might have its own problems (e.g. an algorithm that unexpectedly rarely goes over budget) but I believe iOS has taken a similar approach.
brcmthrowaway 13 hours ago
What if someone wanted to do multicore number crunching??
pjmlp 13 hours ago
See Connection Machine, talking across CPUs via Pvars.
bluegatty 12 hours ago
neat idea!
gzell 11 hours ago
Why does this feel like Groundhog Day and how did this make it to no. 2 on HN?