If such a race condition is critical, then making A and B "otherwise independent" is a poorly designed architecture (and, yes, novices will do this, which is why there is a big admonition in the Elixir docs: https://hexdocs.pm/elixir/master/GenServer.html#module-when-...). Maybe they should all be branching logic or state machine in the same actor and you shouldn't be coordinating with message passing?
If for some reason A and B TRULY need to be asynchronous and independent (let's say they are tracking real-world things), AND order matters, then no amount of language or VM architecture will get you out of building a transactional lock, consensus system, or CRDT to guarantee sane results. That is just how the universe works.
a) be sure to give C whole requests, don't ask C for current data, modify it in A and then send it back to C (which is begging for B to send a modification in the mean time). C's mailbox enforces an ordering on requests (all calls will be handled in the order they are received, not in the order they are sent)
b) rather than A sending to B and C, and B also sends to C, send only from A to B and from B to C. B sends along A's information. Downside is if B crashes before sending to C, A's information is lost. You could also have A send to C, and C replies to B, which then does work and sends back to C.
c) when multiple processes are working on a single thing, try to combine them. A single process will find it hard to race with itself, and will have a clear order of events. I'm in the middle of cleaning up some code that had three processes around one thing (a state process, a reader and a writer), and there were so many weird and racy things because of the separation; putting it into one process means things can't change unexpectedly.
A simple mitigation against these sorts of race conditions would be for C to maintain a version number alongside its data, then have any update requests send back that version number. If the message's version matches the current, then do the update and change the version number; else, reject the message with a reply directing the sender to reobtain the current data and try again. This way, if both A and B grab data from C and then simultaneously try to update that data in C, you won't lose any data.
This is (relevantly to Erlang) exactly how CouchDB works.
See the following for an explanation:
"Physical Indeterminacy in Digital Computation" https://papers.ssrn.com/abstract=3459566
Cheers, Carl
I'd guess he knows...
Besides, such a fork join model might be theoretically free of timing and coordination in a system with infinite resources (bus widths, no cache coherence, an infinitely fast coordinator e.t.c.) but that's not what silicon looks like.
The nice thing about the Actor model is exactly that it immediately exposes you to non-determinism, distributed state, and in Erlangs case, failure.
It's what allows Erlang systems to "effortlessly" (you had to put the effort upfront) span many node clusters with arbitrary reliability in the face of failures.
Somewhere else you write:
> The problem is this corner case opens up all the fundamental issues I mention. When we include it we've got a big non-deterministic, racey, stateful, problem.
That's not caused by the Actor model, but by the fundamental laws governing distributed systems. Distributed systems are inherently, non-deterministic, racey and statefull.
Two generals dictates that you can't solve these issues, unless you're on a single writer system (which your scatter-gather algorithm is an example of, in which you will always be limited by the throughput of the process that organises your scatter-gather operations / your control plane). In which case, you might as well ignore all forms of concurrency and do one thing at a time, which will be faster anyways.
Erlang is about distributed coordination. It's all about concurrency, and parallelism is a means to the end of increased reliability. Merge Sort is data parallel SIMD with a single coordinator.
It's like the difference between multi factory industrial food production (distributed), and you handling multiple pots and pans on the same stove (parallel).
You'd never use message passing for that, because it has way too much overhead in and of itself. And if you had more data than could fit a single machine, you'd choose a different algorithm anyways.
It's not that hard to find a simpler implementation for a problem that's not really distributed by nature.
You're also missing the huge learning opportunity for undergrads here. It's totally possible and actually easy to implement merge sort with message passing (although nobody would do it in the real world), and it provides a good lesson.
The first way to implement something is often not the correct one.
The naive but wrong implementation is to send messages with each value to be sorted. So the mailboxes act like a list. However since there's no ordering guarantee, the issues you mentioned will crop up.
Since messages are our unit of coordination, the naively fixed version simply sends the entire array to its parent node which then merges the arrays it received.
However there is also the possibility to send a tuple containing the index in the subarray as well as the value, which allows the parent to buffer the value and wait for the gaps to be filled. Which teaches you something about TCP as well.
Seriously. Why only ask your undergrads questions, that they can't get wrong? Seems a waste of everybody's time. You should rather teach them about the tradeoffs between different concurrency and parallelism models. SIMD for data parallel high perf stuff. Actor model, for distributed coordination and reliability. Dataflow for FPGA programming. There's no one fits all model.
You can write something using fork-join that works correctly in theory, but expecting it to always work while running on undeterministic hardware is exactly the kind of blind optimism that causes so much software to come down crashing if you look at it wrong.
This seems backwards to me - a fork-join task has no state and can access no other task's state. You can restart it if it fails as many times as you want and the result is always exactly the same. You can't say the same with running an actor twice or sending a message twice - you may get a different result the second time!
How simple is "simple" What happens if process 1 crashes? What if it suffers a network disconnection and looks like it crashes, but then tries to reconnect later? What is the correct logic for completing the combined task?
Wikipedia article is way out of date :-(
There is an up-to-date blog here with links to current articles:
I was at Code Mesh in 2018 in London to attend your "ULTRACONCURRENCY IS THE FUTURE OF PROGRAMMING" presentation
Meeting you and Joe Armstrong in the same place has been one of the greatest pleasure of my professional life.
People talk about that all the time with actors and message passing, since the actor model is largely a tool for structuring the management of those things (not usually for eliminating them, because for many problem domains those are inherent to the domain.)
When there are multiple agents/actors in a distributed system, and the timestamp resolution is datetime64, and clock synchronization and network latency are variable, and non-centralized resilience is necessary to eliminate single points of failure, global ordering is impractical to impossible because there is no natural unique key with which to impose a [partial] preorder [1][2]: there are key collisions when you try and merge the streams.
Just don't cross the streams.
[1] https://en.wikipedia.org/wiki/Preorder_(disambiguation)
[2] https://en.wikipedia.org/wiki/Partially_ordered_set
The C in CAP theorem is for Consistency [3][4]. Sequential consistency is elusive because something probably has to block/lock somewhere unless you've optimally distributed the components of the CFG control flow graph.
[3] https://en.wikipedia.org/wiki/Consistency_model
[4] https://en.wikipedia.org/wiki/CAP_theorem
FWIU, TLA+ can help find such issues. [5]
From experience with clocks, you should really be actively testing the delta, and not just assuming it.
> The Lamport timestamp algorithm is a simple logical clock algorithm used to determine the order of events in a distributed computer system. As different nodes or processes will typically not be perfectly synchronized, this algorithm is used to provide a partial ordering of events with minimal overhead, and conceptually provide a starting point for the more advanced vector clock method.
I have written a lot of actor-based systems, and I’m pretty sure this is heavily talked and thought about.
The race condition situation you described is only a problem for people not used to concurrency and actors. It is bad form to have your actor depend on the order of messages it receives if it is intended to receive messages from multiple actors. So the situation you’ve described is simply bad actor programming.
Often, a good way to program actors is to have them be finite state machines.
Also, your shared mutable state reference does not meet any definition I have ever seen of “mutable”. In actor systems, yes, actors can receive the state of other actors, but that state is a copy. The internal state of an actor is not allowed to be mutated by an external process, typically.
Of course it is!
> The internal state of an actor is not allowed to be mutated by an external process
Having A tell C to mutate its state instead of A just mutating C's state is just like using a 'private' keyword in another language - insofar as mutation is concerned. Race conditions do not care if you ran:
a() {
kindlyInformCToIncreaseXWheneverYouGetThisMessage();
}
versus a() {
c.x++;
}
It's still a mutation.Effectively, mutations to the internal state are "serialized" by the owner process, so it's easier to handle possible race conditions without using explicit locks/semaphores.
One of the biggest strengths in processes in Erlang is that they serialise access, this serialisation though isn't simply that they serialise or are written in a way of "run this once". It's more like processes are (or can be used) basically state machines. This pattern is pervasive and you can find it in the OTP library, the most common construct (although there's proper finite state machine OTP abstractions) is the gen_server. The gen_server, is a generic server interface that uses message passing. It can be described as the simplest of agents that has a baked in generic interface.
Where your sample falls short is that, when you code the interface for a gen_server I'm (or can, usually will) codify any needed relationship between the state a process is in and what it can do with the "messages" it receives according to the state it is in. This allows me to completely forgo of any concern about how someone will use it without having to explicitly define handling of cases I didn't intend.
If I have (pseudo code but completely codifiable):
- when msg and msg == "get_status" and state == "receiving" -> reply, function_that_calculates_response(state), new_state = make_new_state(state)
- when msg and state == "not_available" -> reply unavailable, new_state = state, continue_to: "recheck_assumptions"
- when "recheck_assumptions" and state -> noreply, new_state = check_assumptions(state)
- when msg, state -> reply bad_request, new_state = state
Now I don't have to worry about any nook, escape hatch or other such in the language, that someone will rewrite the state of this process from another thread, or function call or whatever. Nowhere will a process be able to change the state of this process from outside the process meaning I can clearly define the states it can assume. I also don't need to write overly defensive code, or find out that in some given situation something changed the state outside of what I explicitly coded.
In the previous example this means that if two processes (running in different schedulers, nodes, or wtv) both send a msg, the mental model of the receiving gen_server will be a consistent mailbox from which it picks msgs to process one at a time. If one of the msgs would force the gen_server to change its state, and another asks for the status, it won't happen that both of them can have their conditions evaluated at the same time, but the states differing.
So if msg_1 changes the state, msg_2 will be interpreted on this new state. It can't happen that msg_1 is being processed, changes the state in some intermediate step, while msg_2 is interpreted in the same exact conditions as msg_1 (unless msg_1 leaves the state as it was). This is not true for some mutable code, you can have two functions from different threads or whatever, call a function on X concurrently, and the evaluations for these calls being done based on the same state, while then fun1 and fun2 operates on the state. Perhaps fun2 assumed that it was allowed because of being in a given state, but while doing its thing that assumed that, the state had been changed by fun1 that was running at the same time.
It also means, that this process can do whatever it wants, including spawning new processes and whatever, to do their thing in different contexts but its state can only be mutated by itself. This then forces those things (or me when writing code) to explicitly define their interface and if I want to rely on the result of those things changing the state, I need to explicitly message pass it back, for which I will have the previously defined interfaces.
This then when coupled with supervision, links or monitors can make for extremely resilient processes even when they encode complex flows between multiple parts in the presence of possible unknowns.
Can you still bork it? Yes, but the area is much smaller and I guess after a while of working with it it's a very simple model that once understood is always the same. Are there areas where this is not the right away to do it and mutable is right? Probably yes, people point out performance issues but I think there's also some overstating about it, in most cases it seems it can be solved, but I can believe there are possible issues there so not a silver bullet.
Sorry for the long winded post.
Seems to be mentioned in the article, with an example: > If more than one process sends signals to a common process, they can arrive in any order even when you “know” that one of the signals was sent first.
The problem of message order non-determinisim is real, but for orchestration logic in scenarios with multiple uncoordinated message sources, it's inescapable. What is important is that the programming environment helps you deal with it, and doesn't introduce additional - "accidental" - complexity.
I discussed this topic at QCon 2010, and ran through some demos to illustrate where many commercial projects actually DO go wrong, and why the textbook Erlang model keeps you safe.
https://www.infoq.com/presentations/Death-by-Accidental-Comp...
The key guarantees that Erlang gives you here are: * Messages from A to B will all arrive (if they arrive) in the order in which they were sent, and you can detect if there is an interruption * A receiving process can decide in which order messages are processed.
It turns out that people intuitively understand that if Alice and Bob each send me a message, independently of each other, I cannot know which message reaches me first. This mirrors a fundamental real-world constraint, and in a distributed processing environment, there really isn't much you can do about it.
There are other concurrency-related problem domains, some for which the Erlang implementation, at least, is not ideal.
If that doesn't work, don't use Erlang. No sarcasm. The process model is nice but does preclude certain high-performance patterns.
There doesn't seem to be a real solution to deadlocks. I got the oreilly book in front of me and it's basically saying: be careful, but don't worry.
And I don't think erlang has a shared mutable states. In fact a google search for "erlang shared mutable state" has you as the first result.
If ETS is shared mutable state, so is a process with state that accepts changes, as chrisseaton posits. Of course, shared mutable state with clear boundaries between mutations is a lot better than shared memory where everyone can write and read things in bits and pieces.
Arguably (well, of you ignore the process dictionary, which everyone seems to) Erlang lacks local mutable state, but has shared mutable state through actors.
I've seen such ideas tossed around, but I don't think I've ever seen an implementation.
An actor has state. It's mutable - each message can modify it. It's shared - two process working with a shared actor share that state. To me, that's shared mutable state. It causes classic race conditions.
(I know this is an unpopular opinion, and somewhat deliberately contrary and provocative, but ultimately truthful.)
Also note that erlang is not a pure actor system. It is relatively hard to accidentally write a deadlock in erlang with OTP. In about 3 years of programming elixir I've only written a deadlock three or four times (and caught them all in tests). Even so if I had pushed it to prod, it would have timed out certain operations that would have triggered dynamic restart of the relevant processes.
two process working with a shared actor share that state
I think this is where I disagree. They may share an actor but the state of the actor belongs to the actor. To say they share it implies they can always change it independently but that's not the case. Actors don't trample on each other's internal states. For example a simple mutex semaphore pattern fixes your race condition.The actor's state is shared in the sense that both processes can change it in ways that are visible to each other. The actor can control access to it, but unless the actor never changes state in response to messages (in which case why bother with actors at all?) there's still something that changes. Constrained state is still state.
For a proof, see the following article:
"Epistemology Cyberattacks" https://papers.ssrn.com/abstract=3603021
The same thing happens in real life. You cannot solve this problem by using a shared memory model: it isn't inherent to the actor model, it is inherent to the reality of some situations.
I have seen some people avoid referring to scenarios like this as race condtions, but in general there are some situations where you generally need to assign a winner (you have a serial actor decide or you use a lock). It could be real (like the auction example) or it could be bad design where a system has been architected to be unnecessarily concurrent and events that are in reality serial are fired off in parallel and the network (or even the thread scheduler or something else) reorders them. Try to avoid creating unnecessary races, learn to identify real races.
synchronization is a basic requirement in concurrency.
in my experience the actor model implemented in Erlang provides simpler solutions to the problem as highlighted in this comment https://news.ycombinator.com/item?id=26535230
for example if B sends a message to C in response to a message from A, it could send back a specific response to A that will contact C on its behalf and avoid the non determinism
the fact that the actor model provides strong guarantees about messaging order between two actors, makes it easier to reason about it and avoid the pitfalls associated with it
it is also a well known problem
citing the Pony lang FAQ
So for example, if actors X and Y send to actor Z, there is no guarantee what order the messages will be processed by Z except that we can say, all messages sent by X will be processed in the order they were sent, as will all messages sent by Y. However, messages from X and Y can arrive at Z interleaved in any order that maintains the causal ordering of X to Z and Y to Z.
If two otherwise independent processes A and B are sending messages to a single process C, it's non-deterministic which arrives at C first. This can create a race condition. C may respond differently depending on which messages arrives first - A's or B's. This is also effectively an example of shared mutable state - the state of C, which can be mutated whenever a message is received - is shared with A and B because they're communicating with it and their messages work differently based on the current state.
Non-determinism, race-conditions, shared mutable state: the absolute opposite of what we want when dealing with concurrency and parallelism.