source: doc/theses/colby_parsons_MMAth/text/actors.tex @ 6d18ddb

Last change on this file since 6d18ddb was 6d18ddb, checked in by caparsons <caparson@…>, 13 months ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Merged actors.tex. Added 'Actor Termination' section and reworked 'Actor Send' section.

  • Property mode set to 100644
File size: 78.5 KB
Line 
1% ======================================================================
2% ======================================================================
3\chapter{Actors}\label{s:actors}
4% ======================================================================
5% ======================================================================
6
7% C_TODO: add citations throughout chapter
8Actors are an indirect concurrent feature that abstracts threading away from a programmer, and instead provides \gls{actor}s and messages as building blocks for concurrency, where message passing means there is no shared data to protect, making actors amenable in a distributed environment.
9Actors are another message passing concurrency feature, similar to channels but with more abstraction, and are in the realm of \gls{impl_concurrency}, where programmers write concurrent code without dealing with explicit thread creation or interaction.
10The study of actors can be broken into two concepts, the \gls{actor_model}, which describes the model of computation and the \gls{actor_system}, which refers to the implementation of the model.
11Before discussing \CFA's actor system in detail, it is important to first describe the actor model, and the classic approach to implementing an actor system.
12
13\section{Actor Model}
14The actor model is a concurrent paradigm where computation is broken into units of work called actors, and the data for computation is distributed to actors in the form of messages~\cite{Hewitt73}.
15An actor is composed of a \Newterm{mailbox} (message queue) and a set of \Newterm{behaviours} that receive from the mailbox to perform work.
16Actors execute asynchronously upon receiving a message and can modify their own state, make decisions, spawn more actors, and send messages to other actors.
17Because the actor model is implicit concurrency, its strength is that it abstracts away many details and concerns needed in other concurrent paradigms.
18For example, mutual exclusion and locking are rarely relevant concepts in an actor model, as actors typically only operate on local state.
19
20An actor does not have a thread.
21An actor is executed by an underlying \Newterm{executor} (kernel thread-pool) that fairly invokes each actor, where an actor invocation processes one or more messages from its mailbox.
22The default number of executor threads is often proportional to the number of computer cores to achieve good performance.
23An executor is often tunable with respect to the number of kernel threads and its scheduling algorithm, which optimize for specific actor applications and workloads \see{end of Section~\ref{s:CFAActor}}.
24
25\subsection{Classic Actor System}
26An implementation of the actor model with a community of actors is called an actor system.
27Actor systems largely follow the actor model, but can differ in some ways.
28While the semantics of message \emph{send} is asynchronous, the implementation may be synchronous or a combination.
29The default semantics for message \emph{receive} is FIFO, so an actor receives messages from its mailbox in temporal (arrival) order;
30however, messages sent among actors arrive in any order.
31Some actor systems provide priority-based mailboxes and/or priority-based message-selection within a mailbox, where custom message dispatchers search among or within a mailbox(es) with a predicate for specific kinds of actors and/or messages.
32Some actor systems provide a shared mailbox where multiple actors receive from a common mailbox~\cite{Akka}, which is contrary to the no-sharing design of the basic actor-model (and requires additional locking).
33For non-FIFO service, some notion of fairness (eventual progress) must exist, otherwise messages have a high latency or starve, \ie never received.
34Finally, some actor systems provide multiple typed-mailboxes, which then lose the actor-\lstinline{become} mechanism (see Section~\ref{s:SafetyProductivity}).
35%While the definition of the actor model provides no restrictions on message ordering, actor systems tend to guarantee that messages sent from a given actor $i$ to actor $j$ will arrive at actor $j$ in the order they were sent.
36Another way an actor system varies from the model is allowing access to shared global-state.
37When this occurs, it complicates the implementation as this breaks any implicit mutual-exclusion guarantees when only accessing local-state.
38
39\begin{figure}
40\begin{tabular}{l|l}
41\subfloat[Actor-centric system]{\label{f:standard_actor}\input{diagrams/standard_actor.tikz}} &
42\subfloat[Message-centric system]{\label{f:inverted_actor}\raisebox{.1\height}{\input{diagrams/inverted_actor.tikz}}}
43\end{tabular}
44\caption{Classic and inverted actor implementation approaches with sharded queues.}
45\end{figure}
46
47\subsection{\CFA Actor System}
48Figure~\ref{f:standard_actor} shows an actor system designed as \Newterm{actor-centric}, where a set of actors are scheduled and run on underlying executor threads~\cite{CAF,Akka,ProtoActor}.
49The simplest design has a single global queue of actors accessed by the executor threads, but this approach results in high contention as both ends of the queue by the executor threads.
50The more common design is to \Newterm{shard} the single queue among the executor threads, where actors are permanently assigned or can float among the queues.
51Sharding significantly decreases contention among executor threads adding and removing actors to/from a queue.
52Finally, each actor has a receive queue of messages (mailbox), which is a single consumer, multi-producer queue, \ie only the actor removes from the mailbox but multiple actors can attach messages.
53When an actor receives a message in its mailbox, the actor is marked ready and scheduled by a thread to run the actor's current work unit on the message(s).
54
55% cite parallel theatre and our paper
56Figure \ref{f:inverted_actor} shows an actor system designed as \Newterm{message-centric}, where a set of messages are scheduled and run on underlying executor threads~\cite{uC++,Nigro21}.
57Again, the simplest design has a single global queue of messages accessed by the executor threads, but this approach has the same contention problem by the executor threads.
58Therefore, the messages (mailboxes) are sharded and executor threads schedule each message, which points to its corresponding actor.
59Here, an actor's messages are permanently assigned to one queue to ensure FIFO receiving and/or reduce searching for specific actor/messages.
60Since multiple actors belong to each message queue, actor messages are interleaved on a queue.
61This design is \Newterm{inverted} because actors belong to a message queue, whereas in the classic approach a message queue belongs to each actor.
62% In this inverted actor system instead of each executor threads owning a queue of actors, they each own a queue of messages.
63% In this scheme work is consumed from their queue and executed by underlying threads.
64The inverted model can be taken a step further by sharding the message queues for each executor threads, so each executor thread owns a set of queues and cycles through them.
65Again, this extra level of sharding is to reduce queue contention.
66% The arrows from the message queues to the actors in the diagram indicate interleaved messages addressed to each actor.
67
68The actor system in \CFA uses a message-centric design, adopts several features from my prior actor work in \uC~\cite{}, and adds the following contributions related to \CFA:
69\begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt]
70\item
71Provide insight into the impact of envelope allocation in actor systems.
72In all actor systems, dynamic allocation is needed to ensure the lifetime of a unit of work persists from its creation until the unit of work is executed.
73This allocation is often called an \Newterm{envelope} as it ``packages'' the information needed to run the unit of work, alongside any other information needed to send the unit of work, such as an actor's address or link fields.
74This dynamic allocation occurs once per message sent.
75Unfortunately, the high rate of message sends in an actor system results in significant contention on the memory allocator.
76A novel data structure is introduced to consolidate allocations to improve performance by minimizing allocator contention.
77
78\item
79Improve performance of the inverted actor system using multiple approaches to minimize contention on queues, such as queue gulping and avoiding atomic operations.
80
81\item
82Introduce work stealing in the inverted actor system.
83Work stealing in an actor-centric system involves stealing one or more actors among executor threads.
84In the inverted system, the notion of stealing message queues is introduced.
85The queue stealing is implemented such that the act of stealing work does not contend with non-stealing executor threads running actors.
86
87\item
88Introduce and evaluate a timestamp-based work-stealing heuristic with the goal of maintaining non-workstealing performance in work-saturated workloads and improving performance on unbalanced workloads.
89
90\item
91Provide a suite of safety and productivity features including static-typing, detection of erroneous message sends, statistics tracking, and more.
92\end{enumerate}
93
94\section{\CFA Actor}\label{s:CFAActor}
95\CFA is not an object oriented language and it does not have \gls{rtti}.
96As such, all message sends and receives among actors can only occur using static type-matching, as in Typed-Akka~\cite{AkkaTyped}.
97Figure~\ref{f:BehaviourStyles} contrasts dynamic and static type-matching.
98Figure~\ref{l:dynamic_style} shows the dynamic style with a heterogeneous message receive and an indirect dynamic type-discrimination for message processing.
99Figure~\ref{l:static_style} shows the static style with a homogeneous message receive and a direct static type-discrimination for message processing.
100The static-typing style is safer because of the static check and faster because there is no dynamic type-discrimination.
101The dynamic-typing style is more flexible because multiple kinds of messages can be handled in a behaviour condensing the processing code.
102
103\begin{figure}
104\centering
105
106\begin{lrbox}{\myboxA}
107\begin{cfa}[morekeywords=case]
108allocation receive( message & msg ) {
109        case( @msg_type1@, msg ) {      // discriminate type
110                ... msg_d-> ...;        // msg_type1 msg_d
111        } else case( @msg_type2@, msg ) {
112                ... msg_d-> ...;        // msg_type2 msg_d
113        ...
114}
115\end{cfa}
116\end{lrbox}
117
118\begin{lrbox}{\myboxB}
119\begin{cfa}
120allocation receive( @msg_type1@ & msg ) {
121        ... msg ...;
122}
123allocation receive( @msg_type2@ & msg ) {
124        ... msg ...;
125}
126...
127\end{cfa}
128\end{lrbox}
129\subfloat[dynamic typing]{\label{l:dynamic_style}\usebox\myboxA}
130\hspace*{10pt}
131\vrule
132\hspace*{10pt}
133\subfloat[static typing]{\label{l:static_style}\usebox\myboxB}
134\caption{Behaviour Styles}
135\label{f:BehaviourStyles}
136\end{figure}
137
138\begin{figure}
139\centering
140
141\begin{cfa}
142// actor
143struct my_actor {
144        @inline actor;@                                                 $\C[3.25in]{// Plan-9 C inheritance}$
145};
146// messages
147struct str_msg {
148        char str[12];
149        @inline message;@                                               $\C{// Plan-9 C inheritance}$
150};
151void ?{}( str_msg & this, char * str ) { strcpy( this.str, str ); }  $\C{// constructor}$
152struct int_msg {
153        int i;
154        @inline message;@                                               $\C{// Plan-9 C inheritance}$
155};
156// behaviours
157allocation receive( my_actor &, @str_msg & msg@ ) with(msg) {
158        sout | "string message \"" | str | "\"";
159        return Nodelete;                                                $\C{// actor not finished}$
160}
161allocation receive( my_actor &, @int_msg & msg@ ) with(msg) {
162        sout | "integer message" | i;
163        return Nodelete;                                                $\C{// actor not finished}$
164}
165int main() {
166        str_msg str_msg{ "Hello World" };               $\C{// constructor call}$
167        int_msg int_msg{ 42 };                                  $\C{// constructor call}$
168        start_actor_system();                                   $\C{// sets up executor}$
169        my_actor actor;                                                 $\C{// default constructor call}$
170        @actor | str_msg | int_msg;@                    $\C{// cascade sends}$
171        @actor | int_msg;@                                              $\C{// send}$
172        @actor | finished_msg;@                                 $\C{// send => terminate actor (deallocation deferred)}$
173        stop_actor_system();                                    $\C{// waits until actors finish}\CRT$
174} // deallocate int_msg, str_msg, actor
175\end{cfa}
176\caption{\CFA Actor Syntax}
177\label{f:CFAActor}
178\end{figure}
179
180Figure~\ref{f:CFAActor} shows a complete \CFA actor example starting with the actor type @my_actor@ created by defining a @struct@ that inherits from the base @actor@ @struct@ via the @inline@ keyword.
181This inheritance style is the Plan-9 C-style inheritance discussed in Section~\ref{s:Inheritance}.
182Similarly, the message types @str_msg@ and @int_msg@ are created by defining a @struct@ that inherits from the base @message@ @struct@ via the @inline@ keyword.
183Only @str_msg@ needs a constructor to copy the C string;
184@int_msg@ is initialized using its \CFA auto-generated constructors.
185There are two matching @receive@ (behaviour) routines that process the corresponding typed messages.
186Both @receive@ routines use a @with@ clause so message fields are not qualified and return @Nodelete@ indicating the actor is not finished.
187Also, all messages are marked with @Nodelete@ as their default allocation state.
188The program main begins by creating two messages on the stack.
189Then the executor system is started by calling @start_actor_system@.
190Now an actor is created on the stack and four messages are sent it using operator @?|?@.
191The last message is the builtin @finish_msg@, which returns @Finished@ to an executor thread, causing it to removes the actor from the actor system \see{Section~\ref{s:ActorBehaviours}}.
192The call to @stop_actor_system@ blocks the program main until all actors are finished and removed from the actor system.
193The program main ends by deleting the actor and two messages from the stack.
194The output for the program is:
195\begin{cfa}
196string message "Hello World"
197integer message 42
198integer message 42
199\end{cfa}
200
201\subsection{Actor Behaviours}\label{s:ActorBehaviours}
202In general, a behaviour for some derived actor and derived message type is defined with following signature:
203\begin{cfa}
204allocation receive( my_actor & receiver, my_msg & msg )
205\end{cfa}
206where @my_actor@ and @my_msg@ inherit from types @actor@ and @message@, respectively.
207The return value of @receive@ must be a value from enumerated type, @allocation@:
208\begin{cfa}
209enum allocation { Nodelete, Delete, Destroy, Finished };
210\end{cfa}
211The values represent a set of actions that dictate what the executor does with an actor or message after a given behaviour returns.
212For actors, the @receive@ routine returns the @allocation@ status to the executor, which takes the appropriate action.
213For messages, either the default allocation, @Nodelete@, or any changed value in the message is examined by the executor, which takes the appropriate action.
214Message state is updated via a call to:
215\begin{cfa}
216void set_allocation( message & this, allocation state )
217\end{cfa}
218
219In detail, the actions taken by an executor for each of the @allocation@ values are:
220
221\noindent@Nodelete@
222tells the executor that no action is to be taken with regard to an actor or message.
223This status is used when an actor continues receiving messages or a message may be reused.
224
225\noindent@Delete@
226tells the executor to call the object's destructor and deallocate (delete) the object.
227This status is used with dynamically allocated actors and messages when they are not reused.
228
229\noindent@Destroy@
230tells the executor to call the object's destructor, but not deallocate the object.
231This status is used with dynamically allocated actors and messages whose storage is reused.
232
233\noindent@Finished@
234tells the executor to mark the respective actor as finished executing, but not call the object's destructor nor deallocate the object.
235This status is used when actors or messages are global or stack allocated, or a programmer wants to manage deallocation themselves.
236
237For the actor system to terminate, all actors must have returned a status other than @Nodelete@.
238After an actor is terminated, it is erroneous to send messages to it.
239Similarly,  after a message is terminated, it cannot be sent to an actor.
240Note, it is safe to construct an actor or message with a status other than @Nodelete@, since the executor only examines the allocation action after a behaviour returns.
241
242\subsection{Actor Envelopes}\label{s:envelope}
243As stated, each message, regardless of where it is allocated, can be sent to an arbitrary number of actors, and hence, appear on an arbitrary number of message queues.
244Because a C program manages message lifetime, messages cannot be copied for each send, otherwise who manages the copies.
245Therefore, it up to the actor program to manage message life-time across receives.
246However, for a message to appear on multiple message queues, it needs an arbitrary number of associated destination behaviours.
247Hence, there is the concept of an envelop, which is dynamically allocated on each send, that wraps a message with any extra implementation fields needed to persist between send and receive.
248Managing the envelop is straightforward because it is created at the send and deleted after the receive, \ie there is 1:1 relationship for an envelop and a many to one relationship for a message.
249
250% In actor systems, messages are sent and received by actors.
251% When a actor receives a message it executes its behaviour that is associated with that message type.
252% However the unit of work that stores the message, the receiving actor's address, and other pertinent information needs to persist between send and the receive.
253% Furthermore the unit of work needs to be able to be stored in some fashion, usually in a queue, until it is executed by an actor.
254% All these requirements are fulfilled by a construct called an envelope.
255% The envelope wraps up the unit of work and also stores any information needed by data structures such as link fields.
256
257% One may ask, "Could the link fields and other information be stored in the message?".
258% This is a good question to ask since messages also need to have a lifetime that persists beyond the work it delivers.
259% However, if one were to use messages as envelopes then a message would not be able to be sent to multiple actors at a time.
260% Therefore this approach would just push the allocation into another location, and require the user to dynamically allocate a message for every send, or require careful ordering to allow for message reuse.
261
262\subsection{Actor System}\label{s:ActorSystem}
263The calls to @start_actor_system@, and @stop_actor_system@ mark the start and end of a \CFA actor system.
264The call to @start_actor_system@ sets up an executor and executor threads for the actor system.
265It is possible to have multiple start/stop scenarios in a program.
266
267@start_actor_system@ has three overloaded signatures that vary the executor's configuration:
268
269\noindent@void start_actor_system()@
270configures the executor to implicitly use all preallocated kernel-threads (processors), \ie the processors created by the program main prior to starting the actor system.
271When the number of processors is greater than 1, each executor's message queue is sharded by a factor of 16 to reduce contention, \ie for 4 executor threads (processors), there is a total of 4 $\times$ 16 message queues evenly distributed across the executor threads.
272
273\noindent@void start_actor_system( size_t num_thds )@
274configures the number of executor threads to @num_thds@, with the same message queue sharding.
275
276\noindent@void start_actor_system( executor & this )@
277allows the programmer to explicitly create and configure an executor for use by the actor system.
278Executor configuration options include are discussed in Section~\ref{s:executor}.
279
280\noindent
281All actors must be created \emph{after} calling @start_actor_system@ so the executor can keep track of the number of actors that have entered the system but not yet terminated.
282
283\subsection{Actor Send}\label{s:ActorSend}
284All message sends are done using the vertical-bar (bit-or) operator, @?|?@, similar to the syntax of the \CFA stream I/O.
285Hence, programmers must write a matching @?|?@ routine for each @receive@ routine, which is awkward and generates a maintenance problem That must be solved.
286The currently supported approach to creating a generic @?|?@ routine requires users to create specific routines for their actor and message types that access the base type.
287Since these routines are not complex, they can be generated using macros that the user can add following their message and actor types.
288This works, but is not much better than asking users to write the @?|?@ routine themselves.
289
290As stated, \CFA does not have named inheritance with RTTI.
291\CFA does have a preliminary form of virtual routines, but it is not mature enough for use in this work.
292Virtuals would provide a clean mechanism to write a single generic @?|?@ routine taking a base actor and message type, and then dynamically selecting the @receive@ routine from the actor argument.
293Note, virtuals are not needed for the send; Plan-9 inheritance is sufficient because only the inherited fields are needed during the message send (only upcasting is needed).
294
295Therefore, a template-like approach was chosen, where the compiler generates a matching @?|?@ routine for each @receive@ routine it finds with the correct actor/message type-signature.
296This approach requires no annotation or additional code to be written by users, thus it resolves the maintenance problem.
297(When the \CFA virtual routines mature, it should be possible to seamlessly transition to it from the template approach.)
298
299Figure~\ref{f:send_gen} shows the generated send routine for the @int_msg@ receive in Figure~\ref{f:CFAActor}.
300Operator @?|?@ has the same parameter signature as the corresponding @receive@ routine and returns an @actor@ so the operator can be cascaded.
301The routine sets @rec_fn@ to the matching @receive@ routine using the left-hand type to perform the selection.
302Then the routine packages the base and derived actor and message and actor, along with the receive routine into an \hyperref[s:envelope]{envelope}.
303Finally, the envelop is added to the executor queue designated by the actor using the executor routine @send@.
304
305\begin{figure}
306\begin{cfa}
307$\LstCommentStyle{// from Figure~\ref{f:CFAActor}}$
308struct my_actor { inline actor; };                                              $\C[3.75in]{// actor}$
309struct int_msg { inline message; int i; };                              $\C{// message}$
310allocation receive( @my_actor &, int_msg & msg@ ) {...} $\C{// receiver}$
311
312// compiler generated send operator
313typedef allocation (*receive_t)( actor &, message & );
314actor & ?|?( @my_actor & receiver, int_msg & msg@ ) {
315        allocation (*rec_fn)( my_actor &, int_msg & ) = @receive@; // deduce receive routine
316        request req{ &receiver, (actor *)&receiver, &msg, (message *)&msg, (receive_t)rec_fn };
317        send( receiver, req );                                                          $\C{// queue message for execution}\CRT$
318        return receiver;
319}
320\end{cfa}
321\caption{Generated Send Operator}
322\label{f:send_gen}
323\end{figure}
324
325\subsection{Actor Termination}\label{s:ActorTerm}
326As discussed in Section~\ref{s:ActorSend}, during a message send, the derived type of the actor and message is erased, and then recovered later by calling the receive routine.
327After the receive routine is done, the executor must clean up the actor and message according to their allocation status.
328If the allocation status is @Delete@ or @Destroy@, the appropriate destructor must be called by the executor.
329This poses a problem; the type of the actor or message is not available to the executor, but it needs to call the right destructor!
330This requires down-casting from the base type to derived type, which requires a virtual system.
331Thus, a rudimentary destructor-only virtual system was added to \CFA as part of this work.
332This virtual system is used via Plan-9 inheritance of the @virtual_dtor@ type.
333The @virtual_dtor@ type maintains a pointer to the start of the object, and a pointer to the correct destructor.
334When a type inherits the @virtual_dtor@ type, the compiler adds code to its destructor to make sure that whenever any destructor along inheritance tree is called, the destructor call is intercepted, and restarts at the appropriate destructor for that object.
335
336\begin{figure}
337\begin{cfa}
338struct base_type { inline virtual_dtor; };
339struct intermediate_type { inline base_type; };
340struct derived_type { inline intermediate_type; };
341
342int main() {
343    derived_type d1, d2, d3;
344    intermediate_type & i = d2;
345    base_type & b = d3;
346    ^d1{}; ^i{}; ^b{}; // all of these will call the destructors in the correct order
347}
348
349\end{cfa}
350\caption{\CFA Virtual Destructor}
351\label{f:VirtDtor}
352\end{figure}
353
354This virtual destructor system was built for this work, but is general and can be used in any type in \CFA.
355Actors and messages opt into this system by inheriting the @virtual_dtor@ type, which allows the executor to call the right destructor without knowing the derived actor or message type.
356
357Figure~\ref{f:ConvenienceMessages} shows three builtin convenience messages and receive routines used to terminate actors, depending on how an actor is allocated: @Delete@, @Destroy@ or @Finished@.
358For example, in Figure~\ref{f:CFAActor}, the builtin @finished_msg@ message and receive are used to terminate the actor because the actor is allocated on the stack, so no deallocation actions are performed by the executor.
359
360\begin{figure}
361\begin{cfa}
362message __base_msg_finished $@$= { .allocation_ : Finished }; // no auto-gen constructors
363struct __delete_msg_t { inline message; } delete_msg = __base_msg_finished;
364struct __destroy_msg_t { inline message; } destroy_msg = __base_msg_finished;
365struct __finished_msg_t { inline message; } finished_msg = __base_msg_finished;
366
367allocation receive( actor & this, __delete_msg_t & msg ) { return Delete; }
368allocation receive( actor & this, __destroy_msg_t & msg ) { return Destroy; }
369allocation receive( actor & this, __finished_msg_t & msg ) { return Finished; }
370\end{cfa}
371\caption{Builtin Convenience Messages}
372\label{f:ConvenienceMessages}
373\end{figure}
374
375\section{\CFA Executor}\label{s:executor}
376This section describes the basic architecture of the \CFA executor.
377An executor of an actor system is the scheduler that organizes where actor behaviours are run and how messages are sent and delivered.
378In \CFA, the executor is message-centric \see{Figure~\ref{f:inverted_actor}}, but extended by over sharding of a message queue \see{left side of Figure~\ref{f:gulp}}, \ie there are $M$ message queues where $M$ is greater than the number of executor threads $N$ (usually a multiple of $N$).
379This approach reduces contention by spreading message delivery among the $M$ queues rather than $N$, while still maintaining actor FIFO message-delivery semantics.
380The only extra overhead is each executor cycling (usually round-robin) through its $M$/$N$ queues.
381The goal is to achieve better performance and scalability for certain kinds of actor applications by reducing executor locking.
382Note, lock-free queues do not help because busy waiting on any atomic instruction is the source of the slowdown whether it is a lock or lock-free.
383
384\begin{figure}
385\begin{center}
386\input{diagrams/gulp.tikz}
387\end{center}
388\caption{Queue Gulping Mechanism}
389\label{f:gulp}
390\end{figure}
391
392Each executor thread iterates over its own message queues until it finds one with messages.
393At this point, the executor thread atomically \gls{gulp}s the queue, meaning it moves the contents of message queue to a local queue of the executor thread using a single atomic instruction.
394An example of the queue gulping operation is shown in the right side of Figure \ref{f:gulp}, where a executor threads gulps queue 0 and begins to process it locally.
395This step allows an executor thread to process the local queue without any atomics until the next gulp.
396Other executor threads can continue adding to the ends of executor thread's message queues.
397In detail, an executor thread performs a test-and-gulp, non-atomically checking if a queue is non-empty, before attempting to gulp it.
398If an executor misses an non-empty queue due to a race, it eventually finds the queue after cycling through its message queues.
399This approach minimizes costly lock acquisitions.
400
401Processing a local queue involves: removing a unit of work from the queue, dereferencing the actor pointed-to by the work-unit, running the actor's behaviour on the work-unit message, examining the returned allocation status from the @receive@ routine for the actor and internal status in the delivered message, and taking the appropriate actions.
402Since all messages to a given actor are in the same queue, this guarantees atomicity across behaviours of that actor since it can only execute on one thread at a time.
403As each actor is created or terminated by an executor thread, it increments/decrements a global counter.
404When an executor decrements the counter to zero, it sets a global boolean variable that is checked by each executor thread when it has no work.
405Once a executor threads sees the flag is set it stops running.
406After all executors stop, the actor system shutdown is complete.
407
408\subsection{Copy Queue}\label{s:copyQueue}
409Unfortunately, the frequent allocation of envelopes for each send results in heavy contention on the memory allocator.
410This contention is reduced using a novel data structure, called a \Newterm{copy queue}.
411The copy queue is a thin layer over a dynamically sized array that is designed with the envelope use case in mind.
412A copy queue supports the typical queue operations of push/pop but in a different way from a typical array-based queue.
413
414The copy queue is designed to take advantage of the \gls{gulp}ing pattern, giving an amortized runtime cost for each push/pop operation of $O(1)$.
415In contrast, a na\"ive array-based queue often has either push or pop cost $O(n)$ and the other cost $O(1)$ since one of the operations requires shifting the elements of the queue.
416Since the executor threads gulp a queue to operate on it locally, this creates a usage pattern where all elements are popped from the copy queue without any interleaved pushes.
417As such, during pop operations there is no need to shift array elements.
418Instead, an index is stored in the copy-queue data-structure that keeps track of which element to pop next allowing pop to be $O(1)$.
419Push operations are amortized $O(1)$ since pushes may cause doubling reallocations of the underlying dynamic-sized array (like \CC @vector@).
420
421% C_TODO: maybe make copy_queue diagram
422
423Since the copy queue is an array, envelopes are allocated first on the stack and then copied into the copy queue to persist until they are no longer needed.
424For many workload, the copy queues grow in size to facilitate the average number of messages in flight and there is no further dynamic allocations.
425One downside of this approach that more storage is allocated than needed, \ie each copy queue is only partially full.
426Comparatively, the individual envelope allocations of a list-based queue mean that the actor system always uses the minimum amount of heap space and cleans up eagerly.
427Additionally, bursty workloads can cause the copy queues to allocate a large amounts of space to accommodate the peaks of the throughput, even if most of that storage is not needed for the rest of the workload's execution.
428
429To mitigate memory wastage, a reclamation scheme is introduced.
430Initially, the memory reclamation na\"ively reclaims one index of the array per \gls{gulp}, if the array size is above a low fixed threshold.
431However, this approach has a problem.
432The high memory watermark nearly doubled!
433The issue is highlighted with an example.
434Assume a fixed throughput workload, where a queue never has more than 19 messages at a time.
435If the copy queue starts with a size of 10, it ends up doubling at some point to size 20 to accommodate 19 messages.
436However, after 2 gulps and subsequent reclamations the array size is 18.
437The next time 19 messages are enqueued, the array size is doubled to 36!
438To avoid this issue, a second check is added.
439Reclamation only occurs if less than half of the array is utilized.
440This check achieves a lower total storage and overall memory utilization compared to the non-reclamation copy queues.
441However, the use of copy queues still incurs a higher memory cost than list-based queueing, but the increase in memory usage is reasonable considering the performance gains \see{Section~\ref{s:actor_perf}}.
442
443\section{Work Stealing}\label{s:steal}
444Work stealing is a scheduling strategy to provide \Newterm{load balance}.
445The goal is to increase resource utilization by having idle threads steal work from working threads.
446While there are multiple parts in work-stealing scheduler, the two important components are victim selection and the stealing mechanism.
447
448\subsection{Stealing Mechanism}
449In work stealing, the stealing worker is called the \Newterm{thief} and the stolen-from worker is called the \Newterm{victim}.
450The stealing mechanism presented here differs from existing work-stealing actor-systems because of the message-centric (inverted) actor-system.
451Other actor systems, such as Akka~\cite{Akka} and CAF~\cite{CAF}, have work stealing, but use an actor-centric system where stealing is dequeuing from a non-empty ready-queue to an empty ready-queue.
452As an example, in CAF, the sharded actor queue is a set of double-ended queues (dequeues).
453When an actor has messages, it is inserted into a worker's dequeue (ready queue).
454Workers then consume actors from the dequeue and execute their behaviours.
455To steal work, thieves take one or more actors from a victim's dequeue.
456By the pigeon hole principle, there are three dequeue operations (push/victim pop/thief pop) that can occur concurrently and only two ends to a dequeue, so work stealing in a dequeue-based system always results in a potential increase in contention on the dequeues.
457This contention can slows down the victim's throughput.
458Note, which end of the dequeue is used for stealing, consuming, and inserting is not discussed since the largest cost is the mutual exclusion and its duration for safely performing the queue operations.
459
460Work steal now becomes queue stealing, where an entire actor/message queue is stolen, which trivially preserves message ordering in a queue \see{Section~\ref{s:steal}}.
461
462% C_TODO: maybe insert stealing diagram
463
464In \CFA, the actor work-stealing implementation is unique because of the message-centric system.
465In this system, it is impractical to steal actors because an actor's messages are distributed in temporal order along the message queue.
466To ensure sequential actor execution and FIFO message delivery, actor stealing requires finding and removing all of an actor's messages, and inserting them consecutively in another message queue.
467This operation is $O(N)$ with a non-trivial constant.
468The only way for work stealing to become practical is to shard the message queue, which also reduces contention, and steal queues to eliminate queue searching.
469
470Given queue stealing, the goal is to have a zero-victim-cost stealing mechanism, which does not mean stealing has no cost.
471It means work stealing does not affect the performance of the victim worker.
472The implication is that thieves cannot contend with a victim, and that a victim should perform no stealing related work unless it becomes a thief.
473In theory, this goal is not achievable, but results show the goal is achieved in practice.
474
475In \CFA's actor system, workers own a set of sharded queues, which they iterate over and gulp.
476If a worker has iterated over its message queues twice without finding any work, it tries to steal a queue from another worker.
477Stealing a queue is done wait-free with a few atomic instructions that can only create contention with other stealing workers, not the victim.
478To steal a queue, a worker does the following:
479\begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt]
480\item
481The thief chooses a victim, which is trivial because all workers are stored in a shared array.
482
483\item
484The thief starts at a random index in the array of the victim's queues and searches for a candidate queue.
485A candidate queue is any non-empty queue not being processed by the victim and not being stolen by another thief.
486These rules are not strictly enforced.
487A candidate is identified non-atomically, and as such, queues that do not satisfy these rules may be stolen.
488However, steals not meeting the rules do not affect correctness and do not constitute failed steals as the queue is always swapped.
489
490\item
491Once a candidate queue is chosen, the thief attempts a wait-free swap of a victim's queue to a random empty thief queue.
492If the swap successes, the steal is completed.
493If the swap fails, the victim may have been gulping that message queue or another thief must have attempted to steal the victim's queue.
494In either case, that message queue is highly likely to be empty.
495
496\item
497Once a thief fails or succeeds in stealing a queue, it iterates over its messages queues again because new messages may have arrived during stealing.
498Stealing is only repeated after two consecutive iterations over its owned queues without finding work.
499\end{enumerate}
500
501The key to the stealing mechanism is that the queues can still be operated on while they are being swapped.
502This functionality eliminates any contention among thieves and victims.
503
504The first key to this is that actors and workers maintain two distinct arrays of references to queues.
505Actors will always receive messages via the same queues.
506Workers, on the other hand will swap the pointers to queues in their shared array and operate on queues in the range of that array that they own.
507Swapping queues is a matter of atomically swapping two pointers in the worker array.
508As such pushes to the queues can happen concurrently during the swap since pushes happen via the actor queue references.
509
510Gulping can also occur during queue swapping, but the implementation requires more nuance than the pushes.
511When a worker is not stealing it iterates across its own range of queues and gulps them one by one.
512When a worker operates on a queue it first copies the current pointer from the worker array of references to a local variable.
513It then uses that local variable for all queue operations until it moves to the next index of its range of the queue array.
514This ensures that any swaps do not interrupt gulping operations, however this introduces a correctness issue.
515If any behaviours from a queue are run by two workers at a time it violates both mutual exclusion and the actor ordering guarantees.
516As such this must be avoided.
517To avoid this each queue has a @being_processed@ flag that is atomically set to @true@ when a queue is gulped.
518The flag indicates that a queue is being processed locally and is set back to @false@ once the local processing is finished.
519If a worker attempts to gulp a queue and finds that the @being_processed@ flag is @true@, it does not gulp the queue and moves on to the next queue in its range.
520This is a source of contention between victims and thieves since a thief may steal a queue and set @being_processed@ to @true@ between a victim saving a pointer to a queue and gulping it.
521However, the window for this race is very small, making this contention rare.
522This is why the claim is made that this mechanism is zero-victim-cost in practice but not in theory.
523By collecting statistics on failed gulps due to the @being_processed@ flag, it is found that this contention occurs ~0.05\% of the time when a gulp occurs.
524Hence, the claim is made that this stealing mechanism has zero-victim-cost in practice.
525
526
527\subsection{Queue Swap Correctness}
528Given the wait-free swap used is novel, it is important to show that it is correct.
529Firstly, it is clear to show that the swap is wait-free since all workers will fail or succeed in swapping the queues in a finite number of steps since there are no locks or looping.
530There is no retry mechanism in the case of a failed swap, since a failed swap either means the work was already stolen, or that work was stolen from the thief.
531In both cases it is apropos for a thief to given up on stealing.
532\CFA-style pseudocode for the queue swap is presented below.
533The swap uses compare-and-swap (@CAS@) which is just pseudocode for C's @__atomic_compare_exchange_n@.
534A pseudocode implementation of @CAS@ is also shown below.
535The correctness of the wait-free swap will now be discussed in detail.
536To first verify sequential correctness, consider the equivalent sequential swap below:
537
538\begin{cfa}
539void swap( uint victim_idx, uint my_idx ) {
540        // Step 0:
541        work_queue * my_queue = request_queues[my_idx];
542        work_queue * vic_queue = request_queues[victim_idx];
543        // Step 2:
544        request_queues[my_idx] = 0p;
545        // Step 3:
546        request_queues[victim_idx] = my_queue;
547        // Step 4:
548        request_queues[my_idx] = vic_queue;
549}
550\end{cfa}
551
552Step 1 is missing in the sequential example since in only matter in the concurrent context presented later.
553By looking at the sequential swap it is easy to see that it is correct.
554Temporary copies of each pointer being swapped are stored, and then the original values of each pointer are set using the copy of the other pointer.
555
556\begin{cfa}
557// This routine is atomic
558bool CAS( work_queue ** ptr, work_queue ** old, work_queue * new ) {
559        if ( *ptr != *old )
560                return false;
561        *ptr = new;
562        return true;
563}
564
565bool try_swap_queues( worker & this, uint victim_idx, uint my_idx ) with(this) {
566        // Step 0:
567        // request_queues is the shared array of all sharded queues
568        work_queue * my_queue = request_queues[my_idx];
569        work_queue * vic_queue = request_queues[victim_idx];
570
571        // Step 1:
572        // If either queue is 0p then they are in the process of being stolen
573        // 0p is Cforall's equivalent of C++'s nullptr
574        if ( vic_queue == 0p ) return false;
575
576        // Step 2:
577        // Try to set thief's queue ptr to be 0p.
578        // If this CAS fails someone stole thief's queue so return false
579        if ( !CAS( &request_queues[my_idx], &my_queue, 0p ) )
580                return false;
581
582        // Step 3:
583        // Try to set victim queue ptr to be thief's queue ptr.
584        // If it fails someone stole the other queue, so fix up then return false
585        if ( !CAS( &request_queues[victim_idx], &vic_queue, my_queue ) ) {
586                request_queues[my_idx] = my_queue; // reset queue ptr back to prev val
587                return false;
588        }
589
590        // Step 4:
591        // Successfully swapped.
592        // Thief's ptr is 0p so no one will touch it
593        // Write back without CAS is safe
594        request_queues[my_idx] = vic_queue;
595        return true;
596}
597\end{cfa}\label{c:swap}
598
599Now consider the concurrent implementation of the swap.
600\begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt]
601\item
602Step 0 is the same as the sequential example, and the thief stores local copies of the two pointers to be swapped.
603\item
604Step 1 verifies that the stored copy of the victim queue pointer, @vic_queue@, is valid.
605If @vic_queue@ is equal to @0p@, then the victim queue is part of another swap so the operation fails.
606No state has changed at this point so no fixups are needed.
607Note, @my_queue@ can never be equal to @0p@ at this point since thieves only set their own queues pointers to @0p@ when stealing.
608At no other point will a queue pointer be set to @0p@.
609Since each worker owns a disjoint range of the queue array, it is impossible for @my_queue@ to be @0p@.
610\item
611Step 2 attempts to set the thief's queue pointer to @0p@ via @CAS@.
612The @CAS@ will only fail if the thief's queue pointer is no longer equal to @my_queue@, which implies that this thief has become a victim and its queue has been stolen.
613At this point the thief-turned-victim will fail and since it has not changed any state it just fails and returns false.
614If the @CAS@ succeeds then the thief's queue pointer will now be @0p@.
615Nulling the pointer is safe since only thieves look at other worker's queue ranges, and whenever thieves need to dereference a queue pointer they check for @0p@.
616\item
617Step 3 attempts to set the victim's queue pointer to be @my_queue@ via @CAS@.
618If the @CAS@ succeeds then the victim's queue pointer has been set and swap can no longer fail.
619If the @CAS@ fails then the thief's queue pointer must be restored to its previous value before returning.
620\item
621Step 4 sets the thief's queue pointer to be @vic_queue@ completing the swap.
622\end{enumerate}
623
624\begin{theorem}
625The presented swap is correct and concurrently safe in both the success and failure cases.
626\end{theorem}
627
628Correctness of the swap is shown through the existence of an invariant.
629The invariant is that when a queue pointer is set to @0p@ by a thief, then the next write to the pointer can only be performed by the same thief.
630To show that this invariant holds, it is shown that it is true at each step of the swap.
631Step 0 and 1 do not write and as such they cannot invalidate the invariant of any other thieves.
632In step 2 a thief attempts to write @0p@ to one of their queue pointers.
633This queue pointer cannot be @0p@.
634As stated above, @my_queue@ is never equal to @0p@ since thieves will only write @0p@ to queue pointers from their own queue range and all worker's queue ranges are disjoint.
635As such step 2 upholds the invariant since in a failure case no write occurs, and in the success case, the value of the queue pointer is guaranteed to not be 0p.
636In step 3 the thief attempts to write @my_queue@ to the victim's queue pointer.
637If the current value of the victim's queue pointer is @0p@, then the CAS will fail since @vic_queue@ cannot be equal to @0p@ because of the check in step 1.
638Therefore in the success case where the @CAS@ succeeds, the value of the victim's queue pointer must not be @0p@.
639As such, the write will never overwrite a value of @0p@, hence the invariant is held in the @CAS@ of step 3.
640The write back to the thief's queue pointer that happens in the failure case of step three and in step 4 hold the invariant since they are the subsequent write to a @0p@ queue pointer and they are being set by the same thief that set the pointer to @0p@.
641
642Given this informal proof of invariance it can be shown that the successful swap is correct.
643Once a thief atomically sets their queue pointer to be @0p@ in step 2, the invariant guarantees that pointer will not change.
644As such, in the success case step 3 it is known that the value of the victim's queue pointer that was overwritten must be @vic_queue@ due to the use of @CAS@.
645Given that pointers all have unique memory locations, this first write of the successful swap is correct since it can only occur when the pointer has not changed.
646By the invariant the write back in the successful case is correct since no other worker can write to the @0p@ pointer.
647
648In the failed case the outcome is correct in steps 1 and 2 since no writes have occurred so the program state is unchanged.
649In the failed case of step 3 the program state is safely restored to its state it had prior to the @0p@ write in step 2, thanks to the invariant that makes the write back to the @0p@ pointer safe.
650
651\subsection{Stealing Guarantees}
652Given that the stealing operation can potentially fail, it is important to discuss the guarantees provided by the stealing implementation.
653Given a set of $N$ swaps a set of connected directed graphs can be constructed where each vertex is a queue and each edge is a swap directed from a thief queue to a victim queue.
654Since each thief can only steal from one victim at a time, each vertex can only have at most one outgoing edge.
655A corollary that can be drawn from this, is that there are at most $V$ edges in this constructed set of connected directed graphs, where $V$ is the total number of vertices.
656
657\begin{figure}
658\begin{center}
659\input{diagrams/M_to_one_swap.tikz}
660\end{center}
661\caption{Graph of $M$ thieves swapping with one victim.}
662\label{f:M_one_swap}
663\end{figure}
664
665\begin{theorem}
666Given $M$ thieves queues all attempting to swap with one victim queue, and no other swaps occurring that involve these queues, at least one swap is guaranteed to succeed.
667\end{theorem}\label{t:one_vic}
668A graph of the $M$ thieves swapping with one victim discussed in this theorem is presented in Figure~\ref{f:M_one_swap}.
669\\
670First it is important to state that a thief will not attempt to steal from themselves.
671As such, the victim here is not also a thief.
672Stepping through the code in \ref{c:swap}, for all thieves steps 0-1 succeed since the victim is not stealing and will have no queue pointers set to be @0p@.
673Similarly for all thieves step 2 will succeed since no one is stealing from any of the thieves.
674In step 3 the first thief to @CAS@ will win the race and successfully swap the queue pointer.
675Since it is the first one to @CAS@ and @CAS@ is atomic, there is no way for the @CAS@ to fail since no other thief could have written to the victim's queue pointer and the victim did not write to the pointer since they aren't stealing.
676Hence at least one swap is guaranteed to succeed in this case.
677
678\begin{figure}
679\begin{center}
680\input{diagrams/chain_swap.tikz}
681\end{center}
682\caption{Graph of a chain of swaps.}
683\label{f:chain_swap}
684\end{figure}
685
686\begin{theorem}
687Given $M$ > 1, ordered queues pointers all attempting to swap with the queue in front of them in the ordering, except the first queue, and no other swaps occurring that involve these queues, at least one swap is guaranteed to succeed.
688\end{theorem}\label{t:vic_chain}
689A graph of the chain of swaps discussed in this theorem is presented in Figure~\ref{f:chain_swap}.
690\\
691This is a proof by contradiction.
692Assume no swaps occur.
693Then all thieves must have failed at step 1, step 2 or step 3.
694For a given thief $b$ to fail at step 1, thief $b + 1$ must have succeeded at step 2 before $b$ executes step 0.
695Hence, not all thieves can fail at step 1.
696Furthermore if a thief $b$ fails at step 1 it logically splits the chain into two subchains $0 <- b$ and $b + 1 <- M - 1$, where $b$ has become solely a victim since its swap has failed and it did not modify any state.
697There must exist at least one chain containing two or more queues after since it is impossible for a split to occur both before and after a thief, since that requires failing at step 1 and succeeding at step 2.
698Hence, without loss of generality, whether thieves succeed or fail at step 1, this proof can proceed inductively.
699
700For a given thief $i$ to fail at step 2, it means that another thief $j$ had to have written to $i$'s queue pointer between $i$'s step 0 and step 2.
701The only way for $j$ to write to $i$'s queue pointer would be if $j$ was stealing from $i$ and had successfully finished step 3.
702If $j$ finished step 3 then the at least one swap was successful.
703Therefore all thieves did not fail at step 2.
704Hence all thieves must successfully complete step 2 and fail at step 3.
705However, since the first worker, thief $0$, is solely a victim and not a thief, it does not change the state of any of its queue pointers.
706Hence, in this case thief $1$ will always succeed in step 3 if all thieves succeed in step 2.
707Thus, by contradiction with the earlier assumption that no swaps occur, at least one swap must succeed.
708
709% \raisebox{.1\height}{}
710\begin{figure}
711\centering
712\begin{tabular}{l|l}
713\subfloat[Cyclic Swap Graph]{\label{f:cyclic_swap}\input{diagrams/cyclic_swap.tikz}} &
714\subfloat[Acyclic Swap Graph]{\label{f:acyclic_swap}\input{diagrams/acyclic_swap.tikz}}
715\end{tabular}
716\caption{Illustrations of cyclic and acyclic swap graphs.}
717\end{figure}
718
719\begin{theorem}
720Given a set of $M > 1$ swaps occurring that form a single directed connected graph.
721At least one swap is guaranteed to succeed if and only if the graph does not contain a cycle.
722\end{theorem}\label{t:vic_cycle}
723Representations of cyclic and acyclic swap graphs discussed in this theorem are presented in Figures~\ref{f:cyclic_swap} and \ref{f:acyclic_swap}.
724\\
725First the reverse direction is proven.
726If the graph does not contain a cycle, then there must be at least one successful swap.
727Since the graph contains no cycles and is finite in size, then there must be a vertex $A$ with no outgoing edges.
728The graph can then be formulated as a tree with $A$ at the top since each node only has at most one outgoing edge and there are no cycles.
729The forward direction is proven by contradiction in a similar fashion to \ref{t:vic_chain}.
730Assume no swaps occur.
731Similar to \ref{t:vic_chain}, this graph can be inductively split into subgraphs of the same type by failure at step 1, so the proof proceeds without loss of generality.
732Similar to \ref{t:vic_chain} the conclusion is drawn that all thieves must successfully complete step 2 for no swaps to occur, since for step 2 to fail, a different thief has to successfully complete step 3, which would imply a successful swap.
733Hence, the only way forward is to assume all thieves successfully complete step 2.
734Hence for there to be no swaps all thieves must fail step 3.
735However, since $A$ has no outgoing edges, since the graph is connected there must be some $K$ such that $K < M - 1$ thieves are attempting to swap with $A$.
736Since all $K$ thieves have passed step 2, similar to \ref{t:one_vic} the first one of the $K$ thieves to attempt step 3 is guaranteed to succeed.
737Thus, by contradiction with the earlier assumption that no swaps occur, if the graph does not contain a cycle, at least one swap must succeed.
738
739The forward direction is proven by contrapositive.
740If the graph contains a cycle then there exists a situation where no swaps occur.
741This situation is constructed.
742Since all vertices have at most one outgoing edge the cycle must be directed.
743Furthermore, since the graph contains a cycle all vertices in the graph must have exactly one outgoing edge.
744This is shown through construction of an arbitrary cyclic graph.
745The graph contains a directed cycle by definition, so the construction starts with $T$ vertices in a directed cycle.
746Since the graph is connected, and each vertex has at most one outgoing edge, none of the vertices in the cycle have available outgoing edges to accommodate new vertices with no outgoing edges.
747Any vertices added to the graph must have an outgoing edge to connect, leaving the resulting graph with no available outgoing edges.
748Thus, by induction all vertices in the graph must have exactly one outgoing edge.
749Hence all vertices are thief queues.
750Now consider the case where all thieves successfully complete step 0-1, and then they all complete step 2.
751At this point all thieves are attempting to swap with a queue pointer whose value has changed to @0p@.
752If all thieves attempt the @CAS@ before any write backs, then they will all fail.
753Thus, by contrapositive, if the graph contains a cycle then there exists a situation where no swaps occur.
754Hence, at least one swap is guaranteed to succeed if and only if the graph does not contain a cycle.
755
756% C_TODO: go through and use \paragraph to format to make it look nicer
757\subsection{Victim Selection}\label{s:victimSelect}
758In any work stealing algorithm thieves have some heuristic to determine which victim to choose from.
759Choosing this algorithm is difficult and can have implications on performance.
760There is no one selection heuristic that is known to be the best on all workloads.
761Recent work focuses on locality aware scheduling in actor systems\cite{barghi18}\cite{wolke17}.
762However, while locality aware scheduling provides good performance on some workloads, something as simple as randomized selection performs better on other workloads\cite{barghi18}.
763Since locality aware scheduling has been explored recently, this work introduces a heuristic called \textbf{longest victim} and compares it to randomized work stealing.
764The longest victim heuristic maintains a timestamp per executor threads that is updated every time a worker attempts to steal work.
765Thieves then attempt to steal from the thread with the oldest timestamp.
766This means that if two thieves look to steal at the same time, they likely will attempt to steal from the same victim.
767This does increase the chance at contention between thieves, however given that workers have multiple queues under them, often in the tens or hundreds of queues per worker it is rare for two queues to attempt so steal the same queue.
768Furthermore in the case they attempt to steal the same queue at least one of them is guaranteed to successfully steal the queue as shown in Theorem \ref{t:one_vic}.
769Additionally, the longest victim heuristic makes it very improbable that the no swap scenario presented in Theorem \ref{t:vic_cycle} manifests.
770Given the longest victim heuristic, for a cycle to manifest it would require all workers to attempt to steal in a short timeframe.
771This is the only way that more than one thief could choose another thief as a victim, since timestamps are only updated upon attempts to steal.
772In this case, the probability of lack of any successful swaps is a non issue, since it is likely that these steals were not important if all workers are trying to steal.
773
774\section{Safety and Productivity}\label{s:SafetyProductivity}
775\CFA's actor system comes with a suite of safety and productivity features.
776Most of these features are present in \CFA's debug mode, but are removed when code is compiled in nodebug mode.
777The suit of features include the following.
778
779\begin{itemize}
780\item Static-typed message sends.
781If an actor does not support receiving a given message type, the actor program is rejected at compile time, allowing unsupported messages to never be sent to actors.
782\item Detection of message sends to Finished/Destroyed/Deleted actors.
783All actors have a ticket that assigns them to a respective queue.
784The maximum integer value of the ticket is reserved to indicate that an actor is dead, and subsequent message sends result in an error.
785\item Actors made before the executor can result in undefined behaviour since an executor needs to be created beforehand so it can give out the tickets to actors.
786As such, this is detected and an error is printed.
787\item When an executor is created, the queues are handed out to executor threads in round robin order.
788If there are fewer queues than executor threads, then some workers will spin and never do any work.
789There is no reasonable use case for this behaviour so an error is printed if the number of queues is fewer than the number of executor threads.
790\item A warning is printed when messages are deallocated without being sent.
791Since the @Finished@ allocation status is unused for messages, it is used internally to detect if a message has been sent.
792Deallocating a message without sending it could indicate to a user that they are touching freed memory later, or it could point out extra allocations that could be removed.
793\item Detection of messages sent but not received
794As discussed in Section~\ref{s:executor}, once all actors have terminated shutdown is communicated to executor threads via a status flag. Upon termination the executor threads check their queues to see if any contain messages. If they do, an error is reported. Messages being sent but not received means that their allocation action did not occur and their payload was not delivered. Missing the allocation action can lead to memory leaks and missed payloads can cause unpredictable behaviour. Detecting this can indicate a race or logic error in the user's code.
795\end{itemize}
796
797In addition to these features, \CFA's actor system comes with a suite of statistics that can be toggled on and off.
798These statistics have minimal impact on the actor system's performance since they are counted on a per executor threads basis.
799During shutdown of the actor system they are aggregated, ensuring that the only atomic instructions used by the statistics counting happen at shutdown.
800The statistics measured are as follows.
801
802\begin{description}
803\item[\LstBasicStyle{\textbf{Actors Created}}]
804Actors created.
805Includes both actors made by the main and ones made by other actors.
806\item[\LstBasicStyle{\textbf{Messages Sent}}]
807Messages sent and received.
808Includes termination messages send to the executor threads.
809\item[\LstBasicStyle{\textbf{Gulps}}]
810Gulps that occurred across the executor threads.
811\item[\LstBasicStyle{\textbf{Average Gulp Size}}]
812Average number of messages in a gulped queue.
813\item[\LstBasicStyle{\textbf{Missed gulps}}]
814Occurrences where a worker missed a gulp due to the concurrent queue processing by another worker.
815\item[\LstBasicStyle{\textbf{Steal attempts}}]
816Worker threads attempts to steal work.
817
818\item[\LstBasicStyle{\textbf{Steal failures (no candidates)}}]
819Work stealing failures due to selected victim not having any non empty or non-being-processed queues.
820\item[\LstBasicStyle{\textbf{Steal failures (failed swaps)}}]
821Work stealing failures due to the two stage atomic swap failing.
822\item[\LstBasicStyle{\textbf{Messages stolen}}]
823Aggregate of the number of messages in queues as they were stolen.
824\item[\LstBasicStyle{\textbf{Average steal size}}]
825Average number of messages in a stolen queue.
826\end{description}
827
828These statistics enable a user of \CFA's actor system to make informed choices about how to configure their executor, or how to structure their actor program.
829For example, if there is a lot of messages being stolen relative to the number of messages sent, it could indicate to a user that their workload is heavily imbalanced across executor threads.
830In another example, if the average gulp size is very high, it could indicate that the executor could use more queue sharding.
831
832% C_TODO cite poison pill messages and add languages
833Another productivity feature that is included is a group of poison-pill messages.
834Poison-pill messages are common across actor systems, including Akka and ProtoActor \cite{}.
835Poison-pill messages inform an actor to terminate.
836In \CFA, due to the allocation of actors and lack of garbage collection, there needs to be a suite of poison-pills.
837The messages that \CFA provides are @DeleteMsg@, @DestroyMsg@, and @FinishedMsg@.
838These messages are supported on all actor types via inheritance and when sent to an actor, the actor takes the corresponding allocation action after receiving the message.
839Note that any pending messages to the actor will still be sent.
840It is still the user's responsibility to ensure that an actor does not receive any messages after termination.
841
842\section{Performance}\label{s:actor_perf}
843\CAP{I will update the figures to have the larger font size and different line markers once we start editing this chapter.}
844The performance of \CFA's actor system is tested using a suite of microbenchmarks, and compared with other actor systems.
845Most of the benchmarks are the same as those presented in \ref{}, with a few additions.
846% C_TODO cite actor paper
847At the time of this work the versions of the actor systems are as follows.
848\CFA 1.0, \uC 7.0.0, Akka Typed 2.7.0, CAF 0.18.6, and ProtoActor-Go v0.0.0-20220528090104-f567b547ea07.
849Akka Classic is omitted as Akka Typed is their newest version and seems to be the direction they are headed in.
850The experiments are run on
851\begin{list}{\arabic{enumi}.}{\usecounter{enumi}\topsep=5pt\parsep=5pt\itemsep=0pt}
852\item
853Supermicro SYS--6029U--TR4 Intel Xeon Gold 5220R 24--core socket, hyper-threading $\times$ 2 sockets (48 process\-ing units) 2.2GHz, running Linux v5.8.0--59--generic
854\item
855Supermicro AS--1123US--TR4 AMD EPYC 7662 64--core socket, hyper-threading $\times$ 2 sockets (256 processing units) 2.0 GHz, running Linux v5.8.0--55--generic
856\end{list}
857
858The benchmarks are run on up to 48 cores.
859On the Intel, when going beyond 24 cores there is the choice to either hop sockets or to use hyperthreads.
860Either choice will cause a blip in performance trends, which can be seen in the following performance figures.
861On the Intel the choice was made to hyperthread instead of hopping sockets for experiments with more than 24 cores.
862
863All benchmarks presented are run 5 times and the median is taken.
864Error bars showing the 95\% confidence intervals are drawn on each point on the graphs.
865If the confidence bars are small enough, they may be obscured by the point.
866In this section \uC will be compared to \CFA frequently, as the actor system in \CFA was heavily based off \uC's actor system.
867As such the performance differences that arise are largely due to the contributions of this work.
868
869\begin{table}[t]
870\centering
871\setlength{\extrarowheight}{2pt}
872\setlength{\tabcolsep}{5pt}
873
874\caption{Static Actor/Message Performance: message send, program memory}
875\label{t:StaticActorMessagePerformance}
876\begin{tabular}{*{5}{r|}r}
877        & \multicolumn{1}{c|}{\CFA (100M)} & \multicolumn{1}{c|}{CAF (10M)} & \multicolumn{1}{c|}{Akka (100M)} & \multicolumn{1}{c|}{\uC (100M)} & \multicolumn{1}{c@{}}{ProtoActor (100M)} \\
878        \hline
879        AMD             & \input{data/pykeSendStatic} \\
880        \hline
881        Intel   & \input{data/nasusSendStatic}
882\end{tabular}
883
884\bigskip
885
886\caption{Dynamic Actor/Message Performance: message send, program memory}
887\label{t:DynamicActorMessagePerformance}
888
889\begin{tabular}{*{5}{r|}r}
890        & \multicolumn{1}{c|}{\CFA (20M)} & \multicolumn{1}{c|}{CAF (2M)} & \multicolumn{1}{c|}{Akka (2M)} & \multicolumn{1}{c|}{\uC (20M)} & \multicolumn{1}{c@{}}{ProtoActor (2M)} \\
891        \hline
892        AMD             & \input{data/pykeSendDynamic} \\
893        \hline
894        Intel   & \input{data/nasusSendDynamic}
895\end{tabular}
896\end{table}
897
898\subsection{Message Sends}
899Message sending is the key component of actor communication.
900As such latency of a single message send is the fundamental unit of fast-path performance for an actor system.
901The following two microbenchmarks evaluate the average latency for a static actor/message send and a dynamic actor/message send.
902Static and dynamic refer to the allocation of the message and actor.
903In the static send benchmark a message and actor are allocated once and then the message is sent to the same actor repeatedly until it has been sent 100 million (100M) times.
904The average latency per message send is then calculated by dividing the duration by the number of sends.
905This benchmark evaluates the cost of message sends in the actor use case where all actors and messages are allocated ahead of time and do not need to be created dynamically during execution.
906The CAF static send benchmark only sends a message 10M times to avoid extensively long run times.
907
908In the dynamic send benchmark the same experiment is performed, with the change that with each send a new actor and message is allocated.
909This evaluates the cost of message sends in the other common actor pattern where actors and message are created on the fly as the actor program tackles a workload of variable or unknown size.
910Since dynamic sends are more expensive, this benchmark repeats the actor/message creation and send 20M times (\uC, \CFA), or 2M times (Akka, CAF, ProtoActor), to give an appropriate benchmark duration.
911
912The results from the static/dynamic send benchmarks are shown in Figures~\ref{t:StaticActorMessagePerformance} and \ref{t:DynamicActorMessagePerformance} respectively.
913\CFA leads the charts in both benchmarks, largely due to the copy queue removing the majority of the envelope allocations.
914In the static send benchmark all systems except CAF have static send costs that are in the same ballpark, only varying by ~70ns.
915In the dynamic send benchmark all systems experience slower message sends, as expected due to the extra allocations.
916However, Akka and ProtoActor, slow down by a more significant margin than the \uC and \CFA.
917This is likely a result of Akka and ProtoActor's garbage collection, which can suffer from hits in performance for allocation heavy workloads, whereas \uC and \CFA have explicit allocation/deallocation.
918
919\subsection{Work Stealing}
920\CFA's actor system has a work stealing mechanism which uses the longest victim heuristic, introduced in Section~ref{s:victimSelect}.
921In this performance section, \CFA with the longest victim heuristic is compared with other actor systems on the benchmark suite, and is separately compared with vanilla non-stealing \CFA and \CFA with randomized work stealing.
922
923\begin{figure}
924        \centering
925        \subfloat[AMD \CFA Balance-One Benchmark]{
926                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFABalance-One.pgf}}
927                \label{f:BalanceOneAMD}
928        }
929        \subfloat[Intel \CFA Balance-One Benchmark]{
930                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFABalance-One.pgf}}
931                \label{f:BalanceOneIntel}
932        }
933        \caption{The balance-one benchmark comparing stealing heuristics (lower is better).}
934\end{figure}
935
936\begin{figure}
937        \centering
938        \subfloat[AMD \CFA Balance-Multi Benchmark]{
939                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFABalance-Multi.pgf}}
940                \label{f:BalanceMultiAMD}
941        }
942        \subfloat[Intel \CFA Balance-Multi Benchmark]{
943                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFABalance-Multi.pgf}}
944                \label{f:BalanceMultiIntel}
945        }
946        \caption{The balance-multi benchmark comparing stealing heuristics (lower is better).}
947\end{figure}
948
949There are two benchmarks in which \CFA's work stealing is solely evaluated.
950The main goal of introducing work stealing to \CFA's actor system is to eliminate the pathological unbalanced cases that can present themselves in a system without some form of load balancing.
951The following two microbenchmarks construct two such pathological cases, and compare the work stealing variations of \CFA.
952The balance benchmarks adversarially takes advantage of the round robin assignment of actors to load all actors that will do work on specific cores and create 'dummy' actors that terminate after a single message send on all other cores.
953The workload on the loaded cores is the same as the executor benchmark described in \ref{s:executorPerf}, but with fewer rounds.
954The balance-one benchmark loads all the work on a single core, whereas the balance-multi loads all the work on half the cores (every other core).
955Given this layout, one expects the ideal speedup of work stealing in the balance-one case to be $N / N - 1$ where $N$ is the number of threads.
956In the balance-multi case the ideal speedup is 0.5.
957Note that in the balance-one benchmark the workload is fixed so decreasing runtime is expected.
958In the balance-multi experiment, the workload increases with the number of cores so an increasing or constant runtime is expected.
959
960On both balance microbenchmarks slightly less than ideal speedup compared to the non stealing variation is achieved by both the random and longest victim stealing heuristics.
961On the balance-multi benchmark \ref{f:BalanceMultiAMD},\ref{f:BalanceMultiIntel} the random heuristic outperforms the longest victim.
962This is likely a result of the longest victim heuristic having a higher stealing cost as it needs to maintain timestamps and look at all timestamps before stealing.
963Additionally, a performance cost can be observed when hyperthreading kicks in in Figure~\ref{f:BalanceMultiIntel}.
964
965In the balance-one benchmark on AMD \ref{f:BalanceOneAMD}, the performance bottoms out at 32 cores onwards likely due to the amount of work becoming less than the cost to steal it and move it across cores and cache.
966On Intel \ref{f:BalanceOneIntel}, above 32 cores the performance gets worse for all variants due to hyperthreading.
967Note that the non stealing variation of balance-one will slow down marginally as the cores increase due to having to create more dummy actors on the inactive cores during startup.
968
969\subsection{Executor}\label{s:executorPerf}
970The microbenchmarks in this section are designed to stress the executor.
971The executor is the scheduler of an actor system and is responsible for organizing the interaction of executor threads to service the needs of a workload.
972In the executor benchmark, 40'000 actors are created and assigned a group.
973Each group of actors is a group of 100 actors who send and receive 100 messages from all other actors in their group.
974Each time an actor completes all their sends and receives, they are done a round.
975After all groups have completed 400 rounds the system terminates.
976This microbenchmark is designed to flood the executor with a large number of messages flowing between actors.
977Given there is no work associated with each message, other than sending more messages, the intended bottleneck of this experiment is the executor message send process.
978
979\begin{figure}
980        \centering
981        \subfloat[AMD Executor Benchmark]{
982                \resizebox{0.5\textwidth}{!}{\input{figures/nasusExecutor.pgf}}
983                \label{f:ExecutorAMD}
984        }
985        \subfloat[Intel Executor Benchmark]{
986                \resizebox{0.5\textwidth}{!}{\input{figures/pykeExecutor.pgf}}
987                \label{f:ExecutorIntel}
988        }
989        \caption{The executor benchmark comparing actor systems (lower is better).}
990\end{figure}
991
992The results of the executor benchmark in Figures~\ref{f:ExecutorIntel} and \ref{f:ExecutorAMD} show \CFA with the lowest runtime relative to its peers.
993The difference in runtime between \uC and \CFA is largely due to the usage of the copy queue described in Section~\ref{s:copyQueue}.
994The copy queue both reduces and consolidates allocations, heavily reducing contention on the memory allocator.
995Additionally, due to the static typing in \CFA's actor system, it is able to get rid of expensive dynamic casts that occur in \uC to discriminate messages by type.
996Note that dynamic casts are usually not very expensive, but relative to the high performance of the rest of the implementation of the \uC actor system, the cost is significant.
997
998\begin{figure}
999        \centering
1000        \subfloat[AMD \CFA Executor Benchmark]{
1001                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFAExecutor.pgf}}
1002                \label{f:cfaExecutorAMD}
1003        }
1004        \subfloat[Intel \CFA Executor Benchmark]{
1005                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFAExecutor.pgf}}
1006                \label{f:cfaExecutorIntel}
1007        }
1008        \caption{Executor benchmark comparing \CFA stealing heuristics (lower is better).}
1009\end{figure}
1010
1011When comparing the \CFA stealing heuristics in Figure~\ref{f:cfaExecutorAMD} it can be seen that the random heuristic falls slightly behind the other two, but in Figure~\ref{f:cfaExecutorIntel} the runtime of all heuristics are nearly identical to each other.
1012
1013\begin{figure}
1014        \centering
1015        \subfloat[AMD Repeat Benchmark]{
1016                \resizebox{0.5\textwidth}{!}{\input{figures/nasusRepeat.pgf}}
1017                \label{f:RepeatAMD}
1018        }
1019        \subfloat[Intel Repeat Benchmark]{
1020                \resizebox{0.5\textwidth}{!}{\input{figures/pykeRepeat.pgf}}
1021                \label{f:RepeatIntel}
1022        }
1023        \caption{The repeat benchmark comparing actor systems (lower is better).}
1024\end{figure}
1025
1026The repeat microbenchmark also evaluates the executor.
1027It stresses the executor's ability to withstand contention on queues, as it repeatedly fans out messages from a single client to 100000 servers who then all respond to the client.
1028After this scatter and gather repeats 200 times the benchmark terminates.
1029The messages from the servers to the client will likely all come in on the same queue, resulting in high contention.
1030As such this benchmark will not scale with the number of processors, since more processors will result in higher contention.
1031In Figure~\ref{f:RepeatAMD} we can see that \CFA performs well compared to \uC, however by less of a margin than the executor benchmark.
1032One factor in this result is that the contention on the queues poses a significant bottleneck.
1033As such the gains from using the copy queue are much less apparent.
1034
1035\begin{figure}
1036        \centering
1037        \subfloat[AMD \CFA Repeat Benchmark]{
1038                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFARepeat.pgf}}
1039                \label{f:cfaRepeatAMD}
1040        }
1041        \subfloat[Intel \CFA Repeat Benchmark]{
1042                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFARepeat.pgf}}
1043                \label{f:cfaRepeatIntel}
1044        }
1045        \caption{The repeat benchmark comparing \CFA stealing heuristics (lower is better).}
1046\end{figure}
1047
1048In Figure~\ref{f:RepeatIntel} \uC and \CFA are very comparable.
1049In comparison with the other systems \uC does well on the repeat benchmark since it does not have work stealing.
1050The client of this experiment is long running and maintains a lot of state, as it needs to know the handles of all the servers.
1051When stealing the client or its respective queue (in \CFA's inverted model), moving the client incurs a high cost due to cache invalidation.
1052As such stealing the client can result in a hit in performance.
1053
1054This result is shown in Figure~\ref{f:cfaRepeatAMD} and \ref{f:cfaRepeatIntel} where the no-stealing version of \CFA performs better than both stealing variations.
1055In particular on the Intel machine in Figure~\ref{f:cfaRepeatIntel}, the cost of stealing is higher, which can be seen in the vertical shift of Akka, CAF and CFA results in Figure~\ref{f:RepeatIntel} (\uC and ProtoActor do not have work stealing).
1056The shift for CAF is particularly large, which further supports the hypothesis that CAF's work stealing is particularly eager.
1057In both the executor and the repeat benchmark CAF performs poorly.
1058It is hypothesized that CAF has an aggressive work stealing algorithm, that eagerly attempts to steal.
1059This results in poor performance in benchmarks with small messages containing little work per message.
1060On the other hand, in \ref{f:MatrixAMD} CAF performs much better since each message has a large amount of work, and few messages are sent, so the eager work stealing allows for the clean up of loose ends to occur faster.
1061This hypothesis stems from experimentation with \CFA.
1062CAF uses a randomized work stealing heuristic.
1063In \CFA if the system is tuned so that it steals work much more eagerly with a randomized it was able to replicate the results that CAF achieves in the matrix benchmark, but this tuning performed much worse on all other microbenchmarks that we present, since they all perform a small amount of work per message.
1064
1065\begin{table}[t]
1066        \centering
1067        \setlength{\extrarowheight}{2pt}
1068        \setlength{\tabcolsep}{5pt}
1069
1070        \caption{Executor Program Memory High Watermark}
1071        \label{t:ExecutorMemory}
1072        \begin{tabular}{*{5}{r|}r}
1073                & \multicolumn{1}{c|}{\CFA} & \multicolumn{1}{c|}{CAF} & \multicolumn{1}{c|}{Akka} & \multicolumn{1}{c|}{\uC} & \multicolumn{1}{c@{}}{ProtoActor} \\
1074                \hline
1075                AMD             & \input{data/pykeExecutorMem} \\
1076                \hline
1077                Intel   & \input{data/nasusExecutorMem}
1078        \end{tabular}
1079\end{table}
1080
1081Figure~\ref{t:ExecutorMemory} shows the high memory watermark of the actor systems when running the executor benchmark on 48 cores.
1082\CFA has a high watermark relative to the other non-garbage collected systems \uC, and CAF.
1083This is a result of the copy queue data structure, as it will over-allocate storage and not clean up eagerly, whereas the per envelope allocations will always allocate exactly the amount of storage needed.
1084
1085\subsection{Matrix Multiply}
1086The matrix benchmark evaluates the actor systems in a practical application, where actors concurrently multiplies two matrices.
1087The majority of the computation in this benchmark involves computing the final matrix, so this benchmark stresses the actor systems' ability to have actors run work, rather than stressing the executor or message sending system.
1088
1089Given $Z_{m,r} = X_{m,n} \cdot Y_{n,r}$, the matrix multiply is defined as:
1090\begin{displaymath}
1091X_{i,j} \cdot Y_{j,k} = \left( \sum_{c=1}^{j} X_{row,c}Y_{c,column} \right)_{i,k}
1092\end{displaymath}
1093
1094The benchmark uses input matrices $X$ and $Y$ that are both $3072$ by $3072$ in size.
1095An actor is made for each row of $X$ and is passed via message the information needed to calculate a row of the result matrix $Z$.
1096
1097
1098Given that the bottleneck of the benchmark is the computation of the result matrix, it follows that the results in Figures~\ref{f:MatrixAMD} and \ref{f:MatrixIntel} are clustered closer than other experiments.
1099In Figure~\ref{f:MatrixAMD} \uC and \CFA have identical performance and in Figure~\ref{f:MatrixIntel} \uC pulls ahead of \CFA after 24 cores likely due to costs associated with work stealing while hyperthreading.
1100As mentioned in \ref{s:executorPerf}, it is hypothesized that CAF performs better in this benchmark compared to others due to its eager work stealing implementation.
1101In Figures~\ref{f:cfaMatrixAMD} and \ref{f:cfaMatrixIntel} there is little negligible performance difference across \CFA stealing heuristics.
1102
1103\begin{figure}
1104        \centering
1105        \subfloat[AMD Matrix Benchmark]{
1106                \resizebox{0.5\textwidth}{!}{\input{figures/nasusMatrix.pgf}}
1107                \label{f:MatrixAMD}
1108        }
1109        \subfloat[Intel Matrix Benchmark]{
1110                \resizebox{0.5\textwidth}{!}{\input{figures/pykeMatrix.pgf}}
1111                \label{f:MatrixIntel}
1112        }
1113        \caption{The matrix benchmark comparing actor systems (lower is better).}
1114\end{figure}
1115
1116\begin{figure}
1117        \centering
1118        \subfloat[AMD \CFA Matrix Benchmark]{
1119                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFAMatrix.pgf}}
1120                \label{f:cfaMatrixAMD}
1121        }
1122        \subfloat[Intel \CFA Matrix Benchmark]{
1123                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFAMatrix.pgf}}
1124                \label{f:cfaMatrixIntel}
1125        }
1126        \caption{The matrix benchmark comparing \CFA stealing heuristics (lower is better).}
1127\end{figure}
1128
1129% Local Variables: %
1130% tab-width: 4 %
1131% End: %
Note: See TracBrowser for help on using the repository browser.